diff --git a/docs/o08-durable-resume-decision-packet.md b/docs/o08-durable-resume-decision-packet.md index 2d6c3fa..6d494ae 100644 --- a/docs/o08-durable-resume-decision-packet.md +++ b/docs/o08-durable-resume-decision-packet.md @@ -1,12 +1,13 @@ # O08 durable-resume decision packet -Status: proposal for contract-owner review. This document does not change the -prototype, define a released contract, authorize persistent storage, or claim -O08 completion. It contains no private creative material. +Status: the narrow synthetic resume scope was accepted by the contract owner +on 2026-11-08; the local storage trust boundary is selected below. This does +not define a released contract or claim O08 completion. It contains no private +creative material. ## Current evidence and gap -Platform `main` at `2466db85c13b8f16038d147a0d650614535198c5` has a bounded +Platform `main` at `94e4fe60c84a455b524d14f57b1adaa4c4ad7c9f` has a bounded same-process retry. The first attempt is retry-eligible only when its verified provider outcome is the exact rate-limit-before-acceptance case. Explicit retry then rechecks current authority and immutable evidence, honors the original @@ -70,7 +71,7 @@ before-acceptance rate-limit outcome. On restart: This path avoids duplicate effects by requiring evidence that the prior request was not accepted. It does not promise deduplication across attempts or providers. -## Owner decisions required before implementation +## Production decisions remain outside the accepted synthetic scope ### 1. Deadline across process restart @@ -112,6 +113,45 @@ request fingerprint binding, deduplication retention, and the response returned for a duplicate. A fresh key per attempt cannot suppress a duplicate effect. Provider Execution v1's key field alone does not establish those semantics. +## Accepted first-resume contract and selected local trust boundary — 2026-11-08 + +Andy (@andrewperis), as contract owner, approved the narrow first-resume scope: +resume only from a fully committed, terminal first-attempt result that proves +the provider rejected the request before acceptance; recheck current authority +and the original time bounds; quarantine uncertain outcomes rather than replay +them. This does not authorize generic exactly-once claims or provider +deduplication. + +For the first local synthetic implementation slice, use a caller-selected, +owner-controlled directory on a supported local filesystem, with an existing, +durably provisioned owner-controlled parent. The implementation checks private +directory/file modes, current-user ownership where the platform exposes it, +and rejects symlinked roots/files. Initialization fsyncs the store root and its +parent, then each child directory and its parent, before it returns. The caller +must ensure the path is on supported local storage; network/shared filesystem +detection is not reliable and such filesystems are outside this contract. Store +one canonical newline-delimited lifecycle event log per job and immutable +blobs created exclusively. Event and blob writes are not reported successful +until `fsync`, exact read-back and pending-marker removal are confirmed. A +pending marker after a crash makes the record unknown and requires +reconciliation. Use an exclusive per-job claim marker; never expire, steal, or +automatically release a claim after restart. A malformed log, partial blob, or +ambiguous claim/write is unknown. No provider call occurs from this +storage-only slice. + +Trust assumption: the filesystem, OS account boundary, and directory owner are +trusted against malicious modification by the same account or an administrator. +Stored digests detect mismatch against trusted event metadata; they do not +authenticate an event log and do not resist an actor who can rewrite both data +and metadata. No signing key or separate integrity service is introduced. + +The implementation is deliberately split at the storage boundary to fit the +issue's 1–2 focused-day cap: this slice supplies local persistent store and +claim primitives plus restart/corruption tests, but does not reconstruct jobs +or dispatch resumed attempts. Writable resume rehydration and effect +authorization remain the next bounded implementation slice. O09 remains open +and is not satisfied by this store primitive. + ## Finite synthetic restart and crash-point fixtures All rows use the existing exact synthetic production, an injected deterministic @@ -198,9 +238,10 @@ durable store/time authority, prove storage authenticity, or satisfy O08. ## Scope estimate and exclusions -The decision packet is a review artifact and fits within the discovery portion -of O08. A runtime implementation should be re-estimated after the owner selects -the deadline and storage guarantees; it likely exceeds the existing two-focused- -day bound if it includes production-grade persistent storage or a real provider -deduplication integration. This proposal does not change schemas, add storage, -introduce a provider, alter current retry behavior, close O08, or unblock O09. +The owner-approved local store slice is estimated at 1–2 focused days, including +focused tests and handoff. The complete writable-resume/reconstruction flow is +estimated above that bound and is intentionally split. Production-grade +persistent storage, an authenticated integrity root, provider-specific +deduplication, and O09's result linkage remain separate decisions. This slice +does not introduce a provider, alter current retry behavior, close O08, or +unblock O09. diff --git a/src/offline-orchestration-prototype/local-file-store.js b/src/offline-orchestration-prototype/local-file-store.js new file mode 100644 index 0000000..18e6118 --- /dev/null +++ b/src/offline-orchestration-prototype/local-file-store.js @@ -0,0 +1,441 @@ +import { + closeSync, constants, fstatSync, fsyncSync, lstatSync, mkdirSync, + openSync, readFileSync, readdirSync, renameSync, unlinkSync, writeSync +} from 'node:fs'; +import { randomUUID } from 'node:crypto'; +import { dirname, isAbsolute, join, resolve } from 'node:path'; +import { canonicalJson } from '../prompt-sdk/canonical-json.js'; +import { OFFLINE_ORCHESTRATION_LIMITS } from './limits.js'; +import { UNKNOWN_STORE_STATE } from './memory-store.js'; + +const PRIVATE_DIRECTORY_MODE = 0o700; +const PRIVATE_FILE_MODE = 0o600; +const NOFOLLOW = constants.O_NOFOLLOW ?? 0; +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; +const NATIVE_BOOTSTRAP_FILESYSTEM = Object.freeze({ mkdirSync, lstatSync, openSync, fsyncSync, closeSync }); + +function cloneFrozen(value) { + const cloned = JSON.parse(canonicalJson(value)); + const freeze = item => { + if (!item || typeof item !== 'object' || Object.isFrozen(item)) return item; + for (const child of Object.values(item)) freeze(child); + return Object.freeze(item); + }; + return freeze(cloned); +} + +function safeId(value, label) { + if (typeof value !== 'string' || !value || Buffer.byteLength(value, 'utf8') > 128) { + throw new TypeError(`Invalid local store ${label}.`); + } + return value; +} + +function validUuid(value) { return typeof value === 'string' && UUID.test(value); } + +function encoded(value) { + return Buffer.from(value, 'utf8').toString('base64url'); +} + +function decoded(value) { + const bytes = Buffer.from(value, 'base64url'); + if (bytes.toString('base64url') !== value) return undefined; + const text = bytes.toString('utf8'); + return Buffer.from(text, 'utf8').equals(bytes) ? text : undefined; +} + +function ensurePrivateDirectory(path, parentPath, filesystem) { + try { filesystem.mkdirSync(path, { mode: PRIVATE_DIRECTORY_MODE }); } catch (error) { + if (error.code !== 'EEXIST') throw error; + } + const info = filesystem.lstatSync(path); + const uid = typeof process.getuid === 'function' ? process.getuid() : undefined; + if (info.isSymbolicLink() || !info.isDirectory() || (info.mode & 0o077) !== 0 + || (uid !== undefined && info.uid !== uid)) { + throw new Error('LOCAL_STORE_UNSAFE_DIRECTORY'); + } + // Persist both directory metadata and its name in the parent before any + // store operation can acknowledge a durable marker or write. + syncDirectory(path, filesystem); + if (parentPath) syncDirectory(parentPath, filesystem); +} + +function openNoFollow(path, flags, mode = PRIVATE_FILE_MODE) { + return openSync(path, flags | NOFOLLOW, mode); +} + +function readFileBounded(path, maximumBytes) { + let fd; + try { fd = openNoFollow(path, constants.O_RDONLY); } catch (error) { + if (error.code === 'ENOENT') return undefined; + throw error; + } + try { + const info = fstatSync(fd); + const uid = typeof process.getuid === 'function' ? process.getuid() : undefined; + if (!info.isFile() || (info.mode & 0o077) !== 0 || info.size > maximumBytes + || (uid !== undefined && info.uid !== uid)) { + throw new Error('LOCAL_STORE_FILE_INVALID'); + } + return readFileSync(fd); + } finally { + closeSync(fd); + } +} + +function writeAll(fd, bytes) { + let offset = 0; + while (offset < bytes.byteLength) { + const written = writeSync(fd, bytes, offset, bytes.byteLength - offset); + if (!Number.isSafeInteger(written) || written <= 0) throw new Error('LOCAL_STORE_WRITE_INCOMPLETE'); + offset += written; + } +} + +function syncDirectory(path, filesystem = NATIVE_BOOTSTRAP_FILESYSTEM) { + const fd = filesystem.openSync(path, constants.O_RDONLY); + try { filesystem.fsyncSync(fd); } finally { filesystem.closeSync(fd); } +} + +function writeNewFile(path, bytes, directory) { + let fd; + try { + fd = openNoFollow(path, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL); + writeAll(fd, bytes); + fsyncSync(fd); + closeSync(fd); + fd = undefined; + syncDirectory(directory); + return true; + } catch (error) { + if (fd !== undefined) { + try { closeSync(fd); } catch { /* preserve the original failure */ } + } + throw error; + } +} + +function writeAtomicRecord(path, record, directory) { + const temporary = `${path}.${randomUUID()}.tmp`; + writeNewFile(temporary, Buffer.from(canonicalJson(record), 'utf8'), directory); + try { + renameSync(temporary, path); + syncDirectory(directory); + const actual = readJsonRecord(path); + if (actual === UNKNOWN_STORE_STATE || !actual || canonicalJson(actual) !== canonicalJson(record)) { + throw new Error('LOCAL_STORE_READBACK_MISMATCH'); + } + } catch (error) { + try { unlinkSync(temporary); } catch { /* keep an ambiguous temporary for reconciliation */ } + throw error; + } +} + +function readJsonRecord(path) { + let bytes; + try { bytes = readFileBounded(path, 16 * 1024); } catch { return UNKNOWN_STORE_STATE; } + if (bytes === undefined) return undefined; + try { + const text = bytes.toString('utf8'); + if (!Buffer.from(text, 'utf8').equals(bytes)) return UNKNOWN_STORE_STATE; + const value = JSON.parse(text); + if (canonicalJson(value) !== text) return UNKNOWN_STORE_STATE; + return value; + } catch { + return UNKNOWN_STORE_STATE; + } +} + +/** + * Local-only persistent store for the experimental offline prototype. + * The caller must own a private local directory; same-account hostile edits are + * outside the trust model. This store is not a production database. + */ +export class LocalFilePrototypeStore { + #root; + #eventsDirectory; + #blobsDirectory; + #claimsDirectory; + #uncertainEvents = new Set(); + #uncertainBlobs = new Set(); + + constructor(rootDirectory, { bootstrapFilesystem = NATIVE_BOOTSTRAP_FILESYSTEM } = {}) { + if (!NOFOLLOW) throw new Error('LOCAL_STORE_NOFOLLOW_UNSUPPORTED'); + if (typeof rootDirectory !== 'string' || !isAbsolute(rootDirectory)) { + throw new TypeError('An absolute local store directory is required.'); + } + if (!bootstrapFilesystem || typeof bootstrapFilesystem.mkdirSync !== 'function' + || typeof bootstrapFilesystem.lstatSync !== 'function' || typeof bootstrapFilesystem.openSync !== 'function' + || typeof bootstrapFilesystem.fsyncSync !== 'function' || typeof bootstrapFilesystem.closeSync !== 'function') { + throw new TypeError('Invalid local store bootstrap filesystem.'); + } + this.#root = resolve(rootDirectory); + ensurePrivateDirectory(this.#root, dirname(this.#root), bootstrapFilesystem); + this.#eventsDirectory = join(this.#root, 'events'); + this.#blobsDirectory = join(this.#root, 'blobs'); + this.#claimsDirectory = join(this.#root, 'resume-claims'); + ensurePrivateDirectory(this.#eventsDirectory, this.#root, bootstrapFilesystem); + ensurePrivateDirectory(this.#blobsDirectory, this.#root, bootstrapFilesystem); + ensurePrivateDirectory(this.#claimsDirectory, this.#root, bootstrapFilesystem); + } + + #eventPath(jobId) { + safeId(jobId, 'job id'); + return join(this.#eventsDirectory, `${encoded(jobId)}.jsonl`); + } + + #eventPendingPath(jobId) { return `${this.#eventPath(jobId)}.pending`; } + + #blobPath(key) { + safeId(key, 'blob key'); + return join(this.#blobsDirectory, `${encoded(key)}.blob`); + } + + #blobPendingPath(key) { return `${this.#blobPath(key)}.pending`; } + + #claimPath(jobId) { + safeId(jobId, 'job id'); + return join(this.#claimsDirectory, `${encoded(jobId)}.json`); + } + + reserveJobSlot() { + const path = join(this.#root, 'job-slot.json'); + const token = randomUUID(); + try { + writeNewFile(path, Buffer.from(canonicalJson({ status: 'reserved', token }), 'utf8'), this.#root); + const actual = readJsonRecord(path); + if (actual === UNKNOWN_STORE_STATE || !actual || canonicalJson(actual) !== canonicalJson({ status: 'reserved', token })) { + return { status: 'unknown' }; + } + return Object.freeze({ status: 'acquired', token }); + } catch (error) { + if (error.code !== 'EEXIST') return { status: 'unknown' }; + const record = readJsonRecord(path); + if (record === UNKNOWN_STORE_STATE || !record + || Object.keys(record).sort().join('|') !== 'status|token' + || !['reserved', 'consumed'].includes(record.status) || !validUuid(record.token)) return { status: 'unknown' }; + return record.status === 'consumed' ? 'consumed' : 'reserved'; + } + } + + commitJobSlot(token) { + const path = join(this.#root, 'job-slot.json'); + const record = readJsonRecord(path); + if (!record || record === UNKNOWN_STORE_STATE || typeof token !== 'string' + || Object.keys(record).sort().join('|') !== 'status|token' || !validUuid(record.token)) return false; + if (record.status === 'consumed') return record.token === token; + if (record.status !== 'reserved' || record.token !== token) return false; + try { + writeAtomicRecord(path, { status: 'consumed', token }, this.#root); + return true; + } catch { + return false; + } + } + + releaseUnusedJobSlot(token) { + const path = join(this.#root, 'job-slot.json'); + const record = readJsonRecord(path); + if (!record || record === UNKNOWN_STORE_STATE || Object.keys(record).sort().join('|') !== 'status|token' + || !validUuid(record.token) || record.status !== 'reserved' || record.token !== token) return false; + try { + unlinkSync(path); + syncDirectory(this.#root); + return readJsonRecord(path) === undefined; + } catch { + return false; + } + } + + append(event) { + const frozen = cloneFrozen(event); + const jobId = safeId(frozen.job_id, 'job id'); + const pendingPath = this.#eventPendingPath(jobId); + try { + writeNewFile(pendingPath, Buffer.from(canonicalJson({ job_id: jobId, operation: 'append' }), 'utf8'), this.#eventsDirectory); + } catch { throw new Error('LOCAL_STORE_STATE_UNKNOWN'); } + const events = this.#readEvents(jobId); + if (events === UNKNOWN_STORE_STATE) throw new Error('LOCAL_STORE_STATE_UNKNOWN'); + const bytes = Buffer.from(canonicalJson(frozen), 'utf8'); + const priorBytes = events.reduce((sum, item) => sum + Buffer.byteLength(canonicalJson(item), 'utf8'), 0); + if (events.length >= OFFLINE_ORCHESTRATION_LIMITS.maxLifecycleEntriesPerJob + || bytes.byteLength > OFFLINE_ORCHESTRATION_LIMITS.maxLifecycleMetadataBytesPerEntry + || priorBytes + bytes.byteLength > OFFLINE_ORCHESTRATION_LIMITS.maxLifecycleMetadataBytesPerJob) { + try { unlinkSync(pendingPath); syncDirectory(this.#eventsDirectory); } catch { /* fail closed if cleanup is uncertain */ } + throw new Error('LIFECYCLE_METADATA_LIMIT'); + } + const path = this.#eventPath(jobId); + let fd; + try { + const prior = readFileBounded(path, + OFFLINE_ORCHESTRATION_LIMITS.maxLifecycleMetadataBytesPerJob + + OFFLINE_ORCHESTRATION_LIMITS.maxLifecycleEntriesPerJob) ?? Buffer.alloc(0); + const appended = Buffer.concat([prior, bytes, Buffer.from('\n')]); + fd = openNoFollow(path, constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT); + writeAll(fd, Buffer.concat([bytes, Buffer.from('\n')])); + fsyncSync(fd); + closeSync(fd); + fd = undefined; + syncDirectory(this.#eventsDirectory); + const actual = readFileBounded(path, + OFFLINE_ORCHESTRATION_LIMITS.maxLifecycleMetadataBytesPerJob + + OFFLINE_ORCHESTRATION_LIMITS.maxLifecycleEntriesPerJob); + if (!actual?.equals(appended)) throw new Error('LOCAL_STORE_READBACK_MISMATCH'); + unlinkSync(pendingPath); + syncDirectory(this.#eventsDirectory); + this.#uncertainEvents.delete(jobId); + return true; + } catch (error) { + if (fd !== undefined) { + try { closeSync(fd); } catch { /* preserve the original failure */ } + } + this.#uncertainEvents.add(jobId); + throw error; + } + } + + readEvents(jobId) { + try { + safeId(jobId, 'job id'); + if (readFileBounded(this.#eventPendingPath(jobId), 16 * 1024) !== undefined) return UNKNOWN_STORE_STATE; + } catch { return UNKNOWN_STORE_STATE; } + return this.#readEvents(jobId); + } + + #readEvents(jobId) { + try { + safeId(jobId, 'job id'); + if (this.#uncertainEvents.has(jobId)) return UNKNOWN_STORE_STATE; + const bytes = readFileBounded(this.#eventPath(jobId), + OFFLINE_ORCHESTRATION_LIMITS.maxLifecycleMetadataBytesPerJob + + OFFLINE_ORCHESTRATION_LIMITS.maxLifecycleEntriesPerJob); + if (bytes === undefined) return []; + if (bytes.byteLength === 0 || bytes.at(-1) !== 0x0a) return UNKNOWN_STORE_STATE; + const text = bytes.toString('utf8'); + if (!Buffer.from(text, 'utf8').equals(bytes)) return UNKNOWN_STORE_STATE; + const lines = text.slice(0, -1).split('\n'); + if (lines.length > OFFLINE_ORCHESTRATION_LIMITS.maxLifecycleEntriesPerJob) return UNKNOWN_STORE_STATE; + const events = []; + let total = 0; + for (const line of lines) { + const value = JSON.parse(line); + if (canonicalJson(value) !== line || value.job_id !== jobId) return UNKNOWN_STORE_STATE; + const size = Buffer.byteLength(line, 'utf8'); + if (size > OFFLINE_ORCHESTRATION_LIMITS.maxLifecycleMetadataBytesPerEntry + || total + size > OFFLINE_ORCHESTRATION_LIMITS.maxLifecycleMetadataBytesPerJob) return UNKNOWN_STORE_STATE; + total += size; + events.push(cloneFrozen(value)); + } + return events; + } catch { + return UNKNOWN_STORE_STATE; + } + } + + readJobIds() { + try { + const ids = new Set(); + for (const name of readdirSync(this.#eventsDirectory)) { + if (!name.endsWith('.jsonl')) return UNKNOWN_STORE_STATE; + const jobId = decoded(name.slice(0, -6)); + if (!jobId || this.readEvents(jobId) === UNKNOWN_STORE_STATE) return UNKNOWN_STORE_STATE; + ids.add(jobId); + } + for (const name of readdirSync(this.#blobsDirectory)) { + if (!name.endsWith('.blob')) return UNKNOWN_STORE_STATE; + const key = decoded(name.slice(0, -5)); + if (!key) return UNKNOWN_STORE_STATE; + if (key.startsWith('input:') || key.startsWith('prompt:')) ids.add(key.slice(key.indexOf(':') + 1)); + } + return [...ids]; + } catch { + return UNKNOWN_STORE_STATE; + } + } + + writeImmutable(key, bytes) { + safeId(key, 'blob key'); + if (!(bytes instanceof Uint8Array)) throw new TypeError('Invalid local store blob bytes.'); + const existing = this.readImmutable(key); + if (existing === UNKNOWN_STORE_STATE) throw new Error('LOCAL_STORE_STATE_UNKNOWN'); + if (Buffer.isBuffer(existing)) throw new Error('IMMUTABLE_BLOB_ALREADY_EXISTS'); + const path = this.#blobPath(key); + const pendingPath = this.#blobPendingPath(key); + try { + writeNewFile(pendingPath, Buffer.from(canonicalJson({ key, operation: 'write-immutable' }), 'utf8'), this.#blobsDirectory); + } catch { throw new Error('LOCAL_STORE_STATE_UNKNOWN'); } + try { + writeNewFile(path, Buffer.from(bytes), this.#blobsDirectory); + const actual = readFileBounded(path, OFFLINE_ORCHESTRATION_LIMITS.maxAggregateMaterialBytesPerJob); + if (!actual?.equals(Buffer.from(bytes))) throw new Error('LOCAL_STORE_READBACK_MISMATCH'); + unlinkSync(pendingPath); + syncDirectory(this.#blobsDirectory); + this.#uncertainBlobs.delete(key); + return true; + } catch (error) { + if (error.code !== 'EEXIST') this.#uncertainBlobs.add(key); + throw error; + } + } + + readImmutable(key) { + try { + safeId(key, 'blob key'); + if (this.#uncertainBlobs.has(key)) return UNKNOWN_STORE_STATE; + if (readFileBounded(this.#blobPendingPath(key), 16 * 1024) !== undefined) return UNKNOWN_STORE_STATE; + const bytes = readFileBounded(this.#blobPath(key), OFFLINE_ORCHESTRATION_LIMITS.maxAggregateMaterialBytesPerJob); + return bytes === undefined ? Object.freeze({ state: 'absent' }) : Buffer.from(bytes); + } catch { + return UNKNOWN_STORE_STATE; + } + } + + claimResume(jobId) { + const path = this.#claimPath(jobId); + const claimId = randomUUID(); + const record = { job_id: jobId, claim_id: claimId, state: 'held' }; + try { + writeNewFile(path, Buffer.from(canonicalJson(record), 'utf8'), this.#claimsDirectory); + const actual = readJsonRecord(path); + if (actual === UNKNOWN_STORE_STATE || !actual || canonicalJson(actual) !== canonicalJson(record)) { + return Object.freeze({ status: 'unknown' }); + } + return Object.freeze({ status: 'acquired', claim_id: claimId }); + } catch (error) { + if (error.code !== 'EEXIST') return Object.freeze({ status: 'unknown' }); + const existing = readJsonRecord(path); + if (existing === UNKNOWN_STORE_STATE || !existing + || Object.keys(existing).sort().join('|') !== 'claim_id|job_id|state' + || existing.job_id !== jobId || !validUuid(existing.claim_id) || existing.state !== 'held') { + return Object.freeze({ status: 'unknown' }); + } + return Object.freeze({ status: 'held' }); + } + } + + get eventCount() { + const ids = this.readJobIds(); + if (ids === UNKNOWN_STORE_STATE) return UNKNOWN_STORE_STATE; + return ids.reduce((sum, jobId) => { + const events = this.readEvents(jobId); + return events === UNKNOWN_STORE_STATE ? UNKNOWN_STORE_STATE : sum + events.length; + }, 0); + } + + get blobCount() { + try { return readdirSync(this.#blobsDirectory).length; } catch { return UNKNOWN_STORE_STATE; } + } + + eventsFor(jobId) { + return this.readEvents(jobId); + } +} + +export const LOCAL_FILE_STORE_TRUST_BOUNDARY = Object.freeze({ + scope: 'synthetic-local-only', + directory_mode: PRIVATE_DIRECTORY_MODE, + file_mode: PRIVATE_FILE_MODE, + same_account_hostile_edits: 'not-protected', + digest_authenticity: 'not-provided', + automatic_claim_takeover: false +}); diff --git a/src/offline-orchestration-prototype/testing.js b/src/offline-orchestration-prototype/testing.js index e46c555..c8919bb 100644 --- a/src/offline-orchestration-prototype/testing.js +++ b/src/offline-orchestration-prototype/testing.js @@ -1,4 +1,5 @@ // Internal-only test seam. This file is intentionally absent from package exports. export { createOfflineOrchestrationPrototypeForTest } from './runner.js'; export { InMemoryPrototypeStore } from './memory-store.js'; +export { LocalFilePrototypeStore, LOCAL_FILE_STORE_TRUST_BOUNDARY } from './local-file-store.js'; export { MaterialLedger, assertAtMost, checkedAdd } from './limits.js'; diff --git a/tests/offline-orchestration-prototype/local-file-store.test.js b/tests/offline-orchestration-prototype/local-file-store.test.js new file mode 100644 index 0000000..feb9c90 --- /dev/null +++ b/tests/offline-orchestration-prototype/local-file-store.test.js @@ -0,0 +1,240 @@ +import assert from 'node:assert/strict'; +import { + appendFileSync, closeSync, fsyncSync, lstatSync, mkdirSync, mkdtempSync, + openSync, rmSync, statSync, symlinkSync, writeFileSync +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import test from 'node:test'; +import { readFile } from 'node:fs/promises'; +import { randomUUID } from 'node:crypto'; +import { MockTextAdapter } from '../../src/prompt-sdk/index.js'; +import { + createSyntheticExecutionAuthorityVerifier, + SYNTHETIC_EXECUTION_PURPOSE +} from '../../src/offline-orchestration-prototype/execution-authority.js'; +import { + createOfflineOrchestrationPrototypeForTest, + LocalFilePrototypeStore, + LOCAL_FILE_STORE_TRUST_BOUNDARY +} from '../../src/offline-orchestration-prototype/testing.js'; + +const fixture = JSON.parse(await readFile(new URL('../fixtures/comic-manifest-v1.json', import.meta.url), 'utf8')); +const productionSource = JSON.stringify(fixture.production); + +function temporaryDirectory() { + return mkdtempSync(join(tmpdir(), 'dss-o08-local-store-')); +} + +function recordingBootstrapFilesystem({ failPath } = {}) { + const calls = []; + const paths = new Map(); + return { + calls, + filesystem: { + mkdirSync(path, options) { calls.push(['mkdir', path]); return mkdirSync(path, options); }, + lstatSync, + openSync(path, flags) { + const fd = openSync(path, flags); + paths.set(fd, path); + calls.push(['open', path]); + return fd; + }, + fsyncSync(fd) { + const path = paths.get(fd); + calls.push(['fsync', path]); + if (path === failPath) throw new Error('INJECTED_BOOTSTRAP_FSYNC_FAILURE'); + return fsyncSync(fd); + }, + closeSync(fd) { + calls.push(['close', paths.get(fd)]); + paths.delete(fd); + return closeSync(fd); + } + } + }; +} + +function authority() { + const production = { + production_id: 'urn:uuid:10000000-0000-4000-8000-000000000001', + revision: 1, + identity_sha256: 'sha256:9250217ad23125b0356a9e7002f57a55dacf9d982f069caa403b89f8c6c234dc' + }; + const record = (action, suffix) => ({ + decision_id: `20000000-0000-4000-8000-${suffix.padStart(12, '0')}`, + decision: 'allow', + action, + purpose: SYNTHETIC_EXECUTION_PURPOSE, + production, + not_before: '2026-01-01T00:00:00Z', + review_after: '2027-01-01T00:00:00Z', + expires_at: '2027-02-01T00:00:00Z', + authority_reference: 'https://github.com/DefinitelySecureStudio/platform/issues/106' + }); + return createSyntheticExecutionAuthorityVerifier([record('execute', '1'), record('retry', '2')]).verifier; +} + +function runtime() { + return { + now: () => 10_000, + epochId: 'local-file-store-test-epoch', + wallNow: () => Date.parse('2026-10-28T17:00:00Z'), + setTimer: (callback, delay) => setTimeout(callback, delay), + clearTimer: timer => clearTimeout(timer) + }; +} + +function prototype(store, onMockCall = () => {}) { + return createOfflineOrchestrationPrototypeForTest({ + store, + runtime: runtime(), + idFactory: randomUUID, + executionAuthorityProvider: authority(), + onMockCall + }); +} + +test('local file store round-trips canonical events and immutable blobs after reopening', t => { + const root = temporaryDirectory(); + t.after(() => rmSync(root, { recursive: true, force: true })); + const jobId = '10000000-0000-4000-8000-000000000001'; + const blobKey = `input:${jobId}`; + const bytes = Buffer.from('synthetic persisted bytes'); + const store = new LocalFilePrototypeStore(root); + assert.equal(store.append({ job_id: jobId, type: 'admitted', sequence: 0 }), true); + assert.equal(store.writeImmutable(blobKey, bytes), true); + assert.throws(() => store.writeImmutable(blobKey, Buffer.from('replacement'))); + + const reopened = new LocalFilePrototypeStore(root); + assert.deepEqual(reopened.readEvents(jobId), [{ job_id: jobId, type: 'admitted', sequence: 0 }]); + assert.deepEqual(reopened.readImmutable(blobKey), bytes); + assert.deepEqual(reopened.readJobIds(), [jobId]); + assert.equal(reopened.eventCount, 1); + assert.equal(reopened.blobCount, 1); + assert.equal(LOCAL_FILE_STORE_TRUST_BOUNDARY.same_account_hostile_edits, 'not-protected'); + assert.equal(LOCAL_FILE_STORE_TRUST_BOUNDARY.automatic_claim_takeover, false); + assert.equal(statSync(root).mode & 0o777, 0o700); + assert.equal(statSync(join(root, 'events', `${Buffer.from(jobId).toString('base64url')}.jsonl`)).mode & 0o777, 0o600); +}); + +test('local file store preserves one-shot claims across instances and never takes them over', t => { + const root = temporaryDirectory(); + t.after(() => rmSync(root, { recursive: true, force: true })); + const jobId = '10000000-0000-4000-8000-000000000002'; + const first = new LocalFilePrototypeStore(root); + const acquired = first.claimResume(jobId); + assert.equal(acquired.status, 'acquired'); + assert.equal(typeof acquired.claim_id, 'string'); + + const reopened = new LocalFilePrototypeStore(root); + assert.deepEqual(reopened.claimResume(jobId), { status: 'held' }); + assert.equal(reopened.readEvents(jobId).length, 0); +}); + +test('bootstrap fsyncs each directory and its parent before continuing initialization', t => { + const parent = temporaryDirectory(); + t.after(() => rmSync(parent, { recursive: true, force: true })); + const root = join(parent, 'store'); + const { calls, filesystem } = recordingBootstrapFilesystem(); + new LocalFilePrototypeStore(root, { bootstrapFilesystem: filesystem }); + + const expected = []; + const durableDirectory = (path, parentPath) => { + expected.push(['mkdir', path]); + for (const syncedPath of [path, parentPath]) { + expected.push(['open', syncedPath], ['fsync', syncedPath], ['close', syncedPath]); + } + }; + durableDirectory(root, parent); + durableDirectory(join(root, 'events'), root); + durableDirectory(join(root, 'blobs'), root); + durableDirectory(join(root, 'resume-claims'), root); + assert.deepEqual(calls, expected); +}); + +test('bootstrap fsync failures stop initialization before child directories or store use', async t => { + const parent = temporaryDirectory(); + t.after(() => rmSync(parent, { recursive: true, force: true })); + const root = join(parent, 'store'); + for (const failPath of [root, parent]) await t.test(`failure syncing ${failPath === root ? 'root' : 'parent'}`, () => { + const { calls, filesystem } = recordingBootstrapFilesystem({ failPath }); + assert.throws(() => new LocalFilePrototypeStore(root, { bootstrapFilesystem: filesystem }), + /INJECTED_BOOTSTRAP_FSYNC_FAILURE/); + assert.ok(calls.some(([operation, path]) => operation === 'fsync' && path === failPath)); + assert.equal(calls.some(([operation, path]) => operation === 'mkdir' && path === join(root, 'events')), false); + }); + assert.equal(new LocalFilePrototypeStore(root).readJobIds().length, 0); +}); + +test('local file store returns unknown for a truncated event log and rejects a symlinked root', t => { + const parent = temporaryDirectory(); + t.after(() => rmSync(parent, { recursive: true, force: true })); + const root = join(parent, 'store'); + const store = new LocalFilePrototypeStore(root); + const jobId = '10000000-0000-4000-8000-000000000003'; + store.append({ job_id: jobId, type: 'admitted', sequence: 0 }); + const path = join(root, 'events', `${Buffer.from(jobId).toString('base64url')}.jsonl`); + appendFileSync(path, '{"partial":'); + assert.deepEqual(store.readEvents(jobId), { state: 'unknown' }); + + const alias = join(parent, 'alias'); + symlinkSync(root, alias, 'dir'); + assert.throws(() => new LocalFilePrototypeStore(alias), /LOCAL_STORE_UNSAFE_DIRECTORY/); +}); + +test('local file store quarantines persisted pending event and blob writes after restart', t => { + const root = temporaryDirectory(); + t.after(() => rmSync(root, { recursive: true, force: true })); + const jobId = '10000000-0000-4000-8000-000000000004'; + const blobKey = `input:${jobId}`; + const store = new LocalFilePrototypeStore(root); + store.append({ job_id: jobId, type: 'admitted', sequence: 0 }); + store.writeImmutable(blobKey, Buffer.from('synthetic protected bytes')); + writeFileSync(join(root, 'events', `${Buffer.from(jobId).toString('base64url')}.jsonl.pending`), 'ambiguous'); + writeFileSync(join(root, 'blobs', `${Buffer.from(blobKey).toString('base64url')}.blob.pending`), 'ambiguous'); + + const reopened = new LocalFilePrototypeStore(root); + assert.deepEqual(reopened.readEvents(jobId), { state: 'unknown' }); + assert.deepEqual(reopened.readImmutable(blobKey), { state: 'unknown' }); + assert.deepEqual(reopened.readJobIds(), { state: 'unknown' }); +}); + +test('local file store treats non-canonical UTF-8 event bytes as unknown', t => { + const root = temporaryDirectory(); + t.after(() => rmSync(root, { recursive: true, force: true })); + const jobId = '10000000-0000-4000-8000-000000000005'; + const store = new LocalFilePrototypeStore(root); + const encodedId = Buffer.from(jobId).toString('base64url'); + writeFileSync(join(root, 'events', `${encodedId}.jsonl`), Buffer.from([0xff, 0x0a])); + assert.deepEqual(store.readEvents(jobId), { state: 'unknown' }); +}); + +test('runner can inspect a committed synthetic result from a reopened local store without writes or calls', async t => { + const root = temporaryDirectory(); + t.after(() => rmSync(root, { recursive: true, force: true })); + const store = new LocalFilePrototypeStore(root); + let calls = 0; + const first = prototype(store, ({ phase }) => { + if (phase === 'dispatch-confirmed') calls++; + }); + const completed = await first.submit({ productionSource }); + assert.equal(completed.kind, 'terminal'); + assert.equal(completed.result.status, 'complete'); + assert.equal(calls, 1); + + let restartedCalls = 0; + const reopened = new LocalFilePrototypeStore(root); + const restarted = prototype(reopened, () => { restartedCalls++; }); + const beforeEvents = reopened.eventCount; + const beforeBlobs = reopened.blobCount; + const inspection = restarted.inspectRecovery(completed.job_id); + assert.equal(inspection.status, 'terminal'); + assert.equal(inspection.read_only, true); + assert.equal(inspection.writes_performed, 0); + assert.equal(inspection.provider_calls_performed, 0); + assert.equal(reopened.eventCount, beforeEvents); + assert.equal(reopened.blobCount, beforeBlobs); + assert.equal(restartedCalls, 0); + await assert.rejects(() => restarted.submit({ productionSource }), error => error.code === 'JOB_STORE_LIFETIME_LIMIT'); +});