niceeval 0.16.2-canary.98 → 0.16.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.
Files changed (40) hide show
  1. package/dist/inspection/facts.cjs +86 -31
  2. package/dist/inspection/facts.cjs.map +1 -1
  3. package/dist/inspection/facts.d.cts +2 -2
  4. package/dist/inspection/facts.d.mts +2 -2
  5. package/dist/inspection/facts.d.ts +2 -2
  6. package/dist/inspection/overview.cjs +2 -1
  7. package/dist/inspection/overview.cjs.map +1 -1
  8. package/dist/inspection/project-source.cjs +28 -19
  9. package/dist/inspection/project-source.cjs.map +1 -1
  10. package/dist/inspection/protocol.d.cts +17 -17
  11. package/dist/inspection/protocol.d.mts +17 -17
  12. package/dist/inspection/protocol.d.ts +17 -17
  13. package/dist/inspection/select.cjs +10 -6
  14. package/dist/inspection/select.cjs.map +1 -1
  15. package/dist/inspection/source.cjs +4 -2
  16. package/dist/inspection/source.cjs.map +1 -1
  17. package/dist/inspection/source.d.cts +1 -0
  18. package/dist/inspection/source.d.mts +1 -0
  19. package/dist/inspection/source.d.ts +1 -0
  20. package/dist/record/sqlite/database.cjs +2 -8
  21. package/dist/record/sqlite/database.cjs.map +1 -1
  22. package/dist/record/sqlite/index.cjs +13 -11
  23. package/dist/record/sqlite/index.cjs.map +1 -1
  24. package/dist/record/sqlite/index.d.cts +4 -2
  25. package/dist/record/sqlite/index.d.mts +4 -2
  26. package/dist/record/sqlite/index.d.ts +4 -2
  27. package/dist/record/sqlite/storage.cjs +118 -64
  28. package/dist/record/sqlite/storage.cjs.map +1 -1
  29. package/dist/record/sqlite/storage.d.cts +12 -5
  30. package/dist/record/sqlite/storage.d.mts +12 -5
  31. package/dist/record/sqlite/storage.d.ts +12 -5
  32. package/dist/record/sqlite/storage.js +48 -44
  33. package/dist/record/sqlite/types.cjs.map +1 -1
  34. package/dist/record/sqlite/types.d.cts +1 -1
  35. package/dist/record/sqlite/types.d.mts +1 -1
  36. package/dist/record/sqlite/types.d.ts +1 -1
  37. package/dist/view/cli/contribution.cjs +3 -2
  38. package/dist/view/cli/contribution.cjs.map +1 -1
  39. package/dist/view/function-runtime.mjs +251 -464
  40. package/package.json +1 -1
@@ -87,6 +87,7 @@ function emptyOperationalFacts() {
87
87
  return Object.freeze({
88
88
  kind: "project-record",
89
89
  cutoff: () => EMPTY_OPERATIONAL_CUTOFF,
90
+ findExperimentRunIds: () => Object.freeze([]),
90
91
  readRunResource: () => undefined,
91
92
  readSealedRunSummaryPage: (afterRunId = "", _pageSize = 100, expectedCutoffIdentity) => {
92
93
  if (expectedCutoffIdentity !== undefined && expectedCutoffIdentity !== EMPTY_OPERATIONAL_CUTOFF.identity) {
@@ -137,11 +138,12 @@ function sessionFacts(session, kind) {
137
138
  const readPage = (afterRunId = "", pageSize = 100, expectedCutoffIdentity) => remember(session.readSealedRunSummaryPage(afterRunId, pageSize, expectedCutoffIdentity ?? observedCutoff?.identity));
138
139
  return Object.freeze({
139
140
  kind,
140
- cutoff: () => observedCutoff ?? readPage("", 1).cutoff,
141
+ cutoff: () => observedCutoff ??= session.sealedCutoff(),
142
+ findExperimentRunIds: session.findExperimentRunIds,
141
143
  readRunResource: (runId) => session.readRunResource(runId),
142
144
  readSealedRunSummaryPage: readPage,
143
145
  findAttemptLocatorCandidates: (locator, maximumCandidateRuns) => session.findAttemptLocatorCandidates(locator, maximumCandidateRuns),
144
- readSealedRunCore: (runId) => session.readSealedRunCore(runId),
146
+ readSealedRunCore: (runId) => session.readSealedRunCore(runId, true),
145
147
  readContentPage: (contentId, afterOrdinal, pageSize) => session.readContentChunkPage(contentId, afterOrdinal, pageSize),
146
148
  readCollectionPage: (attachmentId, afterOrdinal, pageSize) => session.readCollectionItemPage(attachmentId, afterOrdinal, pageSize),
147
149
  });
@@ -1 +1 @@
1
- {"version":3,"file":"source.js","sourceRoot":"","sources":["source.ts"],"names":[],"mappings":";;;AA4CA,kEAKC;AACD,4DAKC;AAMD,oDA2BC;AAED,sEAQC;A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,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,iCAAiC;QAClF,KAAK;KACR,CAAC,CAAC;AACP,CAAC","sourcesContent":["// @concord-file ne-eval-inspection-source\n// @concord-implements docs/feature/inspection/README.md\n// @concord-implements docs/feature/inspection/architecture.md\n// @concord-implements docs/feature/insight/README.md\nimport { existsSync } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\nimport { Data, Effect } from \"effect\";\nimport type * as Scope from \"effect/Scope\";\nimport { RecordIntegrityFailure } from \"../record/reader/errors.ts\";\nimport { EMPTY_PUBLICATION_CUTOFF_IDENTITY } from \"../run/protocol.ts\";\nimport { openHostOwnedRecordReadSession, acquireProjectRecordReadSession, RECORD_SQLITE_VALIDATION_DEADLINE_MS, type AttemptLocatorCandidates, type CollectionItemPage, type ContentChunkPage, type PinnedRecordReadSession, type SealedRunCore, type SealedRunCutoff, type SealedRunSummaryPage, } from \"../record/sqlite/index.ts\";\nimport { startExternalRecordImport } from \"../record/sqlite/external-record-import.ts\";\nimport type { ReadableRunResource } from \"../run/storage/types.ts\";\nexport type InspectionSource = {\n readonly kind: \"project-record\";\n readonly databasePath: string;\n} | {\n readonly kind: \"external-record\";\n readonly recordPath: string;\n};\nexport class InspectionSourceError extends Data.TaggedError(\"InspectionSourceError\")<{\n readonly code: \"inspection-source-invalid\";\n readonly reason: string;\n readonly cause?: unknown;\n}> {\n}\n/** Safe Inspection identity for a Record publication that is not closed. */\nexport class InspectionIntegrityError extends Data.TaggedError(\"InspectionIntegrityError\")<{\n readonly code: \"inspection-record-integrity-failure\";\n readonly runId: string;\n}> {\n}\n/** Browser-neutral fixed reader capability backed by one pinned Record generation. */\nexport interface InspectionFactSource {\n readonly kind: InspectionSource[\"kind\"];\n readonly cutoff: () => SealedRunCutoff;\n readonly readRunResource: (runId: string) => ReadableRunResource | undefined;\n readonly readSealedRunSummaryPage: (afterRunId?: string, pageSize?: number, expectedCutoffIdentity?: string) => SealedRunSummaryPage;\n readonly findAttemptLocatorCandidates: (locator: string, maximumCandidateRuns: number) => AttemptLocatorCandidates;\n readonly readSealedRunCore: (runId: string) => SealedRunCore | undefined;\n readonly readContentPage: (contentId: string, afterOrdinal: number, pageSize: number) => ContentChunkPage;\n readonly readCollectionPage: (attachmentId: string, afterOrdinal: number, pageSize: number) => CollectionItemPage;\n}\n/** Pure source selection; opening and validation happen only inside a Scope. */\nexport function operationalInspectionSource(cwd: string): InspectionSource {\n return Object.freeze({\n kind: \"project-record\" as const,\n databasePath: resolve(cwd, \".niceeval/record.sqlite\"),\n });\n}\nexport function externalInspectionSource(cwd: string, pathname: string): InspectionSource {\n return Object.freeze({\n kind: \"external-record\" as const,\n recordPath: resolve(cwd, pathname),\n });\n}\n/**\n * Acquires exactly one pinned Record reader. Every fixed operation in the\n * returned source sees the same generation, and Scope closes the session on\n * success, typed failure, defect, or interruption.\n */\nexport function openInspectionSource(source: InspectionSource): Effect.Effect<InspectionFactSource, InspectionSourceError | InspectionIntegrityError, Scope.Scope> {\n return Effect.gen(function* () {\n let session: PinnedRecordReadSession;\n if (source.kind === \"project-record\") {\n if (!existsSync(source.databasePath))\n return emptyOperationalFacts();\n session = yield* acquireProjectRecordReadSession(dirname(source.databasePath)).pipe(Effect.mapError(sourceError));\n }\n else {\n const importDeadline = Date.now() + RECORD_SQLITE_VALIDATION_DEADLINE_MS;\n const importer = yield* Effect.acquireRelease(Effect.try({\n try: () => startExternalRecordImport(source.recordPath, importDeadline),\n catch: (cause) => sourceError(cause),\n }), (handle) => Effect.promise(() => handle.close().catch(() => undefined)));\n const generation = yield* Effect.tryPromise({\n // Declaring the AbortSignal keeps this await interruptible. Scope then\n // terminates the Worker and removes its private generation.\n try: (_signal) => importer.result,\n catch: (cause) => sourceError(cause),\n });\n session = yield* Effect.acquireRelease(Effect.try({\n try: () => openHostOwnedRecordReadSession(generation.path),\n catch: (cause) => sourceError(cause),\n }), (opened) => Effect.sync(() => opened.close()));\n }\n return sessionFacts(session, source.kind);\n });\n}\n/** Opens one already-imported private generation without accepting a public path. */\nexport function openHostOwnedInspectionSource(recordPath: string): Effect.Effect<InspectionFactSource, InspectionSourceError | InspectionIntegrityError, Scope.Scope> {\n return Effect.gen(function* () {\n const session = yield* Effect.acquireRelease(Effect.try({\n try: () => openHostOwnedRecordReadSession(recordPath),\n catch: (cause) => sourceError(cause),\n }), (opened) => Effect.sync(() => opened.close()));\n return sessionFacts(session, \"external-record\");\n });\n}\nconst EMPTY_OPERATIONAL_CUTOFF = Object.freeze({\n identity: EMPTY_PUBLICATION_CUTOFF_IDENTITY,\n runCount: 0,\n});\nfunction emptyOperationalFacts(): InspectionFactSource {\n return Object.freeze({\n kind: \"project-record\" as const,\n cutoff: () => EMPTY_OPERATIONAL_CUTOFF,\n readRunResource: () => undefined,\n readSealedRunSummaryPage: (afterRunId = \"\", _pageSize = 100, expectedCutoffIdentity?: string) => {\n if (expectedCutoffIdentity !== undefined && expectedCutoffIdentity !== EMPTY_OPERATIONAL_CUTOFF.identity) {\n throw new InspectionSourceError({\n code: \"inspection-source-invalid\",\n reason: \"The empty operational publication cutoff changed; restart pagination.\",\n });\n }\n return Object.freeze({\n cutoff: EMPTY_OPERATIONAL_CUTOFF,\n afterRunId,\n summaries: Object.freeze([]),\n nextAfterRunId: null,\n });\n },\n findAttemptLocatorCandidates: (locator: string) => Object.freeze({\n locator,\n ambiguous: false,\n candidates: Object.freeze([]),\n }),\n readSealedRunCore: () => undefined,\n readContentPage: (contentId: string, afterOrdinal: number) => Object.freeze({\n contentId,\n afterOrdinal,\n chunks: Object.freeze([]),\n nextOrdinal: null,\n }),\n readCollectionPage: (attachmentId: string, afterOrdinal: number) => Object.freeze({\n attachmentId,\n afterOrdinal,\n items: Object.freeze([]),\n nextOrdinal: null,\n }),\n });\n}\nfunction sessionFacts(session: PinnedRecordReadSession, kind: InspectionSource[\"kind\"]): InspectionFactSource {\n let observedCutoff: SealedRunCutoff | undefined;\n const remember = (page: SealedRunSummaryPage): SealedRunSummaryPage => {\n if (observedCutoff !== undefined && observedCutoff.identity !== page.cutoff.identity) {\n throw new InspectionSourceError({\n code: \"inspection-source-invalid\",\n reason: \"Pinned Record session changed its sealed cutoff.\",\n });\n }\n observedCutoff = page.cutoff;\n return page;\n };\n const readPage = (afterRunId = \"\", pageSize = 100, expectedCutoffIdentity?: string): SealedRunSummaryPage => remember(session.readSealedRunSummaryPage(afterRunId, pageSize, expectedCutoffIdentity ?? observedCutoff?.identity));\n return Object.freeze({\n kind,\n cutoff: () => observedCutoff ?? readPage(\"\", 1).cutoff,\n readRunResource: (runId: string) => session.readRunResource(runId),\n readSealedRunSummaryPage: readPage,\n findAttemptLocatorCandidates: (locator: string, maximumCandidateRuns: number) => session.findAttemptLocatorCandidates(locator, maximumCandidateRuns),\n readSealedRunCore: (runId: string) => session.readSealedRunCore(runId),\n readContentPage: (contentId: string, afterOrdinal: number, pageSize: number) => session.readContentChunkPage(contentId, afterOrdinal, pageSize),\n readCollectionPage: (attachmentId: string, afterOrdinal: number, pageSize: number) => session.readCollectionItemPage(attachmentId, afterOrdinal, pageSize),\n });\n}\nfunction sourceError(cause: unknown): InspectionSourceError | InspectionIntegrityError {\n if (cause instanceof RecordIntegrityFailure) {\n return new InspectionIntegrityError({\n code: \"inspection-record-integrity-failure\",\n runId: cause.runId,\n });\n }\n return new InspectionSourceError({\n code: \"inspection-source-invalid\",\n reason: cause instanceof Error ? cause.message : \"Record source validation failed\",\n cause,\n });\n}\n"]}
1
+ {"version":3,"file":"source.js","sourceRoot":"","sources":["source.ts"],"names":[],"mappings":";;;AA6CA,kEAKC;AACD,4DAKC;AAMD,oDA2BC;AAED,sEAQC;AAnGD,0CAA0C;AAC1C,wDAAwD;AACxD,8DAA8D;AAC9D,qDAAqD;AACrD,qCAAqC;AACrC,yCAA6C;AAC7C,mCAAsC;AAEtC,0DAAoE;AACpE,oDAAuE;AACvE,wDAAqU;AACrU,0FAAuF;AASvF,MAAa,qBAAsB,SAAQ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iC;QAClF,KAAK;KACR,CAAC,CAAC;AACP,CAAC","sourcesContent":["// @concord-file ne-eval-inspection-source\n// @concord-implements docs/feature/inspection/README.md\n// @concord-implements docs/feature/inspection/architecture.md\n// @concord-implements docs/feature/insight/README.md\nimport { existsSync } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\nimport { Data, Effect } from \"effect\";\nimport type * as Scope from \"effect/Scope\";\nimport { RecordIntegrityFailure } from \"../record/reader/errors.ts\";\nimport { EMPTY_PUBLICATION_CUTOFF_IDENTITY } from \"../run/protocol.ts\";\nimport { openHostOwnedRecordReadSession, acquireProjectRecordReadSession, RECORD_SQLITE_VALIDATION_DEADLINE_MS, type AttemptLocatorCandidates, type CollectionItemPage, type ContentChunkPage, type PinnedRecordReadSession, type SealedRunCore, type SealedRunCutoff, type SealedRunSummaryPage, } from \"../record/sqlite/index.ts\";\nimport { startExternalRecordImport } from \"../record/sqlite/external-record-import.ts\";\nimport type { ReadableRunResource } from \"../run/storage/types.ts\";\nexport type InspectionSource = {\n readonly kind: \"project-record\";\n readonly databasePath: string;\n} | {\n readonly kind: \"external-record\";\n readonly recordPath: string;\n};\nexport class InspectionSourceError extends Data.TaggedError(\"InspectionSourceError\")<{\n readonly code: \"inspection-source-invalid\";\n readonly reason: string;\n readonly cause?: unknown;\n}> {\n}\n/** Safe Inspection identity for a Record publication that is not closed. */\nexport class InspectionIntegrityError extends Data.TaggedError(\"InspectionIntegrityError\")<{\n readonly code: \"inspection-record-integrity-failure\";\n readonly runId: string;\n}> {\n}\n/** Browser-neutral fixed reader capability backed by one pinned Record generation. */\nexport interface InspectionFactSource {\n readonly kind: InspectionSource[\"kind\"];\n readonly cutoff: () => SealedRunCutoff;\n readonly findExperimentRunIds: (experimentId: string) => readonly string[];\n readonly readRunResource: (runId: string) => ReadableRunResource | undefined;\n readonly readSealedRunSummaryPage: (afterRunId?: string, pageSize?: number, expectedCutoffIdentity?: string) => SealedRunSummaryPage;\n readonly findAttemptLocatorCandidates: (locator: string, maximumCandidateRuns: number) => AttemptLocatorCandidates;\n readonly readSealedRunCore: (runId: string) => SealedRunCore | undefined;\n readonly readContentPage: (contentId: string, afterOrdinal: number, pageSize: number) => ContentChunkPage;\n readonly readCollectionPage: (attachmentId: string, afterOrdinal: number, pageSize: number) => CollectionItemPage;\n}\n/** Pure source selection; opening and validation happen only inside a Scope. */\nexport function operationalInspectionSource(cwd: string): InspectionSource {\n return Object.freeze({\n kind: \"project-record\" as const,\n databasePath: resolve(cwd, \".niceeval/record.sqlite\"),\n });\n}\nexport function externalInspectionSource(cwd: string, pathname: string): InspectionSource {\n return Object.freeze({\n kind: \"external-record\" as const,\n recordPath: resolve(cwd, pathname),\n });\n}\n/**\n * Acquires exactly one pinned Record reader. Every fixed operation in the\n * returned source sees the same generation, and Scope closes the session on\n * success, typed failure, defect, or interruption.\n */\nexport function openInspectionSource(source: InspectionSource): Effect.Effect<InspectionFactSource, InspectionSourceError | InspectionIntegrityError, Scope.Scope> {\n return Effect.gen(function* () {\n let session: PinnedRecordReadSession;\n if (source.kind === \"project-record\") {\n if (!existsSync(source.databasePath))\n return emptyOperationalFacts();\n session = yield* acquireProjectRecordReadSession(dirname(source.databasePath)).pipe(Effect.mapError(sourceError));\n }\n else {\n const importDeadline = Date.now() + RECORD_SQLITE_VALIDATION_DEADLINE_MS;\n const importer = yield* Effect.acquireRelease(Effect.try({\n try: () => startExternalRecordImport(source.recordPath, importDeadline),\n catch: (cause) => sourceError(cause),\n }), (handle) => Effect.promise(() => handle.close().catch(() => undefined)));\n const generation = yield* Effect.tryPromise({\n // Declaring the AbortSignal keeps this await interruptible. Scope then\n // terminates the Worker and removes its private generation.\n try: (_signal) => importer.result,\n catch: (cause) => sourceError(cause),\n });\n session = yield* Effect.acquireRelease(Effect.try({\n try: () => openHostOwnedRecordReadSession(generation.path),\n catch: (cause) => sourceError(cause),\n }), (opened) => Effect.sync(() => opened.close()));\n }\n return sessionFacts(session, source.kind);\n });\n}\n/** Opens one already-imported private generation without accepting a public path. */\nexport function openHostOwnedInspectionSource(recordPath: string): Effect.Effect<InspectionFactSource, InspectionSourceError | InspectionIntegrityError, Scope.Scope> {\n return Effect.gen(function* () {\n const session = yield* Effect.acquireRelease(Effect.try({\n try: () => openHostOwnedRecordReadSession(recordPath),\n catch: (cause) => sourceError(cause),\n }), (opened) => Effect.sync(() => opened.close()));\n return sessionFacts(session, \"external-record\");\n });\n}\nconst EMPTY_OPERATIONAL_CUTOFF = Object.freeze({\n identity: EMPTY_PUBLICATION_CUTOFF_IDENTITY,\n runCount: 0,\n});\nfunction emptyOperationalFacts(): InspectionFactSource {\n return Object.freeze({\n kind: \"project-record\" as const,\n cutoff: () => EMPTY_OPERATIONAL_CUTOFF,\n findExperimentRunIds: () => Object.freeze([]),\n readRunResource: () => undefined,\n readSealedRunSummaryPage: (afterRunId = \"\", _pageSize = 100, expectedCutoffIdentity?: string) => {\n if (expectedCutoffIdentity !== undefined && expectedCutoffIdentity !== EMPTY_OPERATIONAL_CUTOFF.identity) {\n throw new InspectionSourceError({\n code: \"inspection-source-invalid\",\n reason: \"The empty operational publication cutoff changed; restart pagination.\",\n });\n }\n return Object.freeze({\n cutoff: EMPTY_OPERATIONAL_CUTOFF,\n afterRunId,\n summaries: Object.freeze([]),\n nextAfterRunId: null,\n });\n },\n findAttemptLocatorCandidates: (locator: string) => Object.freeze({\n locator,\n ambiguous: false,\n candidates: Object.freeze([]),\n }),\n readSealedRunCore: () => undefined,\n readContentPage: (contentId: string, afterOrdinal: number) => Object.freeze({\n contentId,\n afterOrdinal,\n chunks: Object.freeze([]),\n nextOrdinal: null,\n }),\n readCollectionPage: (attachmentId: string, afterOrdinal: number) => Object.freeze({\n attachmentId,\n afterOrdinal,\n items: Object.freeze([]),\n nextOrdinal: null,\n }),\n });\n}\nfunction sessionFacts(session: PinnedRecordReadSession, kind: InspectionSource[\"kind\"]): InspectionFactSource {\n let observedCutoff: SealedRunCutoff | undefined;\n const remember = (page: SealedRunSummaryPage): SealedRunSummaryPage => {\n if (observedCutoff !== undefined && observedCutoff.identity !== page.cutoff.identity) {\n throw new InspectionSourceError({\n code: \"inspection-source-invalid\",\n reason: \"Pinned Record session changed its sealed cutoff.\",\n });\n }\n observedCutoff = page.cutoff;\n return page;\n };\n const readPage = (afterRunId = \"\", pageSize = 100, expectedCutoffIdentity?: string): SealedRunSummaryPage => remember(session.readSealedRunSummaryPage(afterRunId, pageSize, expectedCutoffIdentity ?? observedCutoff?.identity));\n return Object.freeze({\n kind,\n cutoff: () => observedCutoff ??= session.sealedCutoff(),\n findExperimentRunIds: session.findExperimentRunIds,\n readRunResource: (runId: string) => session.readRunResource(runId),\n readSealedRunSummaryPage: readPage,\n findAttemptLocatorCandidates: (locator: string, maximumCandidateRuns: number) => session.findAttemptLocatorCandidates(locator, maximumCandidateRuns),\n readSealedRunCore: (runId: string) => session.readSealedRunCore(runId, true),\n readContentPage: (contentId: string, afterOrdinal: number, pageSize: number) => session.readContentChunkPage(contentId, afterOrdinal, pageSize),\n readCollectionPage: (attachmentId: string, afterOrdinal: number, pageSize: number) => session.readCollectionItemPage(attachmentId, afterOrdinal, pageSize),\n });\n}\nfunction sourceError(cause: unknown): InspectionSourceError | InspectionIntegrityError {\n if (cause instanceof RecordIntegrityFailure) {\n return new InspectionIntegrityError({\n code: \"inspection-record-integrity-failure\",\n runId: cause.runId,\n });\n }\n return new InspectionSourceError({\n code: \"inspection-source-invalid\",\n reason: cause instanceof Error ? cause.message : \"Record source validation failed\",\n cause,\n });\n}\n"]}
@@ -31,6 +31,7 @@ export declare class InspectionIntegrityError extends InspectionIntegrityError_b
31
31
  export interface InspectionFactSource {
32
32
  readonly kind: InspectionSource["kind"];
33
33
  readonly cutoff: () => SealedRunCutoff;
34
+ readonly findExperimentRunIds: (experimentId: string) => readonly string[];
34
35
  readonly readRunResource: (runId: string) => ReadableRunResource | undefined;
35
36
  readonly readSealedRunSummaryPage: (afterRunId?: string, pageSize?: number, expectedCutoffIdentity?: string) => SealedRunSummaryPage;
36
37
  readonly findAttemptLocatorCandidates: (locator: string, maximumCandidateRuns: number) => AttemptLocatorCandidates;
@@ -31,6 +31,7 @@ export declare class InspectionIntegrityError extends InspectionIntegrityError_b
31
31
  export interface InspectionFactSource {
32
32
  readonly kind: InspectionSource["kind"];
33
33
  readonly cutoff: () => SealedRunCutoff;
34
+ readonly findExperimentRunIds: (experimentId: string) => readonly string[];
34
35
  readonly readRunResource: (runId: string) => ReadableRunResource | undefined;
35
36
  readonly readSealedRunSummaryPage: (afterRunId?: string, pageSize?: number, expectedCutoffIdentity?: string) => SealedRunSummaryPage;
36
37
  readonly findAttemptLocatorCandidates: (locator: string, maximumCandidateRuns: number) => AttemptLocatorCandidates;
@@ -31,6 +31,7 @@ export declare class InspectionIntegrityError extends InspectionIntegrityError_b
31
31
  export interface InspectionFactSource {
32
32
  readonly kind: InspectionSource["kind"];
33
33
  readonly cutoff: () => SealedRunCutoff;
34
+ readonly findExperimentRunIds: (experimentId: string) => readonly string[];
34
35
  readonly readRunResource: (runId: string) => ReadableRunResource | undefined;
35
36
  readonly readSealedRunSummaryPage: (afterRunId?: string, pageSize?: number, expectedCutoffIdentity?: string) => SealedRunSummaryPage;
36
37
  readonly findAttemptLocatorCandidates: (locator: string, maximumCandidateRuns: number) => AttemptLocatorCandidates;
@@ -516,14 +516,8 @@ function openRecordReaderAfterRuntimeAdmission(path) {
516
516
  db.setAuthorizer(readerAuthorizer);
517
517
  validateExactSchema(connection);
518
518
  requireMigrationReady(connection);
519
- const integrity = currentStatement(db, "PRAGMA quick_check").get();
520
- if (integrity === undefined || decodeText(integrity.quick_check, "quick_check") !== "ok") {
521
- throw (0, errors_ts_1.sqliteError)("record-database-invalid", "open", "ProjectDatabase integrity check failed");
522
- }
523
- const foreignKeyViolation = currentStatement(db, "PRAGMA foreign_key_check").get();
524
- if (foreignKeyViolation !== undefined) {
525
- throw (0, errors_ts_1.sqliteError)("record-database-invalid", "open", "ProjectDatabase foreign key closure is invalid");
526
- }
519
+ // Full structure and closure validation belongs to import, publication and
520
+ // maintenance. Opening a Host-owned reader must not scan historical payload.
527
521
  return connection;
528
522
  }
529
523
  catch (cause) {
@@ -1 +1 @@
1
- {"version":3,"file":"database.js","sourceRoot":"","sources":["database.ts"],"names":[],"mappings":";;;AA4CA,0CAOC;AAsBD,8DAEC;AAQD,4CAOC;AA6DD,oEAkEC;AAmKD,kDAGC;AACD,4CAoFC;AAED,8DAOC;AACD,4CAGC;AACD,8DAGC;AA6CD,sDA2BC;AACD,kDAMC;AACD,4DAKC;AAED,sDA0BC;AAMD,kEA8KC;AA1wBD,6CAAyC;AACzC,qCAA4D;AAC5D,yCAA6D;AAC7D,6CAA+F;AAC/F,2CAAoI;AACpI,2CAA0C;AAC1C,yCAAkF;AAClF,mGAAsH;AACtH,MAAM,YAAY,GAAG,CAAC,EAAE,EAAE,EAAE,EAAE,CAAC,CAAU,CAAC;AAC1C,MAAM,6BAA6B,GAAG,CAAC,EAAE,EAAE,EAAE,EAAE,CAAC,CAAU,CAAC;AAC3D,MAAM,WAAW,GAAG,IAAI,GAAG,CAAC;IACxB,uBAAS,CAAC,aAAa;IACvB,uBAAS,CAAC,aAAa;IACvB,uBAAS,CAAC,aAAa;IACvB,uBAAS,CAAC,aAAa;IACvB,uBAAS,CAAC,aAAa;IACvB,uBAAS,CAAC,mBAAmB;IAC7B,uBAAS,CAAC,mBAAmB;IAC7B,uBAAS,CAAC,wBAAwB;IAClC,uBAAS,CAAC,wBAAwB;IAClC,uBAAS,CAAC,0BAA0B;IACpC,uBAAS,CAAC,uBAAuB;IACjC,uBAAS,CAAC,qBAAqB;IAC/B,uBAAS,CAAC,kBAAkB;IAC5B,uBAAS,CAAC,iBAAiB;IAC3B,uBAAS,CAAC,iBAAiB;IAC3B,uBAAS,CAAC,sBAAsB;IAChC,uBAAS,CAAC,sBAAsB;IAChC,uBAAS,CAAC,wBAAwB;IAClC,uBAAS,CAAC,qBAAqB;IAC/B,uBAAS,CAAC,mBAAmB;IAC7B,uBAAS,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KAAK,CAAC;YACrE,aAAa,CAAC,YAAY,CAAC,KAAK,EAAE,wBAAwB,CAAC,KAAK,CAAC;YACjE,YAAY,KAAK,SAAS,IAAI,YAAY,CAAC,gBAAgB,KAAK,IAAI,IAAI,YAAY,CAAC,UAAU,KAAK,IAAI,EAAE,CAAC;YAC3G,MAAM,IAAA,uBAAW,EAAC,yBAAyB,EAAE,eAAe,EAAE,yDAAyD,CAAC,CAAC;QAC7H,CAAC;IACL,CAAC;YACO,CAAC;QACL,mBAAmB,CAAC,UAAU,CAAC,CAAC;IACpC,CAAC;IACD,OAAO,IAAI,CAAC;AAChB,CAAC;AACD,2FAA2F;AAC9E,QAAA,0BAA0B,GAAG,2BAA2B,CAAC","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { lstatSync, mkdirSync, readdirSync } from \"node:fs\";\nimport { basename, dirname, join, resolve } from \"node:path\";\nimport { constants, DatabaseSync, type SQLOutputValue, type StatementSync } from \"node:sqlite\";\nimport { RECORD_SQLITE_BASELINE_FINGERPRINT, RECORD_SQLITE_BASELINE_SQL, RECORD_SQLITE_PREPARED_SEAL_TEMP_SQL, } from \"./schema.ts\";\nimport { sqliteError } from \"./errors.ts\";\nimport { RECORD_SQLITE_FORMAT, RECORD_SQLITE_STORAGE_REVISION } from \"./types.ts\";\nimport { currentProcessOwnerIdentity, exactProcessState } from \"../../coordination/platform/node-process-identity.ts\";\nconst MINIMUM_NODE = [24, 15, 0] as const;\nconst MINIMUM_IMMUTABLE_READER_NODE = [24, 10, 0] as const;\nconst READ_DENIED = new Set([\n constants.SQLITE_ATTACH,\n constants.SQLITE_DETACH,\n constants.SQLITE_INSERT,\n constants.SQLITE_UPDATE,\n constants.SQLITE_DELETE,\n constants.SQLITE_CREATE_INDEX,\n constants.SQLITE_CREATE_TABLE,\n constants.SQLITE_CREATE_TEMP_INDEX,\n constants.SQLITE_CREATE_TEMP_TABLE,\n constants.SQLITE_CREATE_TEMP_TRIGGER,\n constants.SQLITE_CREATE_TEMP_VIEW,\n constants.SQLITE_CREATE_TRIGGER,\n constants.SQLITE_CREATE_VIEW,\n constants.SQLITE_DROP_INDEX,\n constants.SQLITE_DROP_TABLE,\n constants.SQLITE_DROP_TEMP_INDEX,\n constants.SQLITE_DROP_TEMP_TABLE,\n constants.SQLITE_DROP_TEMP_TRIGGER,\n constants.SQLITE_DROP_TEMP_VIEW,\n constants.SQLITE_DROP_TRIGGER,\n constants.SQLITE_DROP_VIEW,\n constants.SQLITE_ALTER_TABLE,\n constants.SQLITE_REINDEX,\n constants.SQLITE_ANALYZE,\n constants.SQLITE_CREATE_VTABLE,\n constants.SQLITE_DROP_VTABLE,\n]);\nexport interface RecordDatabase {\n readonly db: DatabaseSync;\n readonly path: string;\n readonly mode: \"writer\" | \"reader\" | \"maintenance\";\n readonly statements: Map<string, StatementSync>;\n}\nexport function recordStatement(connection: RecordDatabase, sql: string): StatementSync {\n const existing = connection.statements.get(sql);\n if (existing !== undefined)\n return existing;\n const prepared = connection.db.prepare(sql);\n connection.statements.set(sql, prepared);\n return prepared;\n}\nfunction currentStatement(db: DatabaseSync, sql: string): StatementSync {\n return db.prepare(sql);\n}\nfunction currentExec(db: DatabaseSync, sql: string): void {\n db.exec(sql);\n}\nfunction nodeVersionTuple(): readonly number[] {\n return process.versions.node.split(\".\").map((part) => Number(part));\n}\nfunction assertMinimumNode(minimum: readonly number[], capability: string): void {\n const actual = nodeVersionTuple();\n for (let index = 0; index < minimum.length; index += 1) {\n const value = actual[index] ?? 0;\n const required = minimum[index];\n if (value > required)\n return;\n if (value < required) {\n throw sqliteError(\"record-runtime-unsupported\", \"open\", `${capability} requires Node ${minimum.join(\".\")} or newer; received ${process.versions.node}`);\n }\n }\n}\nexport function assertRecordSqliteRuntime(): void {\n assertMinimumNode(MINIMUM_NODE, \"Project Record SQLite\");\n}\nfunction assertImmutableRecordReaderRuntime(): void {\n // The 24.15 floor protects mutable WAL ownership. An already-admitted,\n // immutable generation only needs the defensive read APIs introduced in\n // 24.10 and never opens a writer or checkpoints WAL.\n assertMinimumNode(MINIMUM_IMMUTABLE_READER_NODE, \"Immutable Project Record reader\");\n}\n/** Resolves the one ProjectDatabase while preserving custom non-project roots. */\nexport function recordSqlitePath(recordStorageRoot: string): string {\n if (recordStorageRoot.length === 0)\n throw sqliteError(\"record-database-invalid\", \"locate\", \"Record storage root is empty\");\n const resolvedRoot = resolve(recordStorageRoot);\n return basename(resolvedRoot) === \"record\" && basename(dirname(resolvedRoot)) === \".niceeval\"\n ? join(dirname(resolvedRoot), \"record.sqlite\")\n : join(resolvedRoot, \"record.sqlite\");\n}\nfunction legacyRecordSqlitePath(path: string): string | undefined {\n const parent = dirname(path);\n return basename(path) === \"record.sqlite\" && basename(parent) === \".niceeval\"\n ? join(parent, \"record\", \"record.sqlite\")\n : undefined;\n}\nfunction pathExists(path: string): boolean {\n try {\n lstatSync(path);\n return true;\n }\n catch (cause) {\n if (typeof cause === \"object\" && cause !== null && Reflect.get(cause, \"code\") === \"ENOENT\")\n return false;\n throw sqliteError(\"record-database-invalid\", \"locate\", \"Record path could not be inspected safely\", cause);\n }\n}\nfunction legacyRecordRecovery(): string {\n return \"No automatic migration is available. Keep the original project and its .niceeval directory \" +\n \"for inspection with the original NiceEval version. Stop any old NiceEval processes before \" +\n \"copying project files. To run with this version, use a separate project copy without .niceeval \" +\n \"and rerun the experiment there. Do not delete individual legacy locks or records.\";\n}\n/** Record/0.13 is never opened or silently migrated into ProjectDatabase. */\nfunction assertLegacyRecordAbsent(path: string): void {\n const legacyPath = legacyRecordSqlitePath(path);\n if (legacyPath === undefined)\n return;\n if (!pathExists(legacyPath))\n return;\n throw sqliteError(\"record-schema-unsupported\", \"locate\", `legacy Record/0.13 database is unsupported and blocks ProjectDatabase: ${legacyPath}. ${legacyRecordRecovery()}`);\n}\nfunction assertLegacyCoordinationEntriesAbsent(path: string): void {\n const parent = dirname(path);\n if (basename(path) !== \"record.sqlite\" || basename(parent) !== \".niceeval\")\n return;\n for (const name of [\"locks\", \"sessions\", \"teardowns\", \"shared-state-leases\", \"sandboxes\"] as const) {\n const legacy = join(parent, name);\n if (!pathExists(legacy))\n continue;\n const metadata = lstatSync(legacy);\n if (!metadata.isDirectory() || metadata.isSymbolicLink() || readdirSync(legacy).length > 0) {\n throw sqliteError(\"record-schema-unsupported\", \"locate\", `legacy ${name}/ entries block ProjectDatabase mutation: ${legacy}. ${legacyRecordRecovery()}`);\n }\n }\n}\nexport type ProjectRecordDatabaseInspection = {\n readonly state: \"current\";\n readonly exists: boolean;\n} | {\n readonly state: \"unsupported\";\n readonly format: string;\n} | {\n readonly state: \"foreign\";\n};\n/**\n * Bounded identity probe used only by explicit maintenance. It never creates a\n * database and never treats the pre-ProjectDatabase directory as a migration\n * source.\n */\nexport function inspectProjectRecordDatabase(path: string): ProjectRecordDatabaseInspection {\n assertRecordSqliteRuntime();\n const legacyPath = legacyRecordSqlitePath(path);\n if (legacyPath !== undefined && pathExists(legacyPath)) {\n return Object.freeze({ state: \"unsupported\", format: \"niceeval.record/0.13.x\" });\n }\n if (!pathExists(path))\n return Object.freeze({ state: \"current\", exists: false });\n const metadata = lstatSync(path);\n if (!metadata.isFile() || metadata.isSymbolicLink())\n return Object.freeze({ state: \"foreign\" });\n let connection: RecordDatabase | undefined;\n try {\n connection = openRecordMaintenance(path);\n const currentTable = connection.db.prepare(`SELECT count(*) AS count FROM sqlite_schema\n WHERE type='table' AND name='ne18_record_metadata'`).get() as Record<string, SQLOutputValue>;\n const legacy017Table = connection.db.prepare(`SELECT count(*) AS count FROM sqlite_schema\n WHERE type='table' AND name='ne_record_metadata'`).get() as Record<string, SQLOutputValue>;\n const legacyTable = connection.db.prepare(`SELECT count(*) AS count FROM sqlite_schema\n WHERE type='table' AND name='record_metadata'`).get() as Record<string, SQLOutputValue>;\n const hasCurrent = decodeInteger(currentTable.count, \"sqlite_schema.record_metadata\") === 1;\n const hasLegacy017 = decodeInteger(legacy017Table.count, \"sqlite_schema.record_metadata\") === 1;\n const hasLegacy = decodeInteger(legacyTable.count, \"sqlite_schema.record_metadata\") === 1;\n if (Number(hasCurrent) + Number(hasLegacy017) + Number(hasLegacy) !== 1) {\n return Object.freeze({ state: \"foreign\" });\n }\n const metadataTable = hasCurrent ? \"ne18_record_metadata\" : hasLegacy017 ? \"ne_record_metadata\" : \"record_metadata\";\n let row: Record<string, SQLOutputValue> | undefined;\n try {\n row = connection.db.prepare(`SELECT format,storage_revision\n FROM ${metadataTable} WHERE singleton=1`).get() as Record<string, SQLOutputValue> | undefined;\n }\n catch {\n return Object.freeze({ state: \"foreign\" });\n }\n if (row === undefined || typeof row.format !== \"string\")\n return Object.freeze({ state: \"foreign\" });\n if (row.format !== RECORD_SQLITE_FORMAT) {\n return Object.freeze({ state: \"unsupported\", format: row.format });\n }\n let revision: number;\n try {\n revision = decodeInteger(row.storage_revision, \"record_metadata.storage_revision\");\n }\n catch {\n return Object.freeze({ state: \"foreign\" });\n }\n if (revision !== RECORD_SQLITE_STORAGE_REVISION) {\n return Object.freeze({ state: \"unsupported\", format: row.format });\n }\n try {\n validateExactSchema(connection);\n requireMigrationReady(connection);\n return Object.freeze({ state: \"current\", exists: true });\n }\n catch {\n return Object.freeze({ state: \"unsupported\", format: row.format });\n }\n }\n catch {\n return Object.freeze({ state: \"foreign\" });\n }\n finally {\n if (connection !== undefined)\n closeRecordDatabase(connection);\n }\n}\nfunction configureCommon(db: DatabaseSync): void {\n db.enableLoadExtension(false);\n db.enableDefensive(true);\n db.exec(\"PRAGMA secure_delete=ON; PRAGMA foreign_keys=ON; PRAGMA trusted_schema=OFF; PRAGMA mmap_size=0; PRAGMA cache_size=-8192; PRAGMA temp_store=FILE; PRAGMA recursive_triggers=ON;\");\n}\nfunction requireSecureDelete(db: DatabaseSync): void {\n const row = currentStatement(db, \"PRAGMA secure_delete\").get() as Record<string, SQLOutputValue> | undefined;\n if (row === undefined || decodeInteger(row.secure_delete, \"secure_delete\") !== 1) {\n throw sqliteError(\"record-database-invalid\", \"open\", \"ProjectDatabase requires PRAGMA secure_delete=ON\");\n }\n}\nfunction writableAuthorizer() {\n return (action: number, arg1: string | null, arg2: string | null): number => {\n if (action === constants.SQLITE_ATTACH)\n return constants.SQLITE_DENY;\n if (action === constants.SQLITE_DETACH)\n return constants.SQLITE_DENY;\n if (action === constants.SQLITE_FUNCTION && arg2?.toLowerCase() === \"load_extension\")\n return constants.SQLITE_DENY;\n if (action === constants.SQLITE_PRAGMA) {\n const permitted = arg1 === \"busy_timeout\" || arg1 === \"quick_check\" || arg1 === \"foreign_key_check\" || arg1 === \"wal_checkpoint\" || arg1 === \"secure_delete\";\n if (!permitted)\n return constants.SQLITE_DENY;\n }\n return constants.SQLITE_OK;\n };\n}\nfunction readerAuthorizer(action: number, arg1: string | null, arg2: string | null, dbName: string | null): number {\n if (dbName === \"temp\") {\n const preparedTable = arg1 === \"niceeval_prepared_seal_raw\" || arg1 === \"niceeval_prepared_seal_ordered\";\n return preparedTable && (action === constants.SQLITE_READ || action === constants.SQLITE_INSERT || action === constants.SQLITE_DELETE)\n ? constants.SQLITE_OK\n : constants.SQLITE_DENY;\n }\n if (dbName !== null && dbName !== \"main\")\n return constants.SQLITE_DENY;\n if (READ_DENIED.has(action))\n return constants.SQLITE_DENY;\n if (action === constants.SQLITE_PRAGMA && arg1 !== \"quick_check\" && arg1 !== \"foreign_key_check\" && arg1 !== \"secure_delete\")\n return constants.SQLITE_DENY;\n if (action === constants.SQLITE_FUNCTION && arg2?.toLowerCase() === \"load_extension\")\n return constants.SQLITE_DENY;\n return constants.SQLITE_OK;\n}\nfunction schemaRows(db: DatabaseSync): readonly string[] {\n const rows = currentStatement(db, `SELECT type, name, tbl_name, sql FROM sqlite_schema\n WHERE name NOT LIKE 'sqlite_stat%' ORDER BY type, name LIMIT 257`).all() as unknown as readonly Record<string, SQLOutputValue>[];\n if (rows.length > 256)\n throw sqliteError(\"record-database-invalid\", \"validate-schema\", \"database schema exceeds the bounded object allowlist\");\n return rows.map((row) => JSON.stringify([\n decodeText(row.type, \"sqlite_schema.type\"),\n decodeText(row.name, \"sqlite_schema.name\"),\n decodeText(row.tbl_name, \"sqlite_schema.tbl_name\"),\n row.sql === null ? null : normalizeSql(decodeText(row.sql, \"sqlite_schema.sql\")),\n ]));\n}\nfunction normalizeSql(sql: string): string {\n return sql.replace(/\\s+/gu, \" \").replace(/\\s*([(),])\\s*/gu, \"$1\").trim().replace(/;$/u, \"\");\n}\nconst canonicalSchemaRows = new Map<string, readonly string[]>();\nfunction expectedSchemaRows(sql?: string): readonly string[] {\n const key = sql ?? \"bootstrap\";\n const cached = canonicalSchemaRows.get(key);\n if (cached !== undefined)\n return cached;\n const db = new DatabaseSync(\":memory:\", { allowExtension: false, defensive: true, readBigInts: true });\n try {\n db.exec(sql ?? RECORD_SQLITE_BASELINE_SQL);\n const rows = Object.freeze(schemaRows(db));\n canonicalSchemaRows.set(key, rows);\n return rows;\n }\n finally {\n db.close();\n }\n}\nfunction validateSchemaObjects(connection: RecordDatabase, sql?: string): void {\n const actual = schemaRows(connection.db);\n const expected = expectedSchemaRows(sql);\n if (actual.length !== expected.length || actual.some((row, index) => row !== expected[index])) {\n throw sqliteError(\"record-schema-unsupported\", \"validate-schema\", \"database objects do not match the exact Project Record schema allowlist\");\n }\n}\nfunction storageRevision(connection: RecordDatabase): number {\n const row = currentStatement(connection.db, \"SELECT storage_revision FROM ne18_record_metadata WHERE singleton=1\").get() as Record<string, SQLOutputValue> | undefined;\n if (row === undefined)\n throw sqliteError(\"record-schema-unsupported\", \"validate-schema\", \"ProjectDatabase identity is missing\");\n return decodeInteger(row.storage_revision, \"record_metadata.storage_revision\");\n}\nfunction validateExistingOperationalSchemaForWriter(connection: RecordDatabase): void {\n const revision = storageRevision(connection);\n if (revision === RECORD_SQLITE_STORAGE_REVISION) {\n validateExactSchema(connection);\n requireMigrationReady(connection);\n return;\n }\n throw sqliteError(\"record-schema-unsupported\", \"validate-schema\", `record storage revision ${revision} cannot be opened by revision ${RECORD_SQLITE_STORAGE_REVISION}`);\n}\nfunction decodeText(value: SQLOutputValue | undefined, field: string): string {\n if (typeof value !== \"string\")\n throw sqliteError(\"record-database-invalid\", \"decode\", `${field} is not text`);\n return value;\n}\nfunction decodeInteger(value: SQLOutputValue | undefined, field: string): number {\n const numeric = typeof value === \"bigint\" ? Number(value) : value;\n if (typeof numeric !== \"number\" || !Number.isSafeInteger(numeric)) {\n throw sqliteError(\"record-database-invalid\", \"decode\", `${field} is not a safe integer`);\n }\n return numeric;\n}\nfunction validateCurrentRecordDomain(connection: RecordDatabase): void {\n let metadata: Record<string, SQLOutputValue> | undefined;\n try {\n metadata = currentStatement(connection.db, `SELECT format,storage_revision,storage_generation,schema_fingerprint,barrier_state\n FROM ne18_record_metadata WHERE singleton=1`).get() as Record<string, SQLOutputValue> | undefined;\n }\n catch (cause) {\n throw sqliteError(\"record-schema-unsupported\", \"validate-schema\", \"database does not expose the ProjectDatabase identity\", cause);\n }\n if (metadata === undefined) {\n throw sqliteError(\"record-schema-unsupported\", \"validate-schema\", \"ProjectDatabase identity is missing\");\n }\n if (decodeText(metadata.format, \"record_metadata.format\") !== RECORD_SQLITE_FORMAT) {\n throw sqliteError(\"record-schema-unsupported\", \"validate-schema\", \"record format is unsupported\");\n }\n const revision = decodeInteger(metadata.storage_revision, \"record_metadata.storage_revision\");\n if (revision !== RECORD_SQLITE_STORAGE_REVISION) {\n throw sqliteError(\"record-schema-unsupported\", \"validate-schema\", `record storage revision ${revision} is not ${RECORD_SQLITE_STORAGE_REVISION}`);\n }\n if (decodeText(metadata.schema_fingerprint, \"record_metadata.schema_fingerprint\") !== RECORD_SQLITE_BASELINE_FINGERPRINT) {\n throw sqliteError(\"record-schema-unsupported\", \"validate-schema\", \"ProjectDatabase baseline fingerprint is unsupported\");\n }\n const barrierState = decodeText(metadata.barrier_state, \"record_metadata.barrier_state\");\n if (barrierState !== \"open\" && barrierState !== \"draining\" && barrierState !== \"portable\") {\n throw sqliteError(\"record-database-invalid\", \"validate-schema\", \"ProjectDatabase barrier state is invalid\");\n }\n validateSchemaObjects(connection);\n const coordination = currentStatement(connection.db, `SELECT revision,operational_generation,next_writer_sequence,\n writer_ticket_id,barrier_id FROM ne18_coordination_state WHERE singleton=1`).get() as Record<string, SQLOutputValue> | undefined;\n if (coordination === undefined) {\n throw sqliteError(\"record-database-invalid\", \"validate-schema\", \"host coordination generation is missing\");\n }\n const operationalGeneration = decodeText(coordination.operational_generation, \"coordination_state.operational_generation\");\n const storageGeneration = decodeText(metadata.storage_generation, \"record_metadata.storage_generation\");\n if (operationalGeneration !== storageGeneration) {\n throw sqliteError(\"record-database-invalid\", \"validate-schema\", \"operational coordination generation does not match ProjectDatabase\");\n }\n const migration = currentStatement(connection.db, \"SELECT state FROM ne18_migration_state WHERE singleton=1\").get() as Record<string, SQLOutputValue> | undefined;\n if (migration === undefined) {\n throw sqliteError(\"record-database-invalid\", \"validate-schema\", \"ProjectDatabase migration state is missing\");\n }\n const migrationState = decodeText(migration.state, \"migration_state.state\");\n if (migrationState !== \"committed\" && migrationState !== \"ready\") {\n throw sqliteError(\"record-database-invalid\", \"validate-schema\", \"ProjectDatabase migration state is invalid\");\n }\n}\nfunction requireMigrationReady(connection: RecordDatabase): void {\n const row = currentStatement(connection.db, \"SELECT state FROM ne18_migration_state WHERE singleton=1\").get() as Record<string, SQLOutputValue> | undefined;\n if (row === undefined || decodeText(row.state, \"migration_state.state\") !== \"ready\") {\n throw sqliteError(\"record-schema-migration-required\", \"open\", \"ProjectDatabase migration committed but requires Host verification\");\n }\n}\nexport function validateExactSchema(connection: RecordDatabase): void {\n requireSecureDelete(connection.db);\n validateCurrentRecordDomain(connection);\n}\nexport function openRecordWriter(path: string, busyTimeoutMs = 5000): RecordDatabase {\n assertRecordSqliteRuntime();\n assertLegacyRecordAbsent(path);\n assertLegacyCoordinationEntriesAbsent(path);\n const existed = pathExists(path);\n if (existed) {\n const metadata = lstatSync(path);\n if (!metadata.isFile() || metadata.isSymbolicLink()) {\n throw sqliteError(\"record-schema-unsupported\", \"open\", \"ProjectDatabase path is not a regular Host-owned file\");\n }\n }\n mkdirSync(dirname(path), { recursive: true, mode: 0o700 });\n const db = new DatabaseSync(path, {\n allowExtension: false,\n defensive: true,\n enableForeignKeyConstraints: true,\n readBigInts: true,\n timeout: Math.max(0, Math.min(30000, Math.trunc(busyTimeoutMs))),\n });\n const connection: RecordDatabase = { db, path, mode: \"writer\", statements: new Map() };\n try {\n configureCommon(db);\n const objectCount = currentStatement(db, \"SELECT count(*) AS count FROM sqlite_schema\").get() as Record<string, SQLOutputValue>;\n const isEmpty = decodeInteger(objectCount.count, \"sqlite_schema.count\") === 0;\n if (isEmpty && existed) {\n throw sqliteError(\"record-schema-unsupported\", \"open\", \"existing empty SQLite is not a ProjectDatabase\");\n }\n // Never persist WAL mode or acquire a write transaction until an existing\n // file has proved that it is the exact Host-owned ProjectDatabase format.\n if (!isEmpty) {\n validateExistingOperationalSchemaForWriter(connection);\n requireSecureDelete(db);\n }\n else {\n db.exec(\"PRAGMA secure_delete=ON\");\n requireSecureDelete(db);\n }\n db.exec(\"PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;\");\n let created = false;\n try {\n if (isEmpty) {\n const appliedAt = new Date().toISOString();\n const generation = randomUUID();\n db.exec(\"BEGIN IMMEDIATE\");\n try {\n db.exec(RECORD_SQLITE_BASELINE_SQL);\n currentStatement(db, `INSERT INTO ne18_record_metadata(singleton,format,storage_revision,storage_generation,schema_fingerprint,\n created_at,barrier_state,portable_generation,portable_revision,portable_gate_id,record_payload,record_digest)\n VALUES (1,?,?,?,?,?,'open',NULL,NULL,NULL,NULL,NULL)`).run(RECORD_SQLITE_FORMAT, RECORD_SQLITE_STORAGE_REVISION, generation, RECORD_SQLITE_BASELINE_FINGERPRINT, appliedAt);\n currentStatement(db, `INSERT INTO ne18_coordination_state(singleton,revision,operational_generation,next_writer_sequence)\n VALUES (1,0,?,1)`).run(generation);\n currentStatement(db, `INSERT INTO ne18_migration_state(singleton,state,source_format,source_digest)\n VALUES (1,'ready',NULL,NULL)`).run();\n db.exec(\"COMMIT\");\n created = true;\n }\n catch (cause) {\n if (db.isTransaction)\n db.exec(\"ROLLBACK\");\n throw cause;\n }\n }\n else {\n // Revalidate under the write lock so a concurrent schema change cannot\n // cross the admission boundary between the read probe and this writer.\n validateExistingOperationalSchemaForWriter(connection);\n }\n }\n catch (cause) {\n throw cause;\n }\n // Both the creator and every concurrent loser validate the exact committed\n // bootstrap identity before the connection becomes a writer.\n validateExactSchema(connection);\n requireMigrationReady(connection);\n if (created)\n db.exec(\"PRAGMA wal_checkpoint(PASSIVE)\");\n db.setAuthorizer(writableAuthorizer());\n return connection;\n }\n catch (cause) {\n db.close();\n throw cause;\n }\n}\n/** Host admission path: reject legacy coordination before any in-place migration mutation. */\nexport async function openHostOwnedRecordWriter(path: string, busyTimeoutMs = 5000): Promise<RecordDatabase> {\n assertRecordSqliteRuntime();\n assertLegacyRecordAbsent(path);\n assertLegacyCoordinationEntriesAbsent(path);\n const { migrateHostOwnedProjectDatabase } = await __niceevalDynamicImport(\"./migration.cjs\");\n await migrateHostOwnedProjectDatabase(path, busyTimeoutMs);\n return openRecordWriter(path, busyTimeoutMs);\n}\nexport function openRecordReader(path: string): RecordDatabase {\n assertRecordSqliteRuntime();\n return openRecordReaderAfterRuntimeAdmission(path);\n}\nexport function openImmutableRecordReader(path: string): RecordDatabase {\n assertImmutableRecordReaderRuntime();\n return openRecordReaderAfterRuntimeAdmission(path);\n}\nfunction openRecordReaderAfterRuntimeAdmission(path: string): RecordDatabase {\n assertLegacyRecordAbsent(path);\n const db = new DatabaseSync(path, {\n allowExtension: false,\n defensive: true,\n enableForeignKeyConstraints: true,\n readBigInts: true,\n readOnly: true,\n timeout: 0,\n });\n const connection: RecordDatabase = { db, path, mode: \"reader\", statements: new Map() };\n try {\n configureCommon(db);\n requireSecureDelete(db);\n const legacyTable = db.prepare(`SELECT count(*) AS count FROM sqlite_schema\n WHERE type='table' AND name='record_metadata'`).get() as Record<string, SQLOutputValue>;\n if (decodeInteger(legacyTable.count, \"sqlite_schema.record_metadata\") === 1) {\n const legacy = db.prepare(\"SELECT format FROM record_metadata WHERE singleton=1\").get() as Record<string, SQLOutputValue> | undefined;\n const format = legacy?.format;\n if (format === \"niceeval.project-database/0.15\" || format === \"niceeval.project-database/0.16\") {\n throw sqliteError(\"record-schema-unsupported\", \"open\", `${format} cannot be opened through the current-format operational reader. Finish the old writer and provide a portable Record for read-time migration, or upgrade through the Host-owned project writer`);\n }\n }\n // The main database is opened read-only. These two private TEMP tables are\n // the only writable reader state and are required for bounded Seal sort.\n db.exec(RECORD_SQLITE_PREPARED_SEAL_TEMP_SQL);\n db.setAuthorizer(readerAuthorizer);\n validateExactSchema(connection);\n requireMigrationReady(connection);\n const integrity = currentStatement(db, \"PRAGMA quick_check\").get() as Record<string, SQLOutputValue> | undefined;\n if (integrity === undefined || decodeText(integrity.quick_check, \"quick_check\") !== \"ok\") {\n throw sqliteError(\"record-database-invalid\", \"open\", \"ProjectDatabase integrity check failed\");\n }\n const foreignKeyViolation = currentStatement(db, \"PRAGMA foreign_key_check\").get();\n if (foreignKeyViolation !== undefined) {\n throw sqliteError(\"record-database-invalid\", \"open\", \"ProjectDatabase foreign key closure is invalid\");\n }\n return connection;\n }\n catch (cause) {\n db.close();\n throw cause;\n }\n}\nexport function openRecordMaintenance(path: string): RecordDatabase {\n assertRecordSqliteRuntime();\n assertLegacyRecordAbsent(path);\n if (!pathExists(path)) {\n throw sqliteError(\"record-database-invalid\", \"open-maintenance\", \"ProjectDatabase does not exist\");\n }\n const metadata = lstatSync(path);\n if (!metadata.isFile() || metadata.isSymbolicLink()) {\n throw sqliteError(\"record-schema-unsupported\", \"open-maintenance\", \"ProjectDatabase path is not a regular Host-owned file\");\n }\n const db = new DatabaseSync(path, {\n allowExtension: false,\n defensive: true,\n enableForeignKeyConstraints: true,\n readBigInts: true,\n timeout: 5000,\n });\n const connection: RecordDatabase = { db, path, mode: \"maintenance\", statements: new Map() };\n try {\n configureCommon(db);\n db.setAuthorizer(writableAuthorizer());\n return connection;\n }\n catch (cause) {\n db.close();\n throw cause;\n }\n}\nexport function closeRecordDatabase(connection: RecordDatabase): void {\n // node:sqlite finalizes every cached statement when its owning connection is\n // closed; StatementSync intentionally exposes no independent finalize API.\n connection.statements.clear();\n if (connection.db.isOpen)\n connection.db.close();\n}\nexport function checkpointRecordDatabase(connection: RecordDatabase): void {\n if (connection.mode !== \"writer\" || !connection.db.isOpen) {\n throw sqliteError(\"record-database-invalid\", \"checkpoint\", \"Record checkpoint requires an open writer\");\n }\n connection.db.exec(\"PRAGMA wal_checkpoint(TRUNCATE)\");\n}\n/** Starts a new operational generation before coordination services acquire it. */\nexport function reopenProjectDatabase(path: string): void {\n const connection = openRecordWriter(path);\n try {\n connection.db.exec(\"BEGIN IMMEDIATE\");\n const row = currentStatement(connection.db, \"SELECT barrier_state FROM ne18_record_metadata WHERE singleton=1\")\n .get() as Record<string, SQLOutputValue> | undefined;\n if (row === undefined || decodeText(row.barrier_state, \"barrier_state\") === \"draining\") {\n throw sqliteError(\"record-command-conflict\", \"reopen\", \"ProjectDatabase portable gate is draining\");\n }\n if (decodeText(row.barrier_state, \"barrier_state\") === \"portable\") {\n const generation = randomUUID();\n currentStatement(connection.db, `UPDATE ne18_record_metadata SET barrier_state='open',storage_generation=?,portable_generation=NULL,\n portable_revision=NULL,portable_gate_id=NULL WHERE singleton=1 AND barrier_state='portable'`).run(generation);\n currentStatement(connection.db, \"UPDATE ne18_coordination_state SET operational_generation=?,revision=revision+1 WHERE singleton=1\")\n .run(generation);\n }\n connection.db.exec(\"COMMIT\");\n }\n catch (cause) {\n if (connection.db.isTransaction)\n connection.db.exec(\"ROLLBACK\");\n throw cause;\n }\n finally {\n closeRecordDatabase(connection);\n }\n}\n/**\n * Closes the project-wide writer admission and proves that the canonical file\n * itself is portable. The first transaction deliberately persists draining;\n * any later failure therefore remains fail-closed for explicit recovery.\n */\nexport function makeProjectDatabasePortable(path: string): boolean {\n const gateId = randomUUID();\n const gateNonce = randomUUID();\n const gateOwner = currentProcessOwnerIdentity(gateId);\n const admissionDrainDeadline = Date.now() + 5000;\n const waitCell = new Int32Array(new SharedArrayBuffer(4));\n let connection = openRecordWriter(path);\n try {\n connection.db.exec(\"BEGIN IMMEDIATE\");\n const metadata = currentStatement(connection.db, \"SELECT barrier_state,portable_gate_id FROM ne18_record_metadata WHERE singleton=1\")\n .get() as Record<string, SQLOutputValue> | undefined;\n if (metadata === undefined) {\n throw sqliteError(\"record-database-invalid\", \"portable-gate\", \"ProjectDatabase barrier is missing\");\n }\n const barrierState = decodeText(metadata.barrier_state, \"barrier_state\");\n if (barrierState === \"portable\") {\n connection.db.exec(\"COMMIT\");\n return true;\n }\n if (barrierState === \"draining\") {\n const previous = currentStatement(connection.db, `SELECT barrier_id,barrier_nonce,barrier_host,barrier_pid,\n barrier_boot_id,barrier_process_start FROM ne18_coordination_state WHERE singleton=1`).get() as Record<string, SQLOutputValue> | undefined;\n if (previous === undefined || previous.barrier_id === null || previous.barrier_nonce === null) {\n throw sqliteError(\"record-database-invalid\", \"portable-gate\", \"draining portable gate has no fenced owner\");\n }\n const previousOwner = {\n ownerId: decodeText(previous.barrier_id, \"barrier_id\"),\n host: decodeText(previous.barrier_host, \"barrier_host\"),\n pid: decodeInteger(previous.barrier_pid, \"barrier_pid\"),\n bootId: decodeText(previous.barrier_boot_id, \"barrier_boot_id\"),\n processStart: decodeText(previous.barrier_process_start, \"barrier_process_start\"),\n };\n const sameProcess = previousOwner.host === gateOwner.host && previousOwner.pid === gateOwner.pid &&\n previousOwner.bootId === gateOwner.bootId && previousOwner.processStart === gateOwner.processStart;\n if (!sameProcess && exactProcessState(previousOwner) !== \"dead\") {\n throw sqliteError(\"record-command-conflict\", \"portable-gate\", \"draining portable gate owner is not proven dead\");\n }\n const fenced = currentStatement(connection.db, `UPDATE ne18_coordination_state SET barrier_id=?,barrier_nonce=?,barrier_host=?,\n barrier_pid=?,barrier_boot_id=?,barrier_process_start=?,barrier_deadline=?,barrier_requested_at=?,\n barrier_lease_expires_at=?,barrier_status='active',barrier_active_at=?,revision=revision+1\n WHERE singleton=1 AND barrier_id=? AND barrier_nonce=?`).run(gateId, gateNonce, gateOwner.host, gateOwner.pid, gateOwner.bootId, gateOwner.processStart, admissionDrainDeadline, Date.now(), admissionDrainDeadline, Date.now(), previous.barrier_id, previous.barrier_nonce);\n const metadataFenced = currentStatement(connection.db, `UPDATE ne18_record_metadata SET portable_gate_id=?\n WHERE singleton=1 AND barrier_state='draining' AND portable_gate_id=?`).run(gateId, metadata.portable_gate_id);\n if (Number(fenced.changes) !== 1 || Number(metadataFenced.changes) !== 1) {\n throw sqliteError(\"record-command-conflict\", \"portable-gate\", \"draining portable gate changed during recovery\");\n }\n }\n else if (barrierState === \"open\") {\n const entered = recordStatement(connection, `UPDATE ne18_record_metadata SET barrier_state='draining',portable_gate_id=?\n WHERE singleton=1 AND barrier_state='open' AND portable_gate_id IS NULL`).run(gateId);\n const established = currentStatement(connection.db, `UPDATE ne18_coordination_state SET barrier_id=?,barrier_nonce=?,barrier_host=?,\n barrier_pid=?,barrier_boot_id=?,barrier_process_start=?,barrier_deadline=?,barrier_requested_at=?,\n barrier_lease_expires_at=?,barrier_status='active',barrier_active_at=?,revision=revision+1\n WHERE singleton=1 AND barrier_id IS NULL`).run(gateId, gateNonce, gateOwner.host, gateOwner.pid, gateOwner.bootId, gateOwner.processStart, admissionDrainDeadline, Date.now(), admissionDrainDeadline, Date.now());\n if (Number(entered.changes) !== 1 || Number(established.changes) !== 1) {\n throw sqliteError(\"record-command-conflict\", \"portable-gate\", \"ProjectDatabase barrier is not open\");\n }\n }\n else {\n throw sqliteError(\"record-database-invalid\", \"portable-gate\", \"ProjectDatabase barrier state is invalid\");\n }\n const admittedActive = currentStatement(connection.db, `SELECT\n (SELECT count(*) FROM ne18_run_resources WHERE terminal_state IS NULL)+\n (SELECT count(*) FROM ne18_invocation_sessions WHERE state IN ('active','recovering'))+\n (SELECT count(*) FROM ne18_case_locks)+\n (SELECT count(*) FROM ne18_teardown_obligations)+\n (SELECT count(*) FROM ne18_shared_state_generations s WHERE state_kind!='free' AND generation=(SELECT max(generation) FROM ne18_shared_state_generations WHERE state_key=s.state_key))+\n (SELECT count(*) FROM ne18_kept_sandbox_operation_leases) AS count`)\n .get() as Record<string, SQLOutputValue>;\n if (decodeInteger(admittedActive.count, \"active_runs\") !== 0) {\n currentStatement(connection.db, `UPDATE ne18_record_metadata SET barrier_state='open',portable_gate_id=NULL\n WHERE singleton=1 AND barrier_state='draining' AND portable_gate_id=?`).run(gateId);\n currentStatement(connection.db, `UPDATE ne18_coordination_state SET barrier_id=NULL,barrier_nonce=NULL,barrier_host=NULL,\n barrier_pid=NULL,barrier_boot_id=NULL,barrier_process_start=NULL,barrier_deadline=NULL,\n barrier_requested_at=NULL,barrier_lease_expires_at=NULL,barrier_status=NULL,barrier_active_at=NULL,\n revision=revision+1 WHERE singleton=1 AND barrier_id=? AND barrier_nonce=?`).run(gateId, gateNonce);\n connection.db.exec(\"COMMIT\");\n return false;\n }\n // The draining barrier rejects new tickets. Queued-but-not-admitted work\n // has no writer authority and is canceled; an already admitted writer or\n // barrier must release its exact identity before the gate continues.\n currentStatement(connection.db, \"DELETE FROM ne18_coordination_tickets\").run();\n connection.db.exec(\"COMMIT\");\n while (true) {\n const coordination = currentStatement(connection.db, `SELECT\n (writer_ticket_id IS NOT NULL OR (barrier_id IS NOT NULL AND barrier_id!=?)) AS active\n FROM ne18_coordination_state WHERE singleton=1`).get(gateId) as Record<string, SQLOutputValue> | undefined;\n if (coordination === undefined) {\n throw sqliteError(\"record-database-invalid\", \"portable-gate\", \"coordination singleton is missing\");\n }\n if (decodeInteger(coordination.active, \"portable_admission\") === 0)\n break;\n if (Date.now() >= admissionDrainDeadline) {\n throw sqliteError(\"record-write-busy\", \"portable-gate\", \"admitted writer did not drain before the portable deadline\");\n }\n Atomics.wait(waitCell, 0, 0, 15);\n }\n connection.db.exec(\"BEGIN IMMEDIATE\");\n const active = currentStatement(connection.db, \"SELECT count(*) AS count FROM ne18_run_resources WHERE terminal_state IS NULL\")\n .get() as Record<string, SQLOutputValue>;\n if (decodeInteger(active.count, \"active_runs\") !== 0) {\n throw sqliteError(\"record-command-conflict\", \"portable-gate\", \"active Run owners prevent portable close\");\n }\n const invocationWork = currentStatement(connection.db, `SELECT\n (SELECT count(*) FROM ne18_invocation_sessions WHERE state IN ('active','recovering'))+\n (SELECT count(*) FROM ne18_invocation_session_queued_attempts)+\n (SELECT count(*) FROM ne18_case_locks) AS count`).get() as Record<string, SQLOutputValue>;\n if (decodeInteger(invocationWork.count, \"invocation_work\") !== 0) {\n throw sqliteError(\"record-command-conflict\", \"portable-gate\", \"invocation coordination work prevents portable close\");\n }\n currentExec(connection.db, `DELETE FROM ne18_runs WHERE status!='sealed' AND NOT EXISTS\n (SELECT 1 FROM ne18_attempt_publications WHERE origin_run_id=ne18_runs.run_id); DELETE FROM ne18_coordination_tickets;`);\n currentStatement(connection.db, `UPDATE ne18_coordination_state SET revision=revision+1,next_writer_sequence=1,\n writer_ticket_id=NULL,writer_sequence=NULL,writer_host=NULL,writer_pid=NULL,writer_deadline=NULL,\n writer_boot_id=NULL,writer_process_start=NULL,\n writer_enqueued_at=NULL,writer_nonce=NULL,writer_admitted_at=NULL,writer_lease_expires_at=NULL,\n barrier_id=NULL,barrier_nonce=NULL,barrier_host=NULL,barrier_pid=NULL,barrier_deadline=NULL,\n barrier_boot_id=NULL,barrier_process_start=NULL,\n barrier_requested_at=NULL,barrier_lease_expires_at=NULL,barrier_status=NULL,barrier_active_at=NULL\n WHERE singleton=1`).run();\n const clock = currentStatement(connection.db, \"SELECT revision FROM ne18_run_publication_clock WHERE singleton=1\")\n .get() as Record<string, SQLOutputValue>;\n const generation = currentStatement(connection.db, \"SELECT storage_generation FROM ne18_record_metadata WHERE singleton=1\")\n .get() as Record<string, SQLOutputValue>;\n currentStatement(connection.db, `UPDATE ne18_record_metadata SET barrier_state='portable',portable_generation=?,portable_revision=?\n WHERE singleton=1 AND barrier_state='draining' AND portable_gate_id=?`).run(decodeText(generation.storage_generation, \"storage_generation\"), decodeInteger(clock.revision, \"publication_revision\"), gateId);\n connection.db.exec(\"COMMIT\");\n checkpointRecordDatabase(connection);\n }\n catch (cause) {\n if (connection.db.isTransaction)\n connection.db.exec(\"ROLLBACK\");\n throw cause;\n }\n finally {\n closeRecordDatabase(connection);\n }\n connection = openRecordReader(path);\n try {\n const state = currentStatement(connection.db, `SELECT barrier_state,portable_generation,portable_revision,storage_generation\n FROM ne18_record_metadata WHERE singleton=1`).get() as Record<string, SQLOutputValue> | undefined;\n const active = currentStatement(connection.db, `SELECT\n (SELECT count(*) FROM ne18_run_resources WHERE terminal_state IS NULL)+\n (SELECT count(*) FROM ne18_runs r WHERE status!='sealed' AND\n (EXISTS (SELECT 1 FROM ne18_attempts a WHERE a.origin_run_id=r.run_id AND a.publication_state!='published') OR\n EXISTS (SELECT 1 FROM ne18_run_resources rr WHERE rr.run_id=r.run_id AND rr.terminal_state IS NULL)))+\n (SELECT count(*) FROM ne18_coordination_tickets) AS count`).get() as Record<string, SQLOutputValue>;\n const invocationWork = currentStatement(connection.db, `SELECT\n (SELECT count(*) FROM ne18_invocation_sessions WHERE state IN ('active','recovering'))+\n (SELECT count(*) FROM ne18_invocation_session_queued_attempts)+\n (SELECT count(*) FROM ne18_case_locks) AS count`).get() as Record<string, SQLOutputValue>;\n const registryWork = currentStatement(connection.db, `SELECT\n (SELECT count(*) FROM ne18_teardown_obligations)+\n (SELECT count(*) FROM ne18_shared_state_generations s WHERE state_kind!='free' AND generation=(SELECT max(generation) FROM ne18_shared_state_generations WHERE state_key=s.state_key))+\n (SELECT count(*) FROM ne18_kept_sandbox_operation_leases) AS count`).get() as Record<string, SQLOutputValue>;\n const coordination = currentStatement(connection.db, `SELECT writer_ticket_id,barrier_id FROM ne18_coordination_state WHERE singleton=1`)\n .get() as Record<string, SQLOutputValue> | undefined;\n const clock = currentStatement(connection.db, \"SELECT revision FROM ne18_run_publication_clock WHERE singleton=1\")\n .get() as Record<string, SQLOutputValue> | undefined;\n if (state === undefined || decodeText(state.barrier_state, \"barrier_state\") !== \"portable\" ||\n decodeText(state.portable_generation, \"portable_generation\") !== decodeText(state.storage_generation, \"storage_generation\") ||\n clock === undefined || decodeInteger(state.portable_revision, \"portable_revision\") !== decodeInteger(clock.revision, \"publication_revision\") ||\n decodeInteger(active.count, \"portable_work\") !== 0 ||\n decodeInteger(invocationWork.count, \"portable_invocation_work\") !== 0 ||\n decodeInteger(registryWork.count, \"portable_registry_work\") !== 0 ||\n coordination === undefined || coordination.writer_ticket_id !== null || coordination.barrier_id !== null) {\n throw sqliteError(\"record-database-invalid\", \"portable-gate\", \"hostile reopen did not prove a portable ProjectDatabase\");\n }\n }\n finally {\n closeRecordDatabase(connection);\n }\n return true;\n}\n/** Invocation-boundary portable operation; terminal session projections remain durable. */\nexport const finalizeInvocationPortable = makeProjectDatabasePortable;\n"]}
1
+ {"version":3,"file":"database.js","sourceRoot":"","sources":["database.ts"],"names":[],"mappings":";;;AA4CA,0CAOC;AAsBD,8DAEC;AAQD,4CAOC;AA6DD,oEAkEC;AAmKD,kDAGC;AACD,4CAoFC;AAED,8DAOC;AACD,4CAGC;AACD,8DAGC;AAuCD,sDA2BC;AACD,kDAMC;AACD,4DAKC;AAED,sDA0BC;AAMD,kEA8KC;AApwBD,6CAAyC;AACzC,qCAA4D;AAC5D,yCAA6D;AAC7D,6CAA+F;AAC/F,2CAAoI;AACpI,2CAA0C;AAC1C,yCAAkF;AAClF,mGAAsH;AACtH,MAAM,YAAY,GAAG,CAAC,EAAE,EAAE,EAAE,EAAE,CAAC,CAAU,CAAC;AAC1C,MAAM,6BAA6B,GAAG,CAAC,EAAE,EAAE,EAAE,EAAE,CAAC,CAAU,CAAC;AAC3D,MAAM,WAAW,GAAG,IAAI,GAAG,CAAC;IACxB,uBAAS,CAAC,aAAa;IACvB,uBAAS,CAAC,aAAa;IACvB,uBAAS,CAAC,aA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0B,CAAC,KAAK,CAAC;YACrE,aAAa,CAAC,YAAY,CAAC,KAAK,EAAE,wBAAwB,CAAC,KAAK,CAAC;YACjE,YAAY,KAAK,SAAS,IAAI,YAAY,CAAC,gBAAgB,KAAK,IAAI,IAAI,YAAY,CAAC,UAAU,KAAK,IAAI,EAAE,CAAC;YAC3G,MAAM,IAAA,uBAAW,EAAC,yBAAyB,EAAE,eAAe,EAAE,yDAAyD,CAAC,CAAC;QAC7H,CAAC;IACL,CAAC;YACO,CAAC;QACL,mBAAmB,CAAC,UAAU,CAAC,CAAC;IACpC,CAAC;IACD,OAAO,IAAI,CAAC;AAChB,CAAC;AACD,2FAA2F;AAC9E,QAAA,0BAA0B,GAAG,2BAA2B,CAAC","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { lstatSync, mkdirSync, readdirSync } from \"node:fs\";\nimport { basename, dirname, join, resolve } from \"node:path\";\nimport { constants, DatabaseSync, type SQLOutputValue, type StatementSync } from \"node:sqlite\";\nimport { RECORD_SQLITE_BASELINE_FINGERPRINT, RECORD_SQLITE_BASELINE_SQL, RECORD_SQLITE_PREPARED_SEAL_TEMP_SQL, } from \"./schema.ts\";\nimport { sqliteError } from \"./errors.ts\";\nimport { RECORD_SQLITE_FORMAT, RECORD_SQLITE_STORAGE_REVISION } from \"./types.ts\";\nimport { currentProcessOwnerIdentity, exactProcessState } from \"../../coordination/platform/node-process-identity.ts\";\nconst MINIMUM_NODE = [24, 15, 0] as const;\nconst MINIMUM_IMMUTABLE_READER_NODE = [24, 10, 0] as const;\nconst READ_DENIED = new Set([\n constants.SQLITE_ATTACH,\n constants.SQLITE_DETACH,\n constants.SQLITE_INSERT,\n constants.SQLITE_UPDATE,\n constants.SQLITE_DELETE,\n constants.SQLITE_CREATE_INDEX,\n constants.SQLITE_CREATE_TABLE,\n constants.SQLITE_CREATE_TEMP_INDEX,\n constants.SQLITE_CREATE_TEMP_TABLE,\n constants.SQLITE_CREATE_TEMP_TRIGGER,\n constants.SQLITE_CREATE_TEMP_VIEW,\n constants.SQLITE_CREATE_TRIGGER,\n constants.SQLITE_CREATE_VIEW,\n constants.SQLITE_DROP_INDEX,\n constants.SQLITE_DROP_TABLE,\n constants.SQLITE_DROP_TEMP_INDEX,\n constants.SQLITE_DROP_TEMP_TABLE,\n constants.SQLITE_DROP_TEMP_TRIGGER,\n constants.SQLITE_DROP_TEMP_VIEW,\n constants.SQLITE_DROP_TRIGGER,\n constants.SQLITE_DROP_VIEW,\n constants.SQLITE_ALTER_TABLE,\n constants.SQLITE_REINDEX,\n constants.SQLITE_ANALYZE,\n constants.SQLITE_CREATE_VTABLE,\n constants.SQLITE_DROP_VTABLE,\n]);\nexport interface RecordDatabase {\n readonly db: DatabaseSync;\n readonly path: string;\n readonly mode: \"writer\" | \"reader\" | \"maintenance\";\n readonly statements: Map<string, StatementSync>;\n}\nexport function recordStatement(connection: RecordDatabase, sql: string): StatementSync {\n const existing = connection.statements.get(sql);\n if (existing !== undefined)\n return existing;\n const prepared = connection.db.prepare(sql);\n connection.statements.set(sql, prepared);\n return prepared;\n}\nfunction currentStatement(db: DatabaseSync, sql: string): StatementSync {\n return db.prepare(sql);\n}\nfunction currentExec(db: DatabaseSync, sql: string): void {\n db.exec(sql);\n}\nfunction nodeVersionTuple(): readonly number[] {\n return process.versions.node.split(\".\").map((part) => Number(part));\n}\nfunction assertMinimumNode(minimum: readonly number[], capability: string): void {\n const actual = nodeVersionTuple();\n for (let index = 0; index < minimum.length; index += 1) {\n const value = actual[index] ?? 0;\n const required = minimum[index];\n if (value > required)\n return;\n if (value < required) {\n throw sqliteError(\"record-runtime-unsupported\", \"open\", `${capability} requires Node ${minimum.join(\".\")} or newer; received ${process.versions.node}`);\n }\n }\n}\nexport function assertRecordSqliteRuntime(): void {\n assertMinimumNode(MINIMUM_NODE, \"Project Record SQLite\");\n}\nfunction assertImmutableRecordReaderRuntime(): void {\n // The 24.15 floor protects mutable WAL ownership. An already-admitted,\n // immutable generation only needs the defensive read APIs introduced in\n // 24.10 and never opens a writer or checkpoints WAL.\n assertMinimumNode(MINIMUM_IMMUTABLE_READER_NODE, \"Immutable Project Record reader\");\n}\n/** Resolves the one ProjectDatabase while preserving custom non-project roots. */\nexport function recordSqlitePath(recordStorageRoot: string): string {\n if (recordStorageRoot.length === 0)\n throw sqliteError(\"record-database-invalid\", \"locate\", \"Record storage root is empty\");\n const resolvedRoot = resolve(recordStorageRoot);\n return basename(resolvedRoot) === \"record\" && basename(dirname(resolvedRoot)) === \".niceeval\"\n ? join(dirname(resolvedRoot), \"record.sqlite\")\n : join(resolvedRoot, \"record.sqlite\");\n}\nfunction legacyRecordSqlitePath(path: string): string | undefined {\n const parent = dirname(path);\n return basename(path) === \"record.sqlite\" && basename(parent) === \".niceeval\"\n ? join(parent, \"record\", \"record.sqlite\")\n : undefined;\n}\nfunction pathExists(path: string): boolean {\n try {\n lstatSync(path);\n return true;\n }\n catch (cause) {\n if (typeof cause === \"object\" && cause !== null && Reflect.get(cause, \"code\") === \"ENOENT\")\n return false;\n throw sqliteError(\"record-database-invalid\", \"locate\", \"Record path could not be inspected safely\", cause);\n }\n}\nfunction legacyRecordRecovery(): string {\n return \"No automatic migration is available. Keep the original project and its .niceeval directory \" +\n \"for inspection with the original NiceEval version. Stop any old NiceEval processes before \" +\n \"copying project files. To run with this version, use a separate project copy without .niceeval \" +\n \"and rerun the experiment there. Do not delete individual legacy locks or records.\";\n}\n/** Record/0.13 is never opened or silently migrated into ProjectDatabase. */\nfunction assertLegacyRecordAbsent(path: string): void {\n const legacyPath = legacyRecordSqlitePath(path);\n if (legacyPath === undefined)\n return;\n if (!pathExists(legacyPath))\n return;\n throw sqliteError(\"record-schema-unsupported\", \"locate\", `legacy Record/0.13 database is unsupported and blocks ProjectDatabase: ${legacyPath}. ${legacyRecordRecovery()}`);\n}\nfunction assertLegacyCoordinationEntriesAbsent(path: string): void {\n const parent = dirname(path);\n if (basename(path) !== \"record.sqlite\" || basename(parent) !== \".niceeval\")\n return;\n for (const name of [\"locks\", \"sessions\", \"teardowns\", \"shared-state-leases\", \"sandboxes\"] as const) {\n const legacy = join(parent, name);\n if (!pathExists(legacy))\n continue;\n const metadata = lstatSync(legacy);\n if (!metadata.isDirectory() || metadata.isSymbolicLink() || readdirSync(legacy).length > 0) {\n throw sqliteError(\"record-schema-unsupported\", \"locate\", `legacy ${name}/ entries block ProjectDatabase mutation: ${legacy}. ${legacyRecordRecovery()}`);\n }\n }\n}\nexport type ProjectRecordDatabaseInspection = {\n readonly state: \"current\";\n readonly exists: boolean;\n} | {\n readonly state: \"unsupported\";\n readonly format: string;\n} | {\n readonly state: \"foreign\";\n};\n/**\n * Bounded identity probe used only by explicit maintenance. It never creates a\n * database and never treats the pre-ProjectDatabase directory as a migration\n * source.\n */\nexport function inspectProjectRecordDatabase(path: string): ProjectRecordDatabaseInspection {\n assertRecordSqliteRuntime();\n const legacyPath = legacyRecordSqlitePath(path);\n if (legacyPath !== undefined && pathExists(legacyPath)) {\n return Object.freeze({ state: \"unsupported\", format: \"niceeval.record/0.13.x\" });\n }\n if (!pathExists(path))\n return Object.freeze({ state: \"current\", exists: false });\n const metadata = lstatSync(path);\n if (!metadata.isFile() || metadata.isSymbolicLink())\n return Object.freeze({ state: \"foreign\" });\n let connection: RecordDatabase | undefined;\n try {\n connection = openRecordMaintenance(path);\n const currentTable = connection.db.prepare(`SELECT count(*) AS count FROM sqlite_schema\n WHERE type='table' AND name='ne18_record_metadata'`).get() as Record<string, SQLOutputValue>;\n const legacy017Table = connection.db.prepare(`SELECT count(*) AS count FROM sqlite_schema\n WHERE type='table' AND name='ne_record_metadata'`).get() as Record<string, SQLOutputValue>;\n const legacyTable = connection.db.prepare(`SELECT count(*) AS count FROM sqlite_schema\n WHERE type='table' AND name='record_metadata'`).get() as Record<string, SQLOutputValue>;\n const hasCurrent = decodeInteger(currentTable.count, \"sqlite_schema.record_metadata\") === 1;\n const hasLegacy017 = decodeInteger(legacy017Table.count, \"sqlite_schema.record_metadata\") === 1;\n const hasLegacy = decodeInteger(legacyTable.count, \"sqlite_schema.record_metadata\") === 1;\n if (Number(hasCurrent) + Number(hasLegacy017) + Number(hasLegacy) !== 1) {\n return Object.freeze({ state: \"foreign\" });\n }\n const metadataTable = hasCurrent ? \"ne18_record_metadata\" : hasLegacy017 ? \"ne_record_metadata\" : \"record_metadata\";\n let row: Record<string, SQLOutputValue> | undefined;\n try {\n row = connection.db.prepare(`SELECT format,storage_revision\n FROM ${metadataTable} WHERE singleton=1`).get() as Record<string, SQLOutputValue> | undefined;\n }\n catch {\n return Object.freeze({ state: \"foreign\" });\n }\n if (row === undefined || typeof row.format !== \"string\")\n return Object.freeze({ state: \"foreign\" });\n if (row.format !== RECORD_SQLITE_FORMAT) {\n return Object.freeze({ state: \"unsupported\", format: row.format });\n }\n let revision: number;\n try {\n revision = decodeInteger(row.storage_revision, \"record_metadata.storage_revision\");\n }\n catch {\n return Object.freeze({ state: \"foreign\" });\n }\n if (revision !== RECORD_SQLITE_STORAGE_REVISION) {\n return Object.freeze({ state: \"unsupported\", format: row.format });\n }\n try {\n validateExactSchema(connection);\n requireMigrationReady(connection);\n return Object.freeze({ state: \"current\", exists: true });\n }\n catch {\n return Object.freeze({ state: \"unsupported\", format: row.format });\n }\n }\n catch {\n return Object.freeze({ state: \"foreign\" });\n }\n finally {\n if (connection !== undefined)\n closeRecordDatabase(connection);\n }\n}\nfunction configureCommon(db: DatabaseSync): void {\n db.enableLoadExtension(false);\n db.enableDefensive(true);\n db.exec(\"PRAGMA secure_delete=ON; PRAGMA foreign_keys=ON; PRAGMA trusted_schema=OFF; PRAGMA mmap_size=0; PRAGMA cache_size=-8192; PRAGMA temp_store=FILE; PRAGMA recursive_triggers=ON;\");\n}\nfunction requireSecureDelete(db: DatabaseSync): void {\n const row = currentStatement(db, \"PRAGMA secure_delete\").get() as Record<string, SQLOutputValue> | undefined;\n if (row === undefined || decodeInteger(row.secure_delete, \"secure_delete\") !== 1) {\n throw sqliteError(\"record-database-invalid\", \"open\", \"ProjectDatabase requires PRAGMA secure_delete=ON\");\n }\n}\nfunction writableAuthorizer() {\n return (action: number, arg1: string | null, arg2: string | null): number => {\n if (action === constants.SQLITE_ATTACH)\n return constants.SQLITE_DENY;\n if (action === constants.SQLITE_DETACH)\n return constants.SQLITE_DENY;\n if (action === constants.SQLITE_FUNCTION && arg2?.toLowerCase() === \"load_extension\")\n return constants.SQLITE_DENY;\n if (action === constants.SQLITE_PRAGMA) {\n const permitted = arg1 === \"busy_timeout\" || arg1 === \"quick_check\" || arg1 === \"foreign_key_check\" || arg1 === \"wal_checkpoint\" || arg1 === \"secure_delete\";\n if (!permitted)\n return constants.SQLITE_DENY;\n }\n return constants.SQLITE_OK;\n };\n}\nfunction readerAuthorizer(action: number, arg1: string | null, arg2: string | null, dbName: string | null): number {\n if (dbName === \"temp\") {\n const preparedTable = arg1 === \"niceeval_prepared_seal_raw\" || arg1 === \"niceeval_prepared_seal_ordered\";\n return preparedTable && (action === constants.SQLITE_READ || action === constants.SQLITE_INSERT || action === constants.SQLITE_DELETE)\n ? constants.SQLITE_OK\n : constants.SQLITE_DENY;\n }\n if (dbName !== null && dbName !== \"main\")\n return constants.SQLITE_DENY;\n if (READ_DENIED.has(action))\n return constants.SQLITE_DENY;\n if (action === constants.SQLITE_PRAGMA && arg1 !== \"quick_check\" && arg1 !== \"foreign_key_check\" && arg1 !== \"secure_delete\")\n return constants.SQLITE_DENY;\n if (action === constants.SQLITE_FUNCTION && arg2?.toLowerCase() === \"load_extension\")\n return constants.SQLITE_DENY;\n return constants.SQLITE_OK;\n}\nfunction schemaRows(db: DatabaseSync): readonly string[] {\n const rows = currentStatement(db, `SELECT type, name, tbl_name, sql FROM sqlite_schema\n WHERE name NOT LIKE 'sqlite_stat%' ORDER BY type, name LIMIT 257`).all() as unknown as readonly Record<string, SQLOutputValue>[];\n if (rows.length > 256)\n throw sqliteError(\"record-database-invalid\", \"validate-schema\", \"database schema exceeds the bounded object allowlist\");\n return rows.map((row) => JSON.stringify([\n decodeText(row.type, \"sqlite_schema.type\"),\n decodeText(row.name, \"sqlite_schema.name\"),\n decodeText(row.tbl_name, \"sqlite_schema.tbl_name\"),\n row.sql === null ? null : normalizeSql(decodeText(row.sql, \"sqlite_schema.sql\")),\n ]));\n}\nfunction normalizeSql(sql: string): string {\n return sql.replace(/\\s+/gu, \" \").replace(/\\s*([(),])\\s*/gu, \"$1\").trim().replace(/;$/u, \"\");\n}\nconst canonicalSchemaRows = new Map<string, readonly string[]>();\nfunction expectedSchemaRows(sql?: string): readonly string[] {\n const key = sql ?? \"bootstrap\";\n const cached = canonicalSchemaRows.get(key);\n if (cached !== undefined)\n return cached;\n const db = new DatabaseSync(\":memory:\", { allowExtension: false, defensive: true, readBigInts: true });\n try {\n db.exec(sql ?? RECORD_SQLITE_BASELINE_SQL);\n const rows = Object.freeze(schemaRows(db));\n canonicalSchemaRows.set(key, rows);\n return rows;\n }\n finally {\n db.close();\n }\n}\nfunction validateSchemaObjects(connection: RecordDatabase, sql?: string): void {\n const actual = schemaRows(connection.db);\n const expected = expectedSchemaRows(sql);\n if (actual.length !== expected.length || actual.some((row, index) => row !== expected[index])) {\n throw sqliteError(\"record-schema-unsupported\", \"validate-schema\", \"database objects do not match the exact Project Record schema allowlist\");\n }\n}\nfunction storageRevision(connection: RecordDatabase): number {\n const row = currentStatement(connection.db, \"SELECT storage_revision FROM ne18_record_metadata WHERE singleton=1\").get() as Record<string, SQLOutputValue> | undefined;\n if (row === undefined)\n throw sqliteError(\"record-schema-unsupported\", \"validate-schema\", \"ProjectDatabase identity is missing\");\n return decodeInteger(row.storage_revision, \"record_metadata.storage_revision\");\n}\nfunction validateExistingOperationalSchemaForWriter(connection: RecordDatabase): void {\n const revision = storageRevision(connection);\n if (revision === RECORD_SQLITE_STORAGE_REVISION) {\n validateExactSchema(connection);\n requireMigrationReady(connection);\n return;\n }\n throw sqliteError(\"record-schema-unsupported\", \"validate-schema\", `record storage revision ${revision} cannot be opened by revision ${RECORD_SQLITE_STORAGE_REVISION}`);\n}\nfunction decodeText(value: SQLOutputValue | undefined, field: string): string {\n if (typeof value !== \"string\")\n throw sqliteError(\"record-database-invalid\", \"decode\", `${field} is not text`);\n return value;\n}\nfunction decodeInteger(value: SQLOutputValue | undefined, field: string): number {\n const numeric = typeof value === \"bigint\" ? Number(value) : value;\n if (typeof numeric !== \"number\" || !Number.isSafeInteger(numeric)) {\n throw sqliteError(\"record-database-invalid\", \"decode\", `${field} is not a safe integer`);\n }\n return numeric;\n}\nfunction validateCurrentRecordDomain(connection: RecordDatabase): void {\n let metadata: Record<string, SQLOutputValue> | undefined;\n try {\n metadata = currentStatement(connection.db, `SELECT format,storage_revision,storage_generation,schema_fingerprint,barrier_state\n FROM ne18_record_metadata WHERE singleton=1`).get() as Record<string, SQLOutputValue> | undefined;\n }\n catch (cause) {\n throw sqliteError(\"record-schema-unsupported\", \"validate-schema\", \"database does not expose the ProjectDatabase identity\", cause);\n }\n if (metadata === undefined) {\n throw sqliteError(\"record-schema-unsupported\", \"validate-schema\", \"ProjectDatabase identity is missing\");\n }\n if (decodeText(metadata.format, \"record_metadata.format\") !== RECORD_SQLITE_FORMAT) {\n throw sqliteError(\"record-schema-unsupported\", \"validate-schema\", \"record format is unsupported\");\n }\n const revision = decodeInteger(metadata.storage_revision, \"record_metadata.storage_revision\");\n if (revision !== RECORD_SQLITE_STORAGE_REVISION) {\n throw sqliteError(\"record-schema-unsupported\", \"validate-schema\", `record storage revision ${revision} is not ${RECORD_SQLITE_STORAGE_REVISION}`);\n }\n if (decodeText(metadata.schema_fingerprint, \"record_metadata.schema_fingerprint\") !== RECORD_SQLITE_BASELINE_FINGERPRINT) {\n throw sqliteError(\"record-schema-unsupported\", \"validate-schema\", \"ProjectDatabase baseline fingerprint is unsupported\");\n }\n const barrierState = decodeText(metadata.barrier_state, \"record_metadata.barrier_state\");\n if (barrierState !== \"open\" && barrierState !== \"draining\" && barrierState !== \"portable\") {\n throw sqliteError(\"record-database-invalid\", \"validate-schema\", \"ProjectDatabase barrier state is invalid\");\n }\n validateSchemaObjects(connection);\n const coordination = currentStatement(connection.db, `SELECT revision,operational_generation,next_writer_sequence,\n writer_ticket_id,barrier_id FROM ne18_coordination_state WHERE singleton=1`).get() as Record<string, SQLOutputValue> | undefined;\n if (coordination === undefined) {\n throw sqliteError(\"record-database-invalid\", \"validate-schema\", \"host coordination generation is missing\");\n }\n const operationalGeneration = decodeText(coordination.operational_generation, \"coordination_state.operational_generation\");\n const storageGeneration = decodeText(metadata.storage_generation, \"record_metadata.storage_generation\");\n if (operationalGeneration !== storageGeneration) {\n throw sqliteError(\"record-database-invalid\", \"validate-schema\", \"operational coordination generation does not match ProjectDatabase\");\n }\n const migration = currentStatement(connection.db, \"SELECT state FROM ne18_migration_state WHERE singleton=1\").get() as Record<string, SQLOutputValue> | undefined;\n if (migration === undefined) {\n throw sqliteError(\"record-database-invalid\", \"validate-schema\", \"ProjectDatabase migration state is missing\");\n }\n const migrationState = decodeText(migration.state, \"migration_state.state\");\n if (migrationState !== \"committed\" && migrationState !== \"ready\") {\n throw sqliteError(\"record-database-invalid\", \"validate-schema\", \"ProjectDatabase migration state is invalid\");\n }\n}\nfunction requireMigrationReady(connection: RecordDatabase): void {\n const row = currentStatement(connection.db, \"SELECT state FROM ne18_migration_state WHERE singleton=1\").get() as Record<string, SQLOutputValue> | undefined;\n if (row === undefined || decodeText(row.state, \"migration_state.state\") !== \"ready\") {\n throw sqliteError(\"record-schema-migration-required\", \"open\", \"ProjectDatabase migration committed but requires Host verification\");\n }\n}\nexport function validateExactSchema(connection: RecordDatabase): void {\n requireSecureDelete(connection.db);\n validateCurrentRecordDomain(connection);\n}\nexport function openRecordWriter(path: string, busyTimeoutMs = 5000): RecordDatabase {\n assertRecordSqliteRuntime();\n assertLegacyRecordAbsent(path);\n assertLegacyCoordinationEntriesAbsent(path);\n const existed = pathExists(path);\n if (existed) {\n const metadata = lstatSync(path);\n if (!metadata.isFile() || metadata.isSymbolicLink()) {\n throw sqliteError(\"record-schema-unsupported\", \"open\", \"ProjectDatabase path is not a regular Host-owned file\");\n }\n }\n mkdirSync(dirname(path), { recursive: true, mode: 0o700 });\n const db = new DatabaseSync(path, {\n allowExtension: false,\n defensive: true,\n enableForeignKeyConstraints: true,\n readBigInts: true,\n timeout: Math.max(0, Math.min(30000, Math.trunc(busyTimeoutMs))),\n });\n const connection: RecordDatabase = { db, path, mode: \"writer\", statements: new Map() };\n try {\n configureCommon(db);\n const objectCount = currentStatement(db, \"SELECT count(*) AS count FROM sqlite_schema\").get() as Record<string, SQLOutputValue>;\n const isEmpty = decodeInteger(objectCount.count, \"sqlite_schema.count\") === 0;\n if (isEmpty && existed) {\n throw sqliteError(\"record-schema-unsupported\", \"open\", \"existing empty SQLite is not a ProjectDatabase\");\n }\n // Never persist WAL mode or acquire a write transaction until an existing\n // file has proved that it is the exact Host-owned ProjectDatabase format.\n if (!isEmpty) {\n validateExistingOperationalSchemaForWriter(connection);\n requireSecureDelete(db);\n }\n else {\n db.exec(\"PRAGMA secure_delete=ON\");\n requireSecureDelete(db);\n }\n db.exec(\"PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;\");\n let created = false;\n try {\n if (isEmpty) {\n const appliedAt = new Date().toISOString();\n const generation = randomUUID();\n db.exec(\"BEGIN IMMEDIATE\");\n try {\n db.exec(RECORD_SQLITE_BASELINE_SQL);\n currentStatement(db, `INSERT INTO ne18_record_metadata(singleton,format,storage_revision,storage_generation,schema_fingerprint,\n created_at,barrier_state,portable_generation,portable_revision,portable_gate_id,record_payload,record_digest)\n VALUES (1,?,?,?,?,?,'open',NULL,NULL,NULL,NULL,NULL)`).run(RECORD_SQLITE_FORMAT, RECORD_SQLITE_STORAGE_REVISION, generation, RECORD_SQLITE_BASELINE_FINGERPRINT, appliedAt);\n currentStatement(db, `INSERT INTO ne18_coordination_state(singleton,revision,operational_generation,next_writer_sequence)\n VALUES (1,0,?,1)`).run(generation);\n currentStatement(db, `INSERT INTO ne18_migration_state(singleton,state,source_format,source_digest)\n VALUES (1,'ready',NULL,NULL)`).run();\n db.exec(\"COMMIT\");\n created = true;\n }\n catch (cause) {\n if (db.isTransaction)\n db.exec(\"ROLLBACK\");\n throw cause;\n }\n }\n else {\n // Revalidate under the write lock so a concurrent schema change cannot\n // cross the admission boundary between the read probe and this writer.\n validateExistingOperationalSchemaForWriter(connection);\n }\n }\n catch (cause) {\n throw cause;\n }\n // Both the creator and every concurrent loser validate the exact committed\n // bootstrap identity before the connection becomes a writer.\n validateExactSchema(connection);\n requireMigrationReady(connection);\n if (created)\n db.exec(\"PRAGMA wal_checkpoint(PASSIVE)\");\n db.setAuthorizer(writableAuthorizer());\n return connection;\n }\n catch (cause) {\n db.close();\n throw cause;\n }\n}\n/** Host admission path: reject legacy coordination before any in-place migration mutation. */\nexport async function openHostOwnedRecordWriter(path: string, busyTimeoutMs = 5000): Promise<RecordDatabase> {\n assertRecordSqliteRuntime();\n assertLegacyRecordAbsent(path);\n assertLegacyCoordinationEntriesAbsent(path);\n const { migrateHostOwnedProjectDatabase } = await __niceevalDynamicImport(\"./migration.cjs\");\n await migrateHostOwnedProjectDatabase(path, busyTimeoutMs);\n return openRecordWriter(path, busyTimeoutMs);\n}\nexport function openRecordReader(path: string): RecordDatabase {\n assertRecordSqliteRuntime();\n return openRecordReaderAfterRuntimeAdmission(path);\n}\nexport function openImmutableRecordReader(path: string): RecordDatabase {\n assertImmutableRecordReaderRuntime();\n return openRecordReaderAfterRuntimeAdmission(path);\n}\nfunction openRecordReaderAfterRuntimeAdmission(path: string): RecordDatabase {\n assertLegacyRecordAbsent(path);\n const db = new DatabaseSync(path, {\n allowExtension: false,\n defensive: true,\n enableForeignKeyConstraints: true,\n readBigInts: true,\n readOnly: true,\n timeout: 0,\n });\n const connection: RecordDatabase = { db, path, mode: \"reader\", statements: new Map() };\n try {\n configureCommon(db);\n requireSecureDelete(db);\n const legacyTable = db.prepare(`SELECT count(*) AS count FROM sqlite_schema\n WHERE type='table' AND name='record_metadata'`).get() as Record<string, SQLOutputValue>;\n if (decodeInteger(legacyTable.count, \"sqlite_schema.record_metadata\") === 1) {\n const legacy = db.prepare(\"SELECT format FROM record_metadata WHERE singleton=1\").get() as Record<string, SQLOutputValue> | undefined;\n const format = legacy?.format;\n if (format === \"niceeval.project-database/0.15\" || format === \"niceeval.project-database/0.16\") {\n throw sqliteError(\"record-schema-unsupported\", \"open\", `${format} cannot be opened through the current-format operational reader. Finish the old writer and provide a portable Record for read-time migration, or upgrade through the Host-owned project writer`);\n }\n }\n // The main database is opened read-only. These two private TEMP tables are\n // the only writable reader state and are required for bounded Seal sort.\n db.exec(RECORD_SQLITE_PREPARED_SEAL_TEMP_SQL);\n db.setAuthorizer(readerAuthorizer);\n validateExactSchema(connection);\n requireMigrationReady(connection);\n // Full structure and closure validation belongs to import, publication and\n // maintenance. Opening a Host-owned reader must not scan historical payload.\n return connection;\n }\n catch (cause) {\n db.close();\n throw cause;\n }\n}\nexport function openRecordMaintenance(path: string): RecordDatabase {\n assertRecordSqliteRuntime();\n assertLegacyRecordAbsent(path);\n if (!pathExists(path)) {\n throw sqliteError(\"record-database-invalid\", \"open-maintenance\", \"ProjectDatabase does not exist\");\n }\n const metadata = lstatSync(path);\n if (!metadata.isFile() || metadata.isSymbolicLink()) {\n throw sqliteError(\"record-schema-unsupported\", \"open-maintenance\", \"ProjectDatabase path is not a regular Host-owned file\");\n }\n const db = new DatabaseSync(path, {\n allowExtension: false,\n defensive: true,\n enableForeignKeyConstraints: true,\n readBigInts: true,\n timeout: 5000,\n });\n const connection: RecordDatabase = { db, path, mode: \"maintenance\", statements: new Map() };\n try {\n configureCommon(db);\n db.setAuthorizer(writableAuthorizer());\n return connection;\n }\n catch (cause) {\n db.close();\n throw cause;\n }\n}\nexport function closeRecordDatabase(connection: RecordDatabase): void {\n // node:sqlite finalizes every cached statement when its owning connection is\n // closed; StatementSync intentionally exposes no independent finalize API.\n connection.statements.clear();\n if (connection.db.isOpen)\n connection.db.close();\n}\nexport function checkpointRecordDatabase(connection: RecordDatabase): void {\n if (connection.mode !== \"writer\" || !connection.db.isOpen) {\n throw sqliteError(\"record-database-invalid\", \"checkpoint\", \"Record checkpoint requires an open writer\");\n }\n connection.db.exec(\"PRAGMA wal_checkpoint(TRUNCATE)\");\n}\n/** Starts a new operational generation before coordination services acquire it. */\nexport function reopenProjectDatabase(path: string): void {\n const connection = openRecordWriter(path);\n try {\n connection.db.exec(\"BEGIN IMMEDIATE\");\n const row = currentStatement(connection.db, \"SELECT barrier_state FROM ne18_record_metadata WHERE singleton=1\")\n .get() as Record<string, SQLOutputValue> | undefined;\n if (row === undefined || decodeText(row.barrier_state, \"barrier_state\") === \"draining\") {\n throw sqliteError(\"record-command-conflict\", \"reopen\", \"ProjectDatabase portable gate is draining\");\n }\n if (decodeText(row.barrier_state, \"barrier_state\") === \"portable\") {\n const generation = randomUUID();\n currentStatement(connection.db, `UPDATE ne18_record_metadata SET barrier_state='open',storage_generation=?,portable_generation=NULL,\n portable_revision=NULL,portable_gate_id=NULL WHERE singleton=1 AND barrier_state='portable'`).run(generation);\n currentStatement(connection.db, \"UPDATE ne18_coordination_state SET operational_generation=?,revision=revision+1 WHERE singleton=1\")\n .run(generation);\n }\n connection.db.exec(\"COMMIT\");\n }\n catch (cause) {\n if (connection.db.isTransaction)\n connection.db.exec(\"ROLLBACK\");\n throw cause;\n }\n finally {\n closeRecordDatabase(connection);\n }\n}\n/**\n * Closes the project-wide writer admission and proves that the canonical file\n * itself is portable. The first transaction deliberately persists draining;\n * any later failure therefore remains fail-closed for explicit recovery.\n */\nexport function makeProjectDatabasePortable(path: string): boolean {\n const gateId = randomUUID();\n const gateNonce = randomUUID();\n const gateOwner = currentProcessOwnerIdentity(gateId);\n const admissionDrainDeadline = Date.now() + 5000;\n const waitCell = new Int32Array(new SharedArrayBuffer(4));\n let connection = openRecordWriter(path);\n try {\n connection.db.exec(\"BEGIN IMMEDIATE\");\n const metadata = currentStatement(connection.db, \"SELECT barrier_state,portable_gate_id FROM ne18_record_metadata WHERE singleton=1\")\n .get() as Record<string, SQLOutputValue> | undefined;\n if (metadata === undefined) {\n throw sqliteError(\"record-database-invalid\", \"portable-gate\", \"ProjectDatabase barrier is missing\");\n }\n const barrierState = decodeText(metadata.barrier_state, \"barrier_state\");\n if (barrierState === \"portable\") {\n connection.db.exec(\"COMMIT\");\n return true;\n }\n if (barrierState === \"draining\") {\n const previous = currentStatement(connection.db, `SELECT barrier_id,barrier_nonce,barrier_host,barrier_pid,\n barrier_boot_id,barrier_process_start FROM ne18_coordination_state WHERE singleton=1`).get() as Record<string, SQLOutputValue> | undefined;\n if (previous === undefined || previous.barrier_id === null || previous.barrier_nonce === null) {\n throw sqliteError(\"record-database-invalid\", \"portable-gate\", \"draining portable gate has no fenced owner\");\n }\n const previousOwner = {\n ownerId: decodeText(previous.barrier_id, \"barrier_id\"),\n host: decodeText(previous.barrier_host, \"barrier_host\"),\n pid: decodeInteger(previous.barrier_pid, \"barrier_pid\"),\n bootId: decodeText(previous.barrier_boot_id, \"barrier_boot_id\"),\n processStart: decodeText(previous.barrier_process_start, \"barrier_process_start\"),\n };\n const sameProcess = previousOwner.host === gateOwner.host && previousOwner.pid === gateOwner.pid &&\n previousOwner.bootId === gateOwner.bootId && previousOwner.processStart === gateOwner.processStart;\n if (!sameProcess && exactProcessState(previousOwner) !== \"dead\") {\n throw sqliteError(\"record-command-conflict\", \"portable-gate\", \"draining portable gate owner is not proven dead\");\n }\n const fenced = currentStatement(connection.db, `UPDATE ne18_coordination_state SET barrier_id=?,barrier_nonce=?,barrier_host=?,\n barrier_pid=?,barrier_boot_id=?,barrier_process_start=?,barrier_deadline=?,barrier_requested_at=?,\n barrier_lease_expires_at=?,barrier_status='active',barrier_active_at=?,revision=revision+1\n WHERE singleton=1 AND barrier_id=? AND barrier_nonce=?`).run(gateId, gateNonce, gateOwner.host, gateOwner.pid, gateOwner.bootId, gateOwner.processStart, admissionDrainDeadline, Date.now(), admissionDrainDeadline, Date.now(), previous.barrier_id, previous.barrier_nonce);\n const metadataFenced = currentStatement(connection.db, `UPDATE ne18_record_metadata SET portable_gate_id=?\n WHERE singleton=1 AND barrier_state='draining' AND portable_gate_id=?`).run(gateId, metadata.portable_gate_id);\n if (Number(fenced.changes) !== 1 || Number(metadataFenced.changes) !== 1) {\n throw sqliteError(\"record-command-conflict\", \"portable-gate\", \"draining portable gate changed during recovery\");\n }\n }\n else if (barrierState === \"open\") {\n const entered = recordStatement(connection, `UPDATE ne18_record_metadata SET barrier_state='draining',portable_gate_id=?\n WHERE singleton=1 AND barrier_state='open' AND portable_gate_id IS NULL`).run(gateId);\n const established = currentStatement(connection.db, `UPDATE ne18_coordination_state SET barrier_id=?,barrier_nonce=?,barrier_host=?,\n barrier_pid=?,barrier_boot_id=?,barrier_process_start=?,barrier_deadline=?,barrier_requested_at=?,\n barrier_lease_expires_at=?,barrier_status='active',barrier_active_at=?,revision=revision+1\n WHERE singleton=1 AND barrier_id IS NULL`).run(gateId, gateNonce, gateOwner.host, gateOwner.pid, gateOwner.bootId, gateOwner.processStart, admissionDrainDeadline, Date.now(), admissionDrainDeadline, Date.now());\n if (Number(entered.changes) !== 1 || Number(established.changes) !== 1) {\n throw sqliteError(\"record-command-conflict\", \"portable-gate\", \"ProjectDatabase barrier is not open\");\n }\n }\n else {\n throw sqliteError(\"record-database-invalid\", \"portable-gate\", \"ProjectDatabase barrier state is invalid\");\n }\n const admittedActive = currentStatement(connection.db, `SELECT\n (SELECT count(*) FROM ne18_run_resources WHERE terminal_state IS NULL)+\n (SELECT count(*) FROM ne18_invocation_sessions WHERE state IN ('active','recovering'))+\n (SELECT count(*) FROM ne18_case_locks)+\n (SELECT count(*) FROM ne18_teardown_obligations)+\n (SELECT count(*) FROM ne18_shared_state_generations s WHERE state_kind!='free' AND generation=(SELECT max(generation) FROM ne18_shared_state_generations WHERE state_key=s.state_key))+\n (SELECT count(*) FROM ne18_kept_sandbox_operation_leases) AS count`)\n .get() as Record<string, SQLOutputValue>;\n if (decodeInteger(admittedActive.count, \"active_runs\") !== 0) {\n currentStatement(connection.db, `UPDATE ne18_record_metadata SET barrier_state='open',portable_gate_id=NULL\n WHERE singleton=1 AND barrier_state='draining' AND portable_gate_id=?`).run(gateId);\n currentStatement(connection.db, `UPDATE ne18_coordination_state SET barrier_id=NULL,barrier_nonce=NULL,barrier_host=NULL,\n barrier_pid=NULL,barrier_boot_id=NULL,barrier_process_start=NULL,barrier_deadline=NULL,\n barrier_requested_at=NULL,barrier_lease_expires_at=NULL,barrier_status=NULL,barrier_active_at=NULL,\n revision=revision+1 WHERE singleton=1 AND barrier_id=? AND barrier_nonce=?`).run(gateId, gateNonce);\n connection.db.exec(\"COMMIT\");\n return false;\n }\n // The draining barrier rejects new tickets. Queued-but-not-admitted work\n // has no writer authority and is canceled; an already admitted writer or\n // barrier must release its exact identity before the gate continues.\n currentStatement(connection.db, \"DELETE FROM ne18_coordination_tickets\").run();\n connection.db.exec(\"COMMIT\");\n while (true) {\n const coordination = currentStatement(connection.db, `SELECT\n (writer_ticket_id IS NOT NULL OR (barrier_id IS NOT NULL AND barrier_id!=?)) AS active\n FROM ne18_coordination_state WHERE singleton=1`).get(gateId) as Record<string, SQLOutputValue> | undefined;\n if (coordination === undefined) {\n throw sqliteError(\"record-database-invalid\", \"portable-gate\", \"coordination singleton is missing\");\n }\n if (decodeInteger(coordination.active, \"portable_admission\") === 0)\n break;\n if (Date.now() >= admissionDrainDeadline) {\n throw sqliteError(\"record-write-busy\", \"portable-gate\", \"admitted writer did not drain before the portable deadline\");\n }\n Atomics.wait(waitCell, 0, 0, 15);\n }\n connection.db.exec(\"BEGIN IMMEDIATE\");\n const active = currentStatement(connection.db, \"SELECT count(*) AS count FROM ne18_run_resources WHERE terminal_state IS NULL\")\n .get() as Record<string, SQLOutputValue>;\n if (decodeInteger(active.count, \"active_runs\") !== 0) {\n throw sqliteError(\"record-command-conflict\", \"portable-gate\", \"active Run owners prevent portable close\");\n }\n const invocationWork = currentStatement(connection.db, `SELECT\n (SELECT count(*) FROM ne18_invocation_sessions WHERE state IN ('active','recovering'))+\n (SELECT count(*) FROM ne18_invocation_session_queued_attempts)+\n (SELECT count(*) FROM ne18_case_locks) AS count`).get() as Record<string, SQLOutputValue>;\n if (decodeInteger(invocationWork.count, \"invocation_work\") !== 0) {\n throw sqliteError(\"record-command-conflict\", \"portable-gate\", \"invocation coordination work prevents portable close\");\n }\n currentExec(connection.db, `DELETE FROM ne18_runs WHERE status!='sealed' AND NOT EXISTS\n (SELECT 1 FROM ne18_attempt_publications WHERE origin_run_id=ne18_runs.run_id); DELETE FROM ne18_coordination_tickets;`);\n currentStatement(connection.db, `UPDATE ne18_coordination_state SET revision=revision+1,next_writer_sequence=1,\n writer_ticket_id=NULL,writer_sequence=NULL,writer_host=NULL,writer_pid=NULL,writer_deadline=NULL,\n writer_boot_id=NULL,writer_process_start=NULL,\n writer_enqueued_at=NULL,writer_nonce=NULL,writer_admitted_at=NULL,writer_lease_expires_at=NULL,\n barrier_id=NULL,barrier_nonce=NULL,barrier_host=NULL,barrier_pid=NULL,barrier_deadline=NULL,\n barrier_boot_id=NULL,barrier_process_start=NULL,\n barrier_requested_at=NULL,barrier_lease_expires_at=NULL,barrier_status=NULL,barrier_active_at=NULL\n WHERE singleton=1`).run();\n const clock = currentStatement(connection.db, \"SELECT revision FROM ne18_run_publication_clock WHERE singleton=1\")\n .get() as Record<string, SQLOutputValue>;\n const generation = currentStatement(connection.db, \"SELECT storage_generation FROM ne18_record_metadata WHERE singleton=1\")\n .get() as Record<string, SQLOutputValue>;\n currentStatement(connection.db, `UPDATE ne18_record_metadata SET barrier_state='portable',portable_generation=?,portable_revision=?\n WHERE singleton=1 AND barrier_state='draining' AND portable_gate_id=?`).run(decodeText(generation.storage_generation, \"storage_generation\"), decodeInteger(clock.revision, \"publication_revision\"), gateId);\n connection.db.exec(\"COMMIT\");\n checkpointRecordDatabase(connection);\n }\n catch (cause) {\n if (connection.db.isTransaction)\n connection.db.exec(\"ROLLBACK\");\n throw cause;\n }\n finally {\n closeRecordDatabase(connection);\n }\n connection = openRecordReader(path);\n try {\n const state = currentStatement(connection.db, `SELECT barrier_state,portable_generation,portable_revision,storage_generation\n FROM ne18_record_metadata WHERE singleton=1`).get() as Record<string, SQLOutputValue> | undefined;\n const active = currentStatement(connection.db, `SELECT\n (SELECT count(*) FROM ne18_run_resources WHERE terminal_state IS NULL)+\n (SELECT count(*) FROM ne18_runs r WHERE status!='sealed' AND\n (EXISTS (SELECT 1 FROM ne18_attempts a WHERE a.origin_run_id=r.run_id AND a.publication_state!='published') OR\n EXISTS (SELECT 1 FROM ne18_run_resources rr WHERE rr.run_id=r.run_id AND rr.terminal_state IS NULL)))+\n (SELECT count(*) FROM ne18_coordination_tickets) AS count`).get() as Record<string, SQLOutputValue>;\n const invocationWork = currentStatement(connection.db, `SELECT\n (SELECT count(*) FROM ne18_invocation_sessions WHERE state IN ('active','recovering'))+\n (SELECT count(*) FROM ne18_invocation_session_queued_attempts)+\n (SELECT count(*) FROM ne18_case_locks) AS count`).get() as Record<string, SQLOutputValue>;\n const registryWork = currentStatement(connection.db, `SELECT\n (SELECT count(*) FROM ne18_teardown_obligations)+\n (SELECT count(*) FROM ne18_shared_state_generations s WHERE state_kind!='free' AND generation=(SELECT max(generation) FROM ne18_shared_state_generations WHERE state_key=s.state_key))+\n (SELECT count(*) FROM ne18_kept_sandbox_operation_leases) AS count`).get() as Record<string, SQLOutputValue>;\n const coordination = currentStatement(connection.db, `SELECT writer_ticket_id,barrier_id FROM ne18_coordination_state WHERE singleton=1`)\n .get() as Record<string, SQLOutputValue> | undefined;\n const clock = currentStatement(connection.db, \"SELECT revision FROM ne18_run_publication_clock WHERE singleton=1\")\n .get() as Record<string, SQLOutputValue> | undefined;\n if (state === undefined || decodeText(state.barrier_state, \"barrier_state\") !== \"portable\" ||\n decodeText(state.portable_generation, \"portable_generation\") !== decodeText(state.storage_generation, \"storage_generation\") ||\n clock === undefined || decodeInteger(state.portable_revision, \"portable_revision\") !== decodeInteger(clock.revision, \"publication_revision\") ||\n decodeInteger(active.count, \"portable_work\") !== 0 ||\n decodeInteger(invocationWork.count, \"portable_invocation_work\") !== 0 ||\n decodeInteger(registryWork.count, \"portable_registry_work\") !== 0 ||\n coordination === undefined || coordination.writer_ticket_id !== null || coordination.barrier_id !== null) {\n throw sqliteError(\"record-database-invalid\", \"portable-gate\", \"hostile reopen did not prove a portable ProjectDatabase\");\n }\n }\n finally {\n closeRecordDatabase(connection);\n }\n return true;\n}\n/** Invocation-boundary portable operation; terminal session projections remain durable. */\nexport const finalizeInvocationPortable = makeProjectDatabasePortable;\n"]}
@@ -43,7 +43,7 @@ Object.defineProperty(exports, "RECORD_SQLITE_MAX_VALIDATION_ROWS", { enumerable
43
43
  Object.defineProperty(exports, "RECORD_SQLITE_MAX_VALIDATION_RUNS", { enumerable: true, get: function () { return types_ts_2.RECORD_SQLITE_MAX_VALIDATION_RUNS; } });
44
44
  Object.defineProperty(exports, "RECORD_SQLITE_VALIDATION_DEADLINE_MS", { enumerable: true, get: function () { return types_ts_2.RECORD_SQLITE_VALIDATION_DEADLINE_MS; } });
45
45
  Object.defineProperty(exports, "RECORD_SQLITE_STORAGE_REVISION", { enumerable: true, get: function () { return types_ts_2.RECORD_SQLITE_STORAGE_REVISION; } });
46
- function openPinnedRecordReadSession(path, kind, deadlineEpochMs, validation = "complete") {
46
+ function openPinnedRecordReadSession(path, kind, deadlineEpochMs) {
47
47
  if (!Number.isSafeInteger(deadlineEpochMs) || deadlineEpochMs <= Date.now()) {
48
48
  throw (0, errors_ts_1.sqliteError)("record-resource-limit-exceeded", "open-read-session", "pinned read deadline must be a future safe integer");
49
49
  }
@@ -78,23 +78,23 @@ function openPinnedRecordReadSession(path, kind, deadlineEpochMs, validation = "
78
78
  return result;
79
79
  };
80
80
  try {
81
- // BEGIN occurs before the authoritative schema + Seal pass. Every later
81
+ // BEGIN occurs before the authoritative schema pass. Every later
82
82
  // read observes this same WAL/file generation until close rolls it back.
83
83
  connection.db.exec("BEGIN");
84
84
  const publicationCutoff = (0, sqlite_ts_1.currentPublicationCutoffOnConnection)(connection);
85
85
  const cutoffIdentity = (0, cutoff_ts_1.publicationCutoffIdentity)(publicationCutoff);
86
86
  (0, database_ts_1.validateExactSchema)(connection);
87
- if (validation === "complete") {
88
- (0, storage_ts_1.verifyAllSealedRuns)(connection, false, deadlineEpochMs);
89
- }
90
- else if (kind !== "private-generation") {
91
- throw (0, errors_ts_1.sqliteError)("record-database-invalid", "open-read-session", "only an admitted private generation may skip repeated validation");
92
- }
87
+ // Both sources have an admission owner: the project writer or the hostile
88
+ // importer. Re-check selected facts, not every historical Seal, on reads.
89
+ let sealedCutoff;
90
+ const readCutoff = () => sealedCutoff ??= readBounded("read-sealed-cutoff", () => (0, storage_ts_1.readSealedRunCutoff)(connection, cutoffIdentity));
93
91
  assertUsable("open-read-session");
94
92
  return Object.freeze({
95
93
  kind,
96
94
  deadlineEpochMs,
97
95
  publicationCutoff: () => publicationCutoff,
96
+ sealedCutoff: readCutoff,
97
+ findExperimentRunIds: (experimentId) => readBounded("find-experiment-runs", () => (0, storage_ts_1.findExperimentRunIds)(connection, experimentId)),
98
98
  readRunResource: (runId) => readBounded("read-run-resource", () => (0, sqlite_ts_1.readRunResourceOnConnection)(connection, runId, publicationCutoff)),
99
99
  listRunResources: (input) => readBounded("list-run-resources", () => (0, sqlite_ts_1.listRunResourcesOnConnection)(connection, { ...input, cutoff: input?.cutoff ?? publicationCutoff })),
100
100
  readSealedRunSummary: (runId) => readBounded("read-sealed-run-summary", () => (0, storage_ts_1.readSealedRunSummary)(connection, runId)),
@@ -102,7 +102,7 @@ function openPinnedRecordReadSession(path, kind, deadlineEpochMs, validation = "
102
102
  if (expectedCutoffIdentity !== undefined && expectedCutoffIdentity !== cutoffIdentity) {
103
103
  throw (0, errors_ts_1.sqliteError)("record-command-conflict", "page-sealed-runs", "publication cutoff changed; restart pagination");
104
104
  }
105
- const page = (0, storage_ts_1.readSealedRunSummaryPage)(connection, afterRunId, pageSize, undefined, deadlineEpochMs);
105
+ const page = (0, storage_ts_1.readSealedRunSummaryPage)(connection, afterRunId, pageSize, undefined, deadlineEpochMs, readCutoff());
106
106
  return Object.freeze({
107
107
  ...page,
108
108
  cutoff: Object.freeze({ ...page.cutoff, identity: cutoffIdentity }),
@@ -110,7 +110,9 @@ function openPinnedRecordReadSession(path, kind, deadlineEpochMs, validation = "
110
110
  }),
111
111
  findAttemptLocatorCandidates: (locator, maximumCandidateRuns) => readBounded("find-attempt-locator", () => (0, storage_ts_1.findAttemptLocatorCandidates)(connection, locator, maximumCandidateRuns)),
112
112
  readSealedRunDocument: (runId) => readBounded("read-sealed-run-document", () => (0, storage_ts_1.readSealedRunDocument)(connection, runId)),
113
- readSealedRunCore: (runId) => readBounded("read-sealed-run-core", () => (0, storage_ts_1.readSealedRunCore)(connection, runId)),
113
+ readSealedRunCore: (runId, lazyAttachments = false) => readBounded("read-sealed-run-core", () => (0, storage_ts_1.readSealedRunCore)(connection, runId, lazyAttachments
114
+ ? (read) => readBounded("read-sealed-attachment", read)
115
+ : undefined)),
114
116
  readContentChunkPage: (contentId, afterOrdinal, pageSize) => readBounded("read-content-page", () => (0, storage_ts_1.readContentChunkPage)(connection, contentId, afterOrdinal, pageSize)),
115
117
  readCollectionItemPage: (attachmentId, afterOrdinal, pageSize) => readBounded("read-collection-page", () => (0, storage_ts_1.readCollectionItemPage)(connection, attachmentId, afterOrdinal, pageSize)),
116
118
  close,
@@ -140,7 +142,7 @@ exports.acquireProjectRecordReadSession = effect_1.Effect.fn("acquireProjectReco
140
142
  });
141
143
  /** Opens only a private generation already admitted by the hostile importer. */
142
144
  function openHostOwnedRecordReadSession(generationPath, deadlineEpochMs = Date.now() + types_ts_1.RECORD_SQLITE_VALIDATION_DEADLINE_MS) {
143
- return openPinnedRecordReadSession(generationPath, "private-generation", deadlineEpochMs, "host-validated-generation");
145
+ return openPinnedRecordReadSession(generationPath, "private-generation", deadlineEpochMs);
144
146
  }
145
147
  function withSession(session, use) {
146
148
  try {