@earendil-works/pi-durable 0.99.1 → 0.99.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +435 -46
- package/dist/entries.d.ts +20 -2
- package/dist/entries.d.ts.map +1 -1
- package/dist/entries.js +14 -1
- package/dist/entries.js.map +1 -1
- package/dist/env/index.d.ts +13 -38
- package/dist/env/index.d.ts.map +1 -1
- package/dist/env/index.js +2 -0
- package/dist/env/index.js.map +1 -1
- package/dist/env/node.d.ts.map +1 -1
- package/dist/env/node.js +51 -58
- package/dist/env/node.js.map +1 -1
- package/dist/harness/compaction.d.ts +56 -0
- package/dist/harness/compaction.d.ts.map +1 -0
- package/dist/harness/compaction.js +385 -0
- package/dist/harness/compaction.js.map +1 -0
- package/dist/harness/config.d.ts +10 -1
- package/dist/harness/config.d.ts.map +1 -1
- package/dist/harness/config.js +6 -0
- package/dist/harness/config.js.map +1 -1
- package/dist/harness/context.d.ts +8 -0
- package/dist/harness/context.d.ts.map +1 -1
- package/dist/harness/context.js +32 -21
- package/dist/harness/context.js.map +1 -1
- package/dist/harness/events.d.ts +166 -0
- package/dist/harness/events.d.ts.map +1 -0
- package/dist/harness/events.js +319 -0
- package/dist/harness/events.js.map +1 -0
- package/dist/harness/generation.d.ts +37 -6
- package/dist/harness/generation.d.ts.map +1 -1
- package/dist/harness/generation.js +350 -72
- package/dist/harness/generation.js.map +1 -1
- package/dist/harness/harness.d.ts.map +1 -1
- package/dist/harness/harness.js +124 -3
- package/dist/harness/harness.js.map +1 -1
- package/dist/harness/inbox.d.ts +57 -0
- package/dist/harness/inbox.d.ts.map +1 -0
- package/dist/harness/inbox.js +99 -0
- package/dist/harness/inbox.js.map +1 -0
- package/dist/harness/json.d.ts +10 -0
- package/dist/harness/json.d.ts.map +1 -0
- package/dist/harness/json.js +33 -0
- package/dist/harness/json.js.map +1 -0
- package/dist/harness/live.d.ts +66 -7
- package/dist/harness/live.d.ts.map +1 -1
- package/dist/harness/live.js +71 -7
- package/dist/harness/live.js.map +1 -1
- package/dist/harness/output.d.ts +62 -0
- package/dist/harness/output.d.ts.map +1 -0
- package/dist/harness/output.js +261 -0
- package/dist/harness/output.js.map +1 -0
- package/dist/harness/prompt.d.ts +10 -5
- package/dist/harness/prompt.d.ts.map +1 -1
- package/dist/harness/prompt.js +66 -13
- package/dist/harness/prompt.js.map +1 -1
- package/dist/harness/registry.d.ts.map +1 -1
- package/dist/harness/registry.js +11 -2
- package/dist/harness/registry.js.map +1 -1
- package/dist/harness/scheduler.d.ts +37 -12
- package/dist/harness/scheduler.d.ts.map +1 -1
- package/dist/harness/scheduler.js +632 -72
- package/dist/harness/scheduler.js.map +1 -1
- package/dist/harness/submissions.d.ts +12 -7
- package/dist/harness/submissions.d.ts.map +1 -1
- package/dist/harness/submissions.js +72 -33
- package/dist/harness/submissions.js.map +1 -1
- package/dist/harness/tool.d.ts +36 -0
- package/dist/harness/tool.d.ts.map +1 -0
- package/dist/harness/tool.js +412 -0
- package/dist/harness/tool.js.map +1 -0
- package/dist/harness/types.d.ts +185 -11
- package/dist/harness/types.d.ts.map +1 -1
- package/dist/harness/types.js.map +1 -1
- package/dist/harness/usage.d.ts +18 -0
- package/dist/harness/usage.d.ts.map +1 -0
- package/dist/harness/usage.js +57 -0
- package/dist/harness/usage.js.map +1 -0
- package/dist/harness/view.d.ts +43 -0
- package/dist/harness/view.d.ts.map +1 -0
- package/dist/harness/view.js +194 -0
- package/dist/harness/view.js.map +1 -0
- package/dist/index.d.ts +10 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -1
- package/dist/index.js.map +1 -1
- package/dist/session/observation.d.ts +18 -11
- package/dist/session/observation.d.ts.map +1 -1
- package/dist/session/observation.js +24 -13
- package/dist/session/observation.js.map +1 -1
- package/dist/session/session.d.ts +10 -1
- package/dist/session/session.d.ts.map +1 -1
- package/dist/session/session.js +18 -4
- package/dist/session/session.js.map +1 -1
- package/dist/session/transaction.d.ts +10 -1
- package/dist/session/transaction.d.ts.map +1 -1
- package/dist/session/transaction.js +83 -27
- package/dist/session/transaction.js.map +1 -1
- package/dist/storage/jsonl/storage.d.ts +22 -2
- package/dist/storage/jsonl/storage.d.ts.map +1 -1
- package/dist/storage/jsonl/storage.js +1 -1
- package/dist/storage/jsonl/storage.js.map +1 -1
- package/dist/storage/memory.js +1 -1
- package/dist/storage/memory.js.map +1 -1
- package/dist/storage/sqlite/migrations.js +1 -1
- package/dist/storage/sqlite/migrations.js.map +1 -1
- package/dist/testing/storage-benchmark.d.ts.map +1 -1
- package/dist/testing/storage-benchmark.js +0 -1
- package/dist/testing/storage-benchmark.js.map +1 -1
- package/dist/testing/storage-conformance.d.ts.map +1 -1
- package/dist/testing/storage-conformance.js +34 -2
- package/dist/testing/storage-conformance.js.map +1 -1
- package/dist/tools/bash.d.ts +28 -0
- package/dist/tools/bash.d.ts.map +1 -0
- package/dist/tools/bash.js +69 -0
- package/dist/tools/bash.js.map +1 -0
- package/dist/tools/edit-diff.d.ts +89 -0
- package/dist/tools/edit-diff.d.ts.map +1 -0
- package/dist/tools/edit-diff.js +386 -0
- package/dist/tools/edit-diff.js.map +1 -0
- package/dist/tools/edit.d.ts +18 -0
- package/dist/tools/edit.d.ts.map +1 -0
- package/dist/tools/edit.js +116 -0
- package/dist/tools/edit.js.map +1 -0
- package/dist/tools/env.d.ts +5 -0
- package/dist/tools/env.d.ts.map +1 -0
- package/dist/tools/env.js +7 -0
- package/dist/tools/env.js.map +1 -0
- package/dist/tools/file-mutation-queue.d.ts +5 -0
- package/dist/tools/file-mutation-queue.d.ts.map +1 -0
- package/dist/tools/file-mutation-queue.js +46 -0
- package/dist/tools/file-mutation-queue.js.map +1 -0
- package/dist/tools/image.d.ts +2 -0
- package/dist/tools/image.d.ts.map +1 -0
- package/dist/tools/image.js +92 -0
- package/dist/tools/image.js.map +1 -0
- package/dist/tools/index.d.ts +5 -0
- package/dist/tools/index.d.ts.map +1 -0
- package/dist/tools/index.js +5 -0
- package/dist/tools/index.js.map +1 -0
- package/dist/tools/path-utils.d.ts +5 -0
- package/dist/tools/path-utils.d.ts.map +1 -0
- package/dist/tools/path-utils.js +26 -0
- package/dist/tools/path-utils.js.map +1 -0
- package/dist/tools/read.d.ts +17 -0
- package/dist/tools/read.d.ts.map +1 -0
- package/dist/tools/read.js +100 -0
- package/dist/tools/read.js.map +1 -0
- package/dist/tools/write.d.ts +10 -0
- package/dist/tools/write.d.ts.map +1 -0
- package/dist/tools/write.js +30 -0
- package/dist/tools/write.js.map +1 -0
- package/dist/{env/utils/truncate.d.ts → truncate.d.ts} +1 -17
- package/dist/truncate.d.ts.map +1 -0
- package/dist/truncate.js +146 -0
- package/dist/truncate.js.map +1 -0
- package/dist/types.d.ts +86 -19
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/docs/pico-v5-handoff.md +366 -86
- package/docs/pico-v5.md +1373 -283
- package/package.json +11 -3
- package/dist/env/utils/adaptive-publisher.d.ts +0 -24
- package/dist/env/utils/adaptive-publisher.d.ts.map +0 -1
- package/dist/env/utils/adaptive-publisher.js +0 -79
- package/dist/env/utils/adaptive-publisher.js.map +0 -1
- package/dist/env/utils/output-capture.d.ts +0 -31
- package/dist/env/utils/output-capture.d.ts.map +0 -1
- package/dist/env/utils/output-capture.js +0 -238
- package/dist/env/utils/output-capture.js.map +0 -1
- package/dist/env/utils/truncate.d.ts.map +0 -1
- package/dist/env/utils/truncate.js +0 -294
- package/dist/env/utils/truncate.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scheduler.js","sourceRoot":"","sources":["../../src/harness/scheduler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,QAAQ,EAAkB,MAAM,uBAAuB,CAAC;AAC/E,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAkBlF,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAS3C,OAAO,EAAE,WAAW,EAAE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sourcesContent":["import { type Context, copyJson, type JsonValue } from \"@earendil-works/chord\";\nimport { awaitWithContext, withAbortSignal } from \"@earendil-works/chord/context\";\nimport type { Models } from \"@earendil-works/pi-ai\";\nimport type { SessionImpl } from \"../session/session.ts\";\nimport type { Transaction } from \"../session/transaction.ts\";\nimport type {\n\tCommitPublication,\n\tConversationId,\n\tDocumentWatch,\n\tJsonObject,\n\tRunningTask,\n\tStorage,\n\tTaskDefinition,\n\tTaskId,\n\tTaskOutcome,\n\tTaskRecord,\n\tTaskRuntime,\n\tTaskState,\n} from \"../types.ts\";\nimport { readContext } from \"./context.ts\";\nimport type {\n\tAnyTask,\n\tHarnessInspection,\n\tRegistryReader,\n\tRegistrySnapshot,\n\tSettledTask,\n\tTaskInspection,\n} from \"./types.ts\";\nimport { closedError, scanAll, Waiters } from \"./util.ts\";\n\ntype AnyTaskRecord = TaskRecord<JsonValue, JsonValue, JsonValue>;\ntype LiveTaskRecord = Extract<AnyTaskRecord, { readonly state: { readonly status: \"pending\" | \"running\" } }>;\ntype Checkpoint = { readonly phase: string };\ntype ErasedDefinition = TaskDefinition<JsonValue, Checkpoint, JsonValue, object>;\ntype ErasedRuntime = TaskRuntime<JsonValue, Checkpoint, JsonValue, object>;\ntype ErasedRunningTask = RunningTask<JsonValue, Checkpoint, JsonValue>;\n\nconst SCAN_PAGE_SIZE = 256;\n/** Longest delay `setTimeout` supports; longer sleeps wait in several steps. */\nconst MAX_TIMER_DELAY = 2_147_483_647;\n\n/** Why a pending task cannot be reserved under a registry snapshot. Derived, never persisted. */\ntype BlockedReason = \"missing_task\" | \"task_too_old\" | \"migration_failed\";\n\ntype Resolution =\n\t| { readonly kind: \"ready\"; readonly task: AnyTask; readonly record: LiveTaskRecord }\n\t| { readonly kind: \"blocked\"; readonly reason: BlockedReason };\n\n/** A definition that can take a record, or why none can; deciding it runs no task code. */\ntype Fit =\n\t| { readonly task: AnyTask; readonly migrates: boolean }\n\t| { readonly reason: BlockedReason; readonly error?: unknown };\n\n/** One in-memory execution of a task in run or abort mode. */\ntype Invocation = {\n\treadonly taskId: TaskId;\n\treadonly conversationId: ConversationId;\n\treadonly mode: \"run\" | \"abort\";\n\treadonly controller: AbortController;\n\t/** Context passed to handlers; cancelled by `controller`. */\n\treadonly context: Context;\n\t/** Watches acquired through the runtime; stopped at invocation end. */\n\treadonly watches: Set<DocumentWatch<JsonObject>>;\n\tended: boolean;\n\treadonly done: Promise<void>;\n\treadonly finish: () => void;\n};\n\ntype Reservation = {\n\treadonly invocation: Invocation;\n\treadonly task: AnyTask;\n\treadonly snapshot: RegistrySnapshot;\n};\n\n/** Replacement definition already reported as unable to take over, per invocation. */\ntype ReportedTask = { readonly task: AnyTask | undefined } | undefined;\n\n/** Outcome of the phase that just returned, judged by the next step. */\ntype PhaseResult = { readonly checkpoint: Checkpoint; readonly failure?: { readonly error: unknown } };\n\n/** Step decision: continue with the next phase, end the invocation, or end it by writing terminal `faulted`. */\ntype Decision = boolean | { readonly fault: unknown };\n\n/** Terminal outcomes the scheduler writes without running task code. */\nexport type SchedulerOutcome = Extract<TaskOutcome<JsonValue>, { readonly status: \"faulted\" | \"orphaned\" }>;\n\nexport type TaskSchedulerOptions = {\n\treadonly session: SessionImpl;\n\treadonly storage: Storage;\n\treadonly registry: RegistryReader;\n\treadonly models: Models;\n\treadonly now: () => number;\n\treadonly report: (error: unknown) => void;\n\t/** Harness cleanup staged in the same commit as every terminal outcome the scheduler writes itself. */\n\treadonly settleOutcome: (tx: Transaction, record: AnyTaskRecord, outcome: SchedulerOutcome) => Promise<void>;\n\t/** Context for scheduler commits and invocations; carries no caller cancellation. */\n\treadonly context: Context;\n};\n\n/**\n * Durable task scheduler of one Harness.\n *\n * `#live` mirrors every committed pending/running task record. The synchronous commit listener updates it on the\n * Session line, so code running on the line reads exactly the committed state from it.\n *\n * Invariant: every task transition is decided and written by one callback serialized on the Session line. That covers\n * reservation, marks, runtime commits, and the synchronous step before each phase, which applies the precedence rules\n * and writes a fault or handover. Handlers and joins run off the line. An invocation ends inside the step that decides its end,\n * so a runtime commit it queued either lands before that decision or is rejected.\n */\nexport class TaskScheduler {\n\treadonly #session: SessionImpl;\n\treadonly #storage: Storage;\n\treadonly #registry: RegistryReader;\n\treadonly #models: Models;\n\treadonly #now: () => number;\n\treadonly #report: (error: unknown) => void;\n\treadonly #settleOutcome: TaskSchedulerOptions[\"settleOutcome\"];\n\treadonly #context: Context;\n\treadonly #live = new Map<TaskId, LiveTaskRecord>();\n\treadonly #invocations = new Map<TaskId, Invocation>();\n\treadonly #taskWaiters = new Waiters<TaskId, SettledTask<JsonValue>>();\n\t/** Idle waiters by conversation; `undefined` waits for the whole Harness. */\n\treadonly #idleWaiters = new Waiters<ConversationId | undefined, void>();\n\t/** Definition whose migration failed per task; retried only once the registry resolves another definition. */\n\treadonly #failedMigrations = new Map<TaskId, { readonly task: AnyTask; readonly error: unknown }>();\n\t#unsubscribeRegistry: () => void = () => {};\n\t#enabled = false;\n\t#closing = false;\n\t#dirty = false;\n\t#draining = false;\n\n\tconstructor(options: TaskSchedulerOptions) {\n\t\tthis.#session = options.session;\n\t\tthis.#storage = options.storage;\n\t\tthis.#registry = options.registry;\n\t\tthis.#models = options.models;\n\t\tthis.#now = options.now;\n\t\tthis.#report = options.report;\n\t\tthis.#settleOutcome = options.settleOutcome;\n\t\tthis.#context = options.context;\n\t}\n\n\t/** Load live tasks and change surviving `running` tasks back to `pending`. Dispatches nothing. */\n\tasync open(context: Context): Promise<void> {\n\t\tthis.#session.subscribeCommits((publication) => this.#observe(publication));\n\t\tthis.#session.subscribeClose(() => this.#seal());\n\t\tthis.#unsubscribeRegistry = this.#registry.subscribe(() => this.#kick());\n\t\tawait this.#session.commitWith(async (tx) => {\n\t\t\tconst scan = (status: \"pending\" | \"running\") =>\n\t\t\t\tscanAll((cursor) => tx.scanTasks({ status }, SCAN_PAGE_SIZE, cursor)) as Promise<LiveTaskRecord[]>;\n\t\t\tconst pending = await scan(\"pending\");\n\t\t\tconst running = await scan(\"running\");\n\t\t\tfor (const record of [...pending, ...running]) this.#live.set(record.id, record);\n\t\t\tfor (const record of running) {\n\t\t\t\ttx.setTask(withState(record, { status: \"pending\", checkpoint: record.state.checkpoint }));\n\t\t\t}\n\t\t}, context);\n\t}\n\n\t/** Enable scheduling. Idempotent; the kick does nothing once closing. */\n\tresume(): void {\n\t\tthis.#enabled = true;\n\t\tthis.#kick();\n\t}\n\n\t/** Wait for every invocation signalled by `#seal()`. Writes nothing. */\n\tasync join(): Promise<void> {\n\t\tawait Promise.allSettled([...this.#invocations.values()].map((invocation) => invocation.done));\n\t}\n\n\t/**\n\t * Commit the abort mark, or settle a task that no registered definition can take as `orphaned`, then signal and\n\t * join the run invocation seen on the line. The next drain starts the abort invocation.\n\t */\n\tasync abort(id: TaskId, context: Context): Promise<\"marked\" | \"terminal\"> {\n\t\tconst marked = await this.#session.commitWith(async (tx) => {\n\t\t\tconst current = await tx.task(id);\n\t\t\tif (current === undefined) throw new Error(`Task ${id} does not exist`);\n\t\t\tif (current.state.status === \"terminal\") return { result: \"terminal\" as const };\n\t\t\tconst live = current as LiveTaskRecord;\n\t\t\tconst invocation = this.#invocations.get(id);\n\t\t\tif (invocation === undefined) {\n\t\t\t\tconst resolution = this.#resolve(live, this.#registry.snapshot());\n\t\t\t\tif (resolution.kind === \"blocked\") {\n\t\t\t\t\tawait this.#terminate(tx, live, { status: \"orphaned\", reason: resolution.reason });\n\t\t\t\t\treturn { result: \"marked\" as const };\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!live.abortRequested) tx.setTask({ ...live, abortRequested: true });\n\t\t\treturn { result: \"marked\" as const, run: invocation?.mode === \"run\" ? invocation : undefined };\n\t\t}, context);\n\t\tif (marked.run !== undefined) {\n\t\t\tmarked.run.controller.abort();\n\t\t\tawait awaitWithContext(marked.run.done, context);\n\t\t}\n\t\treturn marked.result;\n\t}\n\n\tasync waitForTask(id: TaskId, context: Context): Promise<SettledTask<JsonValue>> {\n\t\t// Check and register on the line so no terminal publication falls between them.\n\t\tconst found = await this.#session.readOnLine(async () => {\n\t\t\tif (this.#closing) throw closedError();\n\t\t\tif (this.#live.has(id)) return { promise: this.#taskWaiters.add(id, context) };\n\t\t\tconst record = await this.#storage.task(id, context);\n\t\t\tif (record === undefined) throw new Error(`Task ${id} does not exist`);\n\t\t\treturn { promise: Promise.resolve(record as SettledTask<JsonValue>) };\n\t\t});\n\t\treturn found.promise;\n\t}\n\n\t/** Resolve when no live non-background task exists, optionally within one conversation. */\n\twaitForIdle(conversationId: ConversationId | undefined, context: Context): Promise<void> {\n\t\tif (this.#closing) return Promise.reject(closedError());\n\t\tif (this.#idle(conversationId)) return Promise.resolve();\n\t\treturn this.#idleWaiters.add(conversationId, context);\n\t}\n\n\t// ─── Scheduling ────────────────────────────────────────────────────────\n\n\t#observe(publication: CommitPublication): void {\n\t\tlet changed = false;\n\t\tfor (const change of publication.changes) {\n\t\t\tif (change.type !== \"task\") continue;\n\t\t\tchanged = true;\n\t\t\tconst record = change.value;\n\t\t\tif (record.state.status !== \"terminal\") {\n\t\t\t\tthis.#live.set(record.id, record as LiveTaskRecord);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthis.#live.delete(record.id);\n\t\t\tthis.#failedMigrations.delete(record.id);\n\t\t\tthis.#taskWaiters.resolve(record.id, record as SettledTask<JsonValue>);\n\t\t}\n\t\tif (!changed) return;\n\t\tfor (const conversationId of this.#idleWaiters.keys()) {\n\t\t\tif (this.#idle(conversationId)) this.#idleWaiters.resolve(conversationId);\n\t\t}\n\t\tthis.#kick();\n\t}\n\n\t/** Close listener: runs synchronously once admission is sealed, before `join()`. */\n\t#seal(): void {\n\t\tthis.#closing = true;\n\t\tthis.#unsubscribeRegistry();\n\t\tconst error = closedError();\n\t\tthis.#taskWaiters.rejectAll(error);\n\t\tthis.#idleWaiters.rejectAll(error);\n\t\tfor (const invocation of this.#invocations.values()) invocation.controller.abort();\n\t}\n\n\t#kick(): void {\n\t\tthis.#dirty = true;\n\t\tif (this.#draining || !this.#enabled || this.#closing) return;\n\t\tthis.#draining = true;\n\t\t// Never commit synchronously from a commit or registry listener.\n\t\tqueueMicrotask(() => void this.#drain());\n\t}\n\n\tasync #drain(): Promise<void> {\n\t\ttry {\n\t\t\twhile (this.#dirty && this.#enabled && !this.#closing) {\n\t\t\t\tthis.#dirty = false;\n\t\t\t\tfor (const reservation of await this.#reserve()) this.#start(reservation);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (!this.#closing) this.#report(error);\n\t\t} finally {\n\t\t\tthis.#draining = false;\n\t\t\t// A wakeup that arrived during a failed pass still needs its pass.\n\t\t\tif (this.#dirty) this.#kick();\n\t\t}\n\t}\n\n\t/** Reserve every eligible task in one commit; orphan abort-marked tasks no definition can take. */\n\tasync #reserve(): Promise<Reservation[]> {\n\t\tconst reservations: Reservation[] = [];\n\t\ttry {\n\t\t\tawait this.#session.commitWith(async (tx) => {\n\t\t\t\tif (!this.#enabled || this.#closing) return;\n\t\t\t\t// Taken once per pass, and only when some task is a candidate.\n\t\t\t\tlet snapshot: RegistrySnapshot | undefined;\n\t\t\t\tfor (const record of [...this.#live.values()]) {\n\t\t\t\t\tif (this.#invocations.has(record.id) || this.#waitingOn(record).length > 0) continue;\n\t\t\t\t\tconst mode = record.abortRequested ? \"abort\" : \"run\";\n\t\t\t\t\tsnapshot ??= this.#registry.snapshot();\n\t\t\t\t\tconst resolution = this.#resolve(record, snapshot);\n\t\t\t\t\tif (resolution.kind === \"blocked\") {\n\t\t\t\t\t\tif (mode === \"abort\")\n\t\t\t\t\t\t\tawait this.#terminate(tx, record, { status: \"orphaned\", reason: resolution.reason });\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (resolution.record !== record || record.state.status !== \"running\") {\n\t\t\t\t\t\ttx.setTask(\n\t\t\t\t\t\t\twithState(resolution.record, {\n\t\t\t\t\t\t\t\tstatus: \"running\",\n\t\t\t\t\t\t\t\tcheckpoint: resolution.record.state.checkpoint,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\t// Registered on the line, so marks and later reservations see it and close joins it.\n\t\t\t\t\tconst invocation = this.#createInvocation(record, mode);\n\t\t\t\t\treservations.push({ invocation, task: resolution.task, snapshot });\n\t\t\t\t}\n\t\t\t}, this.#context);\n\t\t} catch (error) {\n\t\t\tfor (const { invocation } of reservations) {\n\t\t\t\tthis.#invocations.delete(invocation.taskId);\n\t\t\t\tinvocation.finish();\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\treturn reservations;\n\t}\n\n\t/** Resolve the record's definition by kind, migrating an older stored version. */\n\t#resolve(record: LiveTaskRecord, snapshot: RegistrySnapshot): Resolution {\n\t\tconst fit = this.#fit(record, snapshot.task(record.kind));\n\t\tif (\"reason\" in fit) return { kind: \"blocked\", reason: fit.reason };\n\t\tif (!fit.migrates) return { kind: \"ready\", task: fit.task, record };\n\t\tconst definition = erased(fit.task);\n\t\ttry {\n\t\t\tif (definition.migrate === undefined) throw missingMigration(record, definition);\n\t\t\tconst migrated = definition.migrate(record.input, record.state.checkpoint, record.version);\n\t\t\tconst state = { status: record.state.status, checkpoint: copyJson(migrated.checkpoint) };\n\t\t\tconst migratedRecord = { ...record, version: definition.version, input: copyJson(migrated.input), state };\n\t\t\treturn { kind: \"ready\", task: fit.task, record: migratedRecord as LiveTaskRecord };\n\t\t} catch (error) {\n\t\t\tthis.#failedMigrations.set(record.id, { task: fit.task, error });\n\t\t\tthis.#report(error);\n\t\t\treturn { kind: \"blocked\", reason: \"migration_failed\" };\n\t\t}\n\t}\n\n\t#fit(record: LiveTaskRecord, task: AnyTask | undefined): Fit {\n\t\tif (task === undefined) return { reason: \"missing_task\" };\n\t\tconst version = task.definition.version;\n\t\tif (version === record.version) return { task, migrates: false };\n\t\tif (version < record.version) return { reason: \"task_too_old\" };\n\t\tconst failed = this.#failedMigrations.get(record.id);\n\t\tif (failed?.task === task) return { reason: \"migration_failed\", error: failed.error };\n\t\treturn { task, migrates: true };\n\t}\n\n\t/** Live dependencies a run waits for; an abort mark bypasses them and a running task has passed them. */\n\t#waitingOn(record: LiveTaskRecord): TaskId[] {\n\t\tif (record.abortRequested || record.state.status !== \"pending\") return [];\n\t\treturn record.after.filter((id) => this.#live.has(id));\n\t}\n\n\t/**\n\t * Scheduling state and every live task with its derived state, read on the Session line. Runs no task code: a\n\t * pending migration shows as `ready` with `migrates`, and only a migration the scheduler already tried, or one that\n\t * cannot exist, shows as failed.\n\t */\n\tinspect(snapshot: RegistrySnapshot): { scheduling: HarnessInspection[\"scheduling\"]; tasks: TaskInspection[] } {\n\t\tconst tasks: TaskInspection[] = [];\n\t\tfor (const record of this.#live.values()) tasks.push({ record, state: this.#inspectTask(record, snapshot) });\n\t\tconst scheduling = this.#closing ? \"closing\" : this.#enabled ? \"running\" : \"paused\";\n\t\treturn { scheduling, tasks };\n\t}\n\n\t#inspectTask(record: LiveTaskRecord, snapshot: RegistrySnapshot): TaskInspection[\"state\"] {\n\t\tif (this.#invocations.has(record.id)) return { kind: \"running\" };\n\t\tconst fit = this.#fit(record, snapshot.task(record.kind));\n\t\tif (\"reason\" in fit) return { kind: \"blocked\", ...fit };\n\t\tif (fit.migrates && fit.task.definition.migrate === undefined) {\n\t\t\treturn { kind: \"blocked\", reason: \"migration_failed\", error: missingMigration(record, erased(fit.task)) };\n\t\t}\n\t\tconst on = this.#waitingOn(record);\n\t\treturn on.length > 0 ? { kind: \"waiting\", on } : { kind: \"ready\", migrates: fit.migrates };\n\t}\n\n\t#createInvocation(record: LiveTaskRecord, mode: \"run\" | \"abort\"): Invocation {\n\t\tconst controller = new AbortController();\n\t\tconst { promise: done, resolve: finish } = Promise.withResolvers<void>();\n\t\tconst invocation: Invocation = {\n\t\t\ttaskId: record.id,\n\t\t\tconversationId: record.conversationId,\n\t\t\tmode,\n\t\t\tcontroller,\n\t\t\tcontext: withAbortSignal(controller.signal, this.#context),\n\t\t\twatches: new Set(),\n\t\t\tended: false,\n\t\t\tdone,\n\t\t\tfinish: () => finish(),\n\t\t};\n\t\tthis.#invocations.set(record.id, invocation);\n\t\treturn invocation;\n\t}\n\n\t#start(reservation: Reservation): void {\n\t\tconst invocation = reservation.invocation;\n\t\tvoid (async () => {\n\t\t\ttry {\n\t\t\t\tif (invocation.mode === \"run\") await this.#run(reservation);\n\t\t\t\telse await this.#runAbort(reservation);\n\t\t\t} catch (error) {\n\t\t\t\tthis.#report(error);\n\t\t\t} finally {\n\t\t\t\tthis.#end(invocation);\n\t\t\t\tinvocation.finish();\n\t\t\t\tthis.#kick();\n\t\t\t}\n\t\t})();\n\t}\n\n\t/** Run phase handlers, each preceded by a step that decides on the line whether the invocation continues. */\n\tasync #run(reservation: Reservation): Promise<void> {\n\t\tconst invocation = reservation.invocation;\n\t\tconst state = { task: reservation.task, snapshot: reservation.snapshot, reported: undefined as ReportedTask };\n\t\tconst runtime = this.#runtime(invocation, () => state.snapshot);\n\t\tlet previous: PhaseResult | undefined;\n\t\tfor (;;) {\n\t\t\tconst current = await this.#step(invocation, (tx, current) => this.#decide(tx, current, previous, state));\n\t\t\t// Close may seal between the decision and dispatch.\n\t\t\tif (current === undefined || this.#closing) return;\n\t\t\tconst checkpoint = current.state.checkpoint;\n\t\t\ttry {\n\t\t\t\tawait erased(state.task).phases[checkpoint.phase]!(current, runtime, invocation.context);\n\t\t\t\tprevious = { checkpoint };\n\t\t\t} catch (error) {\n\t\t\t\tprevious = { checkpoint, failure: { error } };\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Precedence rules for a run invocation, on the line. Rules 1 (terminal) and 2 (closing) are applied by `#step`.\n\t * Returns whether the invocation continues with the next phase.\n\t */\n\t#decide(\n\t\ttx: Transaction,\n\t\tcurrent: ErasedRunningTask,\n\t\tprevious: PhaseResult | undefined,\n\t\tstate: { task: AnyTask; snapshot: RegistrySnapshot; reported: ReportedTask },\n\t): Decision {\n\t\t// 3. abort mark: end; the next drain starts a fresh abort invocation.\n\t\tif (current.abortRequested) return false;\n\t\tif (previous === undefined) return true;\n\t\t// 4. uncaught error.\n\t\tif (previous.failure !== undefined) return { fault: previous.failure.error };\n\t\t// 6. no durable progress.\n\t\tif (jsonEqual(current.state.checkpoint, previous.checkpoint)) {\n\t\t\tconst message = `Task ${current.kind} phase ${previous.checkpoint.phase} returned without durable progress`;\n\t\t\treturn { fault: new Error(message) };\n\t\t}\n\t\t// 5. progress: refresh the snapshot; hand over to a replacement definition that can take the task.\n\t\tstate.snapshot = this.#registry.snapshot();\n\t\tconst next = state.snapshot.task(current.kind);\n\t\tif (next !== state.task) {\n\t\t\tif (next !== undefined && canReserve(next, current)) {\n\t\t\t\ttx.setTask(withState(current, { status: \"pending\", checkpoint: current.state.checkpoint }));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (state.reported === undefined || state.reported.task !== next) {\n\t\t\t\tstate.reported = { task: next };\n\t\t\t\tconst cause = next === undefined ? \"missing_task\" : \"incompatible_task\";\n\t\t\t\tthis.#report(\n\t\t\t\t\tnew Error(`Task ${current.id} keeps running under its old ${current.kind} definition`, { cause }),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\t/** Run the abort handler once; rules 1, 2, and 4 apply, and returning without an outcome faults. */\n\tasync #runAbort(reservation: Reservation): Promise<void> {\n\t\tconst invocation = reservation.invocation;\n\t\tconst current = this.#live.get(invocation.taskId) as ErasedRunningTask | undefined;\n\t\tif (current === undefined || this.#closing) return;\n\t\tlet failure: { readonly error: unknown } | undefined;\n\t\ttry {\n\t\t\tconst runtime = this.#runtime(invocation, () => reservation.snapshot);\n\t\t\tawait erased(reservation.task).abort(current, runtime, invocation.context);\n\t\t} catch (error) {\n\t\t\tfailure = { error };\n\t\t}\n\t\tconst message = `Abort handler of task ${invocation.taskId} returned without a terminal outcome`;\n\t\tawait this.#step(invocation, () => ({ fault: failure?.error ?? new Error(message) }));\n\t}\n\n\t/**\n\t * One synchronous decision on the Session line. A terminal task (rule 1) or a closing Harness (rule 2) ends the\n\t * invocation without a write; otherwise `decide` may stage a write and returns whether the invocation continues.\n\t * Ending happens inside the callback, before a fault's Harness cleanup. A rejected step, such as admission after\n\t * close, also ends the invocation.\n\t */\n\tasync #step(\n\t\tinvocation: Invocation,\n\t\tdecide: (tx: Transaction, current: ErasedRunningTask) => Decision,\n\t): Promise<ErasedRunningTask | undefined> {\n\t\ttry {\n\t\t\treturn await this.#session.commitWith(async (tx) => {\n\t\t\t\tconst current = this.#live.get(invocation.taskId) as ErasedRunningTask | undefined;\n\t\t\t\tconst decision = current !== undefined && !this.#closing ? decide(tx, current) : false;\n\t\t\t\tif (decision === true) return current;\n\t\t\t\tthis.#end(invocation);\n\t\t\t\tif (decision !== false) {\n\t\t\t\t\tconst message = decision.fault instanceof Error ? decision.fault.message : String(decision.fault);\n\t\t\t\t\tawait this.#terminate(tx, current!, { status: \"faulted\", error: { message } });\n\t\t\t\t}\n\t\t\t\treturn undefined;\n\t\t\t}, this.#context);\n\t\t} catch (error) {\n\t\t\tthis.#end(invocation);\n\t\t\tif (!this.#closing) this.#report(error);\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\t/** Write a scheduler-decided terminal outcome together with its Harness cleanup. */\n\t#terminate(tx: Transaction, record: LiveTaskRecord, outcome: SchedulerOutcome): Promise<void> {\n\t\ttx.setTask(withState(record, { status: \"terminal\", outcome }));\n\t\treturn this.#settleOutcome(tx, record, outcome);\n\t}\n\n\t/** End an invocation: its runtime operations reject from now on, its watches stop, and its task is free. */\n\t#end(invocation: Invocation): void {\n\t\tif (invocation.ended) return;\n\t\tinvocation.ended = true;\n\t\tif (this.#invocations.get(invocation.taskId) === invocation) this.#invocations.delete(invocation.taskId);\n\t\tfor (const watch of invocation.watches) void watch.stop();\n\t}\n\n\t#idle(conversationId: ConversationId | undefined): boolean {\n\t\tfor (const record of this.#live.values()) {\n\t\t\tif (record.background) continue;\n\t\t\tif (conversationId === undefined || record.conversationId === conversationId) return false;\n\t\t}\n\t\treturn true;\n\t}\n\n\t// ─── Invocation runtime ──────────────────────────────────────────────────\n\n\t#runtime(invocation: Invocation, snapshot: () => RegistrySnapshot): ErasedRuntime {\n\t\treturn {\n\t\t\ttaskId: invocation.taskId as TaskId<JsonValue>,\n\t\t\tconversationId: invocation.conversationId,\n\t\t\tsignal: invocation.controller.signal,\n\t\t\tmodels: this.#models,\n\t\t\tget registry() {\n\t\t\t\treturn snapshot();\n\t\t\t},\n\t\t\tcommit: (change, context) =>\n\t\t\t\tthis.#gated(\n\t\t\t\t\tinvocation,\n\t\t\t\t\tasync (tx, current) => {\n\t\t\t\t\t\tconst next = await change(tx, current);\n\t\t\t\t\t\tif (next !== undefined) tx.setTask(withState(current, next));\n\t\t\t\t\t},\n\t\t\t\t\tcontext,\n\t\t\t\t),\n\t\t\tmemo: ((name: string, ...rest: readonly unknown[]) => {\n\t\t\t\tif (rest.length === 1) {\n\t\t\t\t\treturn this.#read(invocation, async () => memoOf(this.#live.get(invocation.taskId), name));\n\t\t\t\t}\n\t\t\t\tconst candidate = rest[0] as JsonValue;\n\t\t\t\treturn this.#gated(\n\t\t\t\t\tinvocation,\n\t\t\t\t\t(tx, current) => {\n\t\t\t\t\t\tconst winner = memoOf(current, name);\n\t\t\t\t\t\tif (winner !== undefined) return winner;\n\t\t\t\t\t\ttx.setTask({ ...current, memos: { ...current.memos, [name]: candidate } } as AnyTaskRecord);\n\t\t\t\t\t\treturn candidate;\n\t\t\t\t\t},\n\t\t\t\t\trest[1] as Context,\n\t\t\t\t);\n\t\t\t}) as ErasedRuntime[\"memo\"],\n\t\t\tsleep: (until, context) => this.#sleep(invocation, until, context),\n\t\t\twatchDoc: ((...args: readonly unknown[]) => this.#watchDoc(invocation, args)) as ErasedRuntime[\"watchDoc\"],\n\t\t\tsnapshot: ((...args: readonly unknown[]) =>\n\t\t\t\tthis.#read(invocation, () =>\n\t\t\t\t\tsessionMethod(this.#session, \"snapshot\")(...args),\n\t\t\t\t)) as ErasedRuntime[\"snapshot\"],\n\t\t\tsnapshotAsOf: ((...args: readonly unknown[]) =>\n\t\t\t\tthis.#read(invocation, () =>\n\t\t\t\t\tsessionMethod(this.#session, \"snapshotAsOf\")(...args),\n\t\t\t\t)) as ErasedRuntime[\"snapshotAsOf\"],\n\t\t\tcontext: (conversationId, context, at) =>\n\t\t\t\tthis.#read(invocation, () => readContext(this.#session, this.#storage, conversationId, context, at)),\n\t\t\tnow: () => this.#now(),\n\t\t\treport: (error) => this.#report(error),\n\t\t};\n\t}\n\n\t/** Run a committed-state read unless the invocation has ended. */\n\tasync #read<T>(invocation: Invocation, read: () => Promise<T>): Promise<T> {\n\t\tif (invocation.ended) throw endedError(invocation);\n\t\treturn read();\n\t}\n\n\t/** Commit after rereading the task on the line and gating the invocation. */\n\t#gated<T>(\n\t\tinvocation: Invocation,\n\t\tchange: (tx: Transaction, current: ErasedRunningTask) => T | Promise<T>,\n\t\tcontext: Context,\n\t): Promise<T> {\n\t\tif (invocation.ended) return Promise.reject(endedError(invocation));\n\t\treturn this.#session.commitWith(\n\t\t\tasync (tx) => {\n\t\t\t\tif (invocation.ended) throw endedError(invocation);\n\t\t\t\tif (this.#closing) throw closedError();\n\t\t\t\tconst current = this.#live.get(invocation.taskId) as ErasedRunningTask | undefined;\n\t\t\t\tif (current === undefined) throw new Error(`Task ${invocation.taskId} is terminal`);\n\t\t\t\tif (invocation.mode === \"run\" && current.abortRequested) {\n\t\t\t\t\tthrow new Error(`Task ${invocation.taskId} has a durable abort mark`);\n\t\t\t\t}\n\t\t\t\treturn change(tx, current);\n\t\t\t},\n\t\t\tcontext,\n\t\t\t{ conversationId: invocation.conversationId, taskId: invocation.taskId },\n\t\t);\n\t}\n\n\t/** Wait until the Harness clock reaches `until`, rechecking it after every timer. */\n\tasync #sleep(invocation: Invocation, until: number, context: Context): Promise<void> {\n\t\tif (invocation.ended) throw endedError(invocation);\n\t\tconst signals = [invocation.controller.signal];\n\t\tif (context.abortSignal !== undefined) signals.push(context.abortSignal);\n\t\tconst signal = AbortSignal.any(signals);\n\t\tfor (;;) {\n\t\t\tsignal.throwIfAborted();\n\t\t\tconst remaining = until - this.#now();\n\t\t\tif (remaining <= 0) return;\n\t\t\tawait delay(Math.min(remaining, MAX_TIMER_DELAY), signal);\n\t\t}\n\t}\n\n\tasync #watchDoc(invocation: Invocation, args: readonly unknown[]): Promise<DocumentWatch<JsonObject> | undefined> {\n\t\tif (invocation.ended) throw endedError(invocation);\n\t\tconst watch = (await sessionMethod(this.#session, \"watchDoc\")(...args)) as DocumentWatch<JsonObject> | undefined;\n\t\tif (watch === undefined) return undefined;\n\t\tif (invocation.ended) {\n\t\t\tvoid watch.stop();\n\t\t\tthrow endedError(invocation);\n\t\t}\n\t\tinvocation.watches.add(watch);\n\t\tvoid watch.closed.then(() => invocation.watches.delete(watch));\n\t\treturn watch;\n\t}\n}\n\n/** Own memo entry only; memo names such as `toString` must not resolve to inherited properties. */\nfunction memoOf(record: LiveTaskRecord | undefined, name: string): JsonValue | undefined {\n\tconst memos = record?.memos;\n\treturn memos !== undefined && Object.hasOwn(memos, name) ? memos[name] : undefined;\n}\n\n/** Overloaded Session method bound for forwarding an argument list unchanged. */\nfunction sessionMethod(\n\tsession: SessionImpl,\n\tname: \"snapshot\" | \"snapshotAsOf\" | \"watchDoc\",\n): (...args: readonly unknown[]) => Promise<unknown> {\n\treturn (session[name] as (...args: readonly unknown[]) => Promise<unknown>).bind(session);\n}\n\nfunction missingMigration(record: LiveTaskRecord, definition: ErasedDefinition): Error {\n\treturn new Error(`Task ${record.kind} version ${definition.version} has no migration from ${record.version}`);\n}\n\nfunction erased(task: AnyTask): ErasedDefinition {\n\treturn task.definition as unknown as ErasedDefinition;\n}\n\nfunction endedError(invocation: Invocation): Error {\n\treturn new Error(`Task ${invocation.taskId} invocation has ended`);\n}\n\n/** Replace a live record's state; memos disappear in the terminal replacement. */\nfunction withState(record: LiveTaskRecord, state: TaskState<JsonValue, JsonValue>): AnyTaskRecord {\n\tif (state.status !== \"terminal\") return { ...record, state } as AnyTaskRecord;\n\tconst { memos: _memos, ...rest } = record;\n\treturn { ...rest, state };\n}\n\n/** Whether a definition can take the task at reservation: same version, or newer with a migration. */\nfunction canReserve(task: AnyTask, record: LiveTaskRecord): boolean {\n\tconst definition = task.definition;\n\treturn (\n\t\tdefinition.version === record.version || (definition.version > record.version && definition.migrate !== undefined)\n\t);\n}\n\nfunction delay(ms: number, signal: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst onAbort = (): void => {\n\t\t\tclearTimeout(timer);\n\t\t\treject(signal.reason);\n\t\t};\n\t\tconst timer = setTimeout(() => {\n\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\tresolve();\n\t\t}, ms);\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t});\n}\n\n/** Structural equality of two JSON values; object key order is ignored. */\nfunction jsonEqual(left: JsonValue | undefined, right: JsonValue | undefined): boolean {\n\tif (left === right) return true;\n\tif (typeof left !== \"object\" || typeof right !== \"object\" || left === null || right === null) return false;\n\tif (Array.isArray(left) || Array.isArray(right)) {\n\t\tif (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) return false;\n\t\treturn left.every((value, index) => jsonEqual(value, right[index]));\n\t}\n\tconst keys = Object.keys(left);\n\tif (keys.length !== Object.keys(right).length) return false;\n\treturn keys.every((key) => Object.hasOwn(right, key) && jsonEqual(left[key], right[key]));\n}\n"]}
|
|
1
|
+
{"version":3,"file":"scheduler.js","sourceRoot":"","sources":["../../src/harness/scheduler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,QAAQ,EAAkB,MAAM,uBAAuB,CAAC;AAC/E,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAuBlF,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAW3C,OAAO,EAAE,WAAW,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAa1D,MAAM,cAAc,GAAG,GAAG,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KAAK,KAAK,QAAQ,IAAI,IAAI,KAAK,IAAI,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,KAAK,CAAC;IAC3G,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QACjD,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,IAAI,CAAC,MAAM,KAAK,KAAK,CAAC,MAAM;YAAE,OAAO,KAAK,CAAC;QAChG,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC,SAAS,CAAC,KAAK,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IACrE,CAAC;IACD,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC/B,IAAI,IAAI,CAAC,MAAM,KAAK,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,MAAM;QAAE,OAAO,KAAK,CAAC;IAC5D,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,EAAE,GAAG,CAAC,IAAI,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;AAC3F,CAAC","sourcesContent":["import { type Context, copyJson, type JsonValue } from \"@earendil-works/chord\";\nimport { awaitWithContext, withAbortSignal } from \"@earendil-works/chord/context\";\nimport type { Models } from \"@earendil-works/pi-ai\";\nimport type { ExecutionEnv } from \"../env/index.ts\";\nimport type { SessionImpl } from \"../session/session.ts\";\nimport type { Transaction } from \"../session/transaction.ts\";\nimport type {\n\tCommitPublication,\n\tConversationId,\n\tDocumentWatch,\n\tEntryId,\n\tEntryRecord,\n\tHookRunner,\n\tJsonObject,\n\tNextTaskState,\n\tRunningTask,\n\tStorage,\n\tTaskDefinition,\n\tTaskId,\n\tTaskOutcome,\n\tTaskRecord,\n\tTaskRuntime,\n\tTaskState,\n} from \"../types.ts\";\nimport { readContext } from \"./context.ts\";\nimport type {\n\tAnyTask,\n\tConversationHandle,\n\tHarnessInspection,\n\tHookScope,\n\tRegistryReader,\n\tRegistrySnapshot,\n\tSettledTask,\n\tTaskInspection,\n} from \"./types.ts\";\nimport { closedError, scanAll, Waiters } from \"./util.ts\";\n\ntype AnyTaskRecord = TaskRecord<JsonValue, JsonValue, JsonValue>;\n/** A record that can still run code: pending, running, or waiting. */\ntype RunnableTaskRecord = Extract<\n\tAnyTaskRecord,\n\t{ readonly state: { readonly status: \"pending\" | \"running\" | \"waiting\" } }\n>;\ntype Checkpoint = { readonly phase: string };\ntype ErasedDefinition = TaskDefinition<JsonValue, Checkpoint, JsonValue, object>;\ntype ErasedRuntime = TaskRuntime<JsonValue, Checkpoint, JsonValue, object>;\ntype ErasedRunningTask = RunningTask<JsonValue, Checkpoint, JsonValue>;\n\nconst SCAN_PAGE_SIZE = 256;\n/** Longest delay `setTimeout` supports; longer sleeps wait in several steps. */\nconst MAX_TIMER_DELAY = 2_147_483_647;\nconst LIVE_STATUSES = [\"pending\", \"running\", \"waiting\", \"completing\"] as const;\n\n/** Why a pending task cannot be reserved under a registry snapshot. Derived, never persisted. */\ntype BlockedReason = \"missing_task\" | \"task_too_old\" | \"migration_failed\";\n\ntype Resolution =\n\t| { readonly kind: \"ready\"; readonly task: AnyTask; readonly record: RunnableTaskRecord }\n\t| { readonly kind: \"blocked\"; readonly reason: BlockedReason };\n\n/** A definition that can take a record, or why none can; deciding it runs no task code. */\ntype Fit =\n\t| { readonly task: AnyTask; readonly migrates: boolean }\n\t| { readonly reason: BlockedReason; readonly error?: unknown };\n\n/** One in-memory execution of a task in run or abort mode. */\ntype Invocation = {\n\treadonly taskId: TaskId;\n\treadonly conversationId: ConversationId;\n\treadonly mode: \"run\" | \"abort\";\n\treadonly controller: AbortController;\n\t/** Context passed to handlers; cancelled by `controller`. */\n\treadonly context: Context;\n\t/** Watches acquired through the runtime; stopped at invocation end. */\n\treadonly watches: Set<DocumentWatch<JsonObject>>;\n\tended: boolean;\n\treadonly done: Promise<void>;\n\treadonly finish: () => void;\n};\n\ntype Reservation = {\n\treadonly invocation: Invocation;\n\treadonly task: AnyTask;\n\treadonly snapshot: RegistrySnapshot;\n};\n\n/** Replacement definition already reported as unable to take over, per invocation. */\ntype ReportedTask = { readonly task: AnyTask | undefined } | undefined;\n\n/** Outcome of the phase that just returned, judged by the next step. */\ntype PhaseResult = { readonly checkpoint: Checkpoint; readonly failure?: { readonly error: unknown } };\n\n/** Step decision: continue with the next phase, end the invocation, or end it by writing `faulted`. */\ntype Decision = boolean | { readonly fault: unknown };\n\n/** Terminal outcomes the scheduler writes without running task code. */\nexport type SchedulerOutcome = Extract<TaskOutcome<JsonValue>, { readonly status: \"faulted\" | \"orphaned\" }>;\n\n/** An invocation a conversation handle is bound to: its signal, and a check that throws once it ended. */\nexport type InvocationBinding = { readonly signal: AbortSignal; check(): void };\n\n/** The immutable ownership fields of a task. */\ntype TaskNode = Pick<AnyTaskRecord, \"conversationId\" | \"owner\" | \"background\">;\n\n/** Where a walk up the ownership tree continues: an owner task, or a conversation. */\ntype Up = { readonly task: TaskId } | { readonly conversation: ConversationId };\n\n/** One step of a walk up: an owner task with its node, a conversation, or an owner edge that is not loaded yet. */\ntype Step =\n\t| { readonly task: TaskId; readonly node: TaskNode }\n\t| { readonly conversation: ConversationId }\n\t| { readonly unknown: true };\n\n/** Candidate records a commit staged; they override committed records in ownership walks. */\ntype Overlay = {\n\treadonly tasks: ReadonlyMap<TaskId, AnyTaskRecord>;\n\treadonly edges: ReadonlyMap<ConversationId, TaskId | null>;\n};\n\n/** Where ordinary ownership traversal starts: one conversation, or every ownerless conversation. */\ntype Scope = { readonly conversation: ConversationId } | { readonly roots: true };\n\nexport type TaskSchedulerOptions = {\n\treadonly session: SessionImpl;\n\treadonly storage: Storage;\n\treadonly registry: RegistryReader;\n\treadonly models: Models;\n\treadonly env: ExecutionEnv | undefined;\n\treadonly now: () => number;\n\treadonly report: (error: unknown) => void;\n\t/** Harness cleanup staged in the commit that makes an outcome the scheduler wrote itself terminal. */\n\treadonly settleOutcome: (tx: Transaction, record: AnyTaskRecord, outcome: SchedulerOutcome) => Promise<void>;\n\t/** Withdraw a conversation's queued inputs, for conversation abort and abort cascades. */\n\treadonly withdrawInputs: (tx: Transaction, conversationId: ConversationId) => Promise<void>;\n\t/** Invocation-bound handle of an existing conversation, for task runtimes and tools. */\n\treadonly conversation: (\n\t\tid: ConversationId,\n\t\tbinding: InvocationBinding,\n\t\tcontext: Context,\n\t) => Promise<ConversationHandle | undefined>;\n\t/** Context for scheduler commits and invocations; carries no caller cancellation. */\n\treadonly context: Context;\n};\n\n/**\n * Durable task scheduler of one Harness.\n *\n * `#live` mirrors every committed non-terminal task record: pending, running, waiting, and completing. The synchronous\n * commit listener updates it on the Session line, so code running on the line reads exactly the committed state from it.\n *\n * Tasks and conversations form one ownership tree (spec §5.5): a task's parent is its owner task, or its conversation;\n * a conversation's parent is its owner task, if any. Walks up that tree decide cascades, idle scopes, and whether a\n * task's ordinary owned work is live, which holds its outcome as `completing` and delays its abort handler.\n *\n * Invariant: every task transition is decided and written by one callback serialized on the Session line. That covers\n * reservation, marks, runtime commits, finalization, and the synchronous step before each phase, which applies the\n * precedence rules and writes a fault or handover. Handlers and joins run off the line. An invocation ends inside the\n * step that decides its end, so a runtime commit it queued either lands before that decision or is rejected.\n */\nexport class TaskScheduler {\n\treadonly #session: SessionImpl;\n\treadonly #storage: Storage;\n\treadonly #registry: RegistryReader;\n\treadonly #models: Models;\n\treadonly #env: ExecutionEnv | undefined;\n\treadonly #now: () => number;\n\treadonly #report: (error: unknown) => void;\n\treadonly #settleOutcome: TaskSchedulerOptions[\"settleOutcome\"];\n\treadonly #withdrawInputs: TaskSchedulerOptions[\"withdrawInputs\"];\n\treadonly #conversation: TaskSchedulerOptions[\"conversation\"];\n\treadonly #context: Context;\n\treadonly #live = new Map<TaskId, AnyTaskRecord>();\n\treadonly #invocations = new Map<TaskId, Invocation>();\n\treadonly #taskWaiters = new Waiters<TaskId, SettledTask<JsonValue>>();\n\t/** Idle waiters by conversation; `undefined` waits for the whole Harness. */\n\treadonly #idleWaiters = new Waiters<ConversationId | undefined, void>();\n\t/** Definition whose migration failed per task; retried only once the registry resolves another definition. */\n\treadonly #failedMigrations = new Map<TaskId, { readonly task: AnyTask; readonly error: unknown }>();\n\t/** Owner task of each loaded conversation, `null` when ownerless. */\n\treadonly #edges = new Map<ConversationId, TaskId | null>();\n\t/** Tasks that own a loaded conversation; their nodes stay in `#settled` once terminal. */\n\treadonly #conversationOwners = new Set<TaskId>();\n\t/** Ownership fields of terminal tasks that walks pass through. */\n\treadonly #settled = new Map<TaskId, TaskNode>();\n\t/**\n\t * `failFast` waiters the next reconcile checks for a failed task in `on`: at open, when they start waiting, and when\n\t * one of their tasks fails.\n\t */\n\treadonly #failFastChecks = new Set<TaskId>();\n\t#reconcileScheduled = false;\n\t#cascadePending = false;\n\t#unsubscribeRegistry: () => void = () => {};\n\t#enabled = false;\n\t#closing = false;\n\t#dirty = false;\n\t#draining = false;\n\n\tconstructor(options: TaskSchedulerOptions) {\n\t\tthis.#session = options.session;\n\t\tthis.#storage = options.storage;\n\t\tthis.#registry = options.registry;\n\t\tthis.#models = options.models;\n\t\tthis.#env = options.env;\n\t\tthis.#now = options.now;\n\t\tthis.#report = options.report;\n\t\tthis.#settleOutcome = options.settleOutcome;\n\t\tthis.#withdrawInputs = options.withdrawInputs;\n\t\tthis.#conversation = options.conversation;\n\t\tthis.#context = options.context;\n\t}\n\n\t/** Load live tasks and change surviving `running` tasks back to `pending`. Dispatches nothing. */\n\tasync open(context: Context): Promise<void> {\n\t\tthis.#session.subscribeCommits((publication) => this.#observe(publication));\n\t\tthis.#session.subscribeClose(() => this.#seal());\n\t\tthis.#unsubscribeRegistry = this.#registry.subscribe(() => this.#kick());\n\t\tawait this.#session.commitWith(async (tx) => {\n\t\t\t// Every table read before the first write.\n\t\t\tconst scans = [];\n\t\t\tfor (const status of LIVE_STATUSES) {\n\t\t\t\tscans.push(await scanAll((cursor) => tx.scanTasks({ status }, SCAN_PAGE_SIZE, cursor)));\n\t\t\t}\n\t\t\tfor (const records of scans) {\n\t\t\t\tfor (const record of records) {\n\t\t\t\t\tthis.#live.set(record.id, record);\n\t\t\t\t\tif (record.state.status === \"running\") {\n\t\t\t\t\t\ttx.setTask(withState(record, { status: \"pending\", checkpoint: record.state.checkpoint }));\n\t\t\t\t\t}\n\t\t\t\t\tif (record.state.status === \"waiting\" && record.state.policy === \"failFast\") {\n\t\t\t\t\t\tthis.#failFastChecks.add(record.id);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}, context);\n\t\t// Derive abort marks a crash left unapplied below cancelled owners, and finalize held outcomes.\n\t\tthis.#cascadePending = true;\n\t\tthis.#scheduleReconcile();\n\t}\n\n\t/** Enable scheduling. Idempotent; the kick does nothing once closing. */\n\tresume(): void {\n\t\tthis.#enabled = true;\n\t\tthis.#kick();\n\t}\n\n\t/** Wait for every invocation signalled by `#seal()`. Writes nothing. */\n\tasync join(): Promise<void> {\n\t\tawait Promise.allSettled([...this.#invocations.values()].map((invocation) => invocation.done));\n\t}\n\n\t/**\n\t * Commit the abort mark, or settle a task that no registered definition can take as `orphaned` when nothing it owns\n\t * is live, then join the run invocation seen on the line; the commit listener signalled it. The abort invocation\n\t * starts once the task's ordinary owned work is gone. A `completing` task is only marked.\n\t */\n\tasync abort(id: TaskId, context: Context): Promise<\"marked\" | \"terminal\"> {\n\t\tconst marked = await this.#session.commitWith(async (tx) => {\n\t\t\tconst current = await tx.task(id);\n\t\t\tif (current === undefined) throw new Error(`Task ${id} does not exist`);\n\t\t\tif (current.state.status === \"terminal\") return { result: \"terminal\" as const };\n\t\t\tconst invocation = this.#invocations.get(id);\n\t\t\tif (invocation === undefined && current.state.status !== \"completing\") {\n\t\t\t\tawait this.#loadScopes(false);\n\t\t\t\tif (!this.#ownedLive().has(id)) {\n\t\t\t\t\tconst resolution = this.#resolve(current as RunnableTaskRecord, this.#registry.snapshot());\n\t\t\t\t\tif (resolution.kind === \"blocked\") {\n\t\t\t\t\t\tawait this.#terminate(tx, current, { status: \"orphaned\", reason: resolution.reason });\n\t\t\t\t\t\treturn { result: \"marked\" as const };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!current.abortRequested) tx.setTask({ ...current, abortRequested: true });\n\t\t\treturn { result: \"marked\" as const, run: invocation?.mode === \"run\" ? invocation : undefined };\n\t\t}, context);\n\t\t// The commit listener signalled the run; join it.\n\t\tif (marked.run !== undefined) await awaitWithContext(marked.run.done, context);\n\t\treturn marked.result;\n\t}\n\n\tasync waitForTask(id: TaskId, context: Context): Promise<SettledTask<JsonValue>> {\n\t\t// Check and register on the line so no terminal publication falls between them.\n\t\tconst found = await this.#session.readOnLine(async () => {\n\t\t\tif (this.#closing) throw closedError();\n\t\t\tif (this.#live.has(id)) return { promise: this.#taskWaiters.add(id, context) };\n\t\t\tconst record = await this.#storage.task(id, context);\n\t\t\tif (record === undefined) throw new Error(`Task ${id} does not exist`);\n\t\t\treturn { promise: Promise.resolve(record as SettledTask<JsonValue>) };\n\t\t});\n\t\treturn found.promise;\n\t}\n\n\t/**\n\t * Resolve when ordinary traversal from the conversation, or from every ownerless conversation, reaches no live\n\t * non-background task.\n\t */\n\twaitForIdle(conversationId: ConversationId | undefined, context: Context): Promise<void> {\n\t\tif (this.#closing) return Promise.reject(closedError());\n\t\tif (this.#idle(conversationId)) return Promise.resolve();\n\t\tthis.#scheduleReconcile();\n\t\treturn this.#idleWaiters.add(conversationId, context);\n\t}\n\n\t/**\n\t * `Conversation.abort()`: in one commit, withdraw the queued inputs and mark every live non-background task that\n\t * ordinary traversal from the conversation reaches; resolves once the scope is idle. With `background`, traversal\n\t * crosses background boundaries, and the wait also covers every task it reached.\n\t */\n\tasync abortConversation(conversationId: ConversationId, background: boolean, context: Context): Promise<void> {\n\t\tconst reached = await this.#session.commitWith(async (tx) => {\n\t\t\tconst queued = await this.#loadScopes(true);\n\t\t\tconst scope = { conversation: conversationId };\n\t\t\tconst reached: TaskId[] = [];\n\t\t\tfor (const record of this.#live.values()) {\n\t\t\t\tif (record.background && !background) continue;\n\t\t\t\tif (this.#inScope(parentOf(record), scope, background) !== true) continue;\n\t\t\t\treached.push(record.id);\n\t\t\t\tif (!record.abortRequested) tx.setTask({ ...record, abortRequested: true });\n\t\t\t}\n\t\t\tfor (const id of queued) {\n\t\t\t\tif (this.#inScope({ conversation: id }, scope, background) === true) await this.#withdrawInputs(tx, id);\n\t\t\t}\n\t\t\treturn reached;\n\t\t}, context);\n\t\tif (background) for (const id of reached) await this.waitForTask(id, context);\n\t\tawait this.waitForIdle(conversationId, context);\n\t}\n\n\t// ─── Scheduling ────────────────────────────────────────────────────────\n\n\t#observe(publication: CommitPublication): void {\n\t\tconst updated: AnyTaskRecord[] = [];\n\t\tconst failed: TaskId[] = [];\n\t\tlet changed = false;\n\t\tfor (const change of publication.changes) {\n\t\t\tif (change.type !== \"task\") continue;\n\t\t\tchanged = true;\n\t\t\tconst record = change.value;\n\t\t\tconst previous = this.#live.get(record.id);\n\t\t\tif (failedOutcome(record) && (previous === undefined || !failedOutcome(previous))) failed.push(record.id);\n\t\t\tif (record.state.status === \"terminal\") {\n\t\t\t\tthis.#live.delete(record.id);\n\t\t\t\tthis.#failedMigrations.delete(record.id);\n\t\t\t\tthis.#failFastChecks.delete(record.id);\n\t\t\t\tif (this.#conversationOwners.has(record.id)) this.#settled.set(record.id, nodeOf(record));\n\t\t\t\tthis.#taskWaiters.resolve(record.id, record as SettledTask<JsonValue>);\n\t\t\t\t// Its owner may finalize now.\n\t\t\t\tthis.#scheduleReconcile();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (record.abortRequested && previous?.abortRequested !== true) {\n\t\t\t\tthis.#cascadePending = true;\n\t\t\t\t// Signal a run invocation of the newly marked task; its next step ends it.\n\t\t\t\tconst invocation = this.#invocations.get(record.id);\n\t\t\t\tif (invocation?.mode === \"run\") invocation.controller.abort();\n\t\t\t}\n\t\t\tconst status = record.state.status;\n\t\t\tif (status === \"completing\" && previous?.state.status !== \"completing\") {\n\t\t\t\tif (cancellationIntent(record)) this.#cascadePending = true;\n\t\t\t\tthis.#scheduleReconcile();\n\t\t\t}\n\t\t\tif (status === \"waiting\" && record.state.policy === \"failFast\" && previous?.state.status !== \"waiting\") {\n\t\t\t\tthis.#failFastChecks.add(record.id);\n\t\t\t\tthis.#scheduleReconcile();\n\t\t\t}\n\t\t\tthis.#live.set(record.id, record);\n\t\t\tupdated.push(record);\n\t\t}\n\t\tfor (const id of failed) {\n\t\t\tfor (const record of this.#live.values()) {\n\t\t\t\tconst state = record.state;\n\t\t\t\tif (state.status === \"waiting\" && state.policy === \"failFast\" && state.on.includes(id)) {\n\t\t\t\t\tthis.#failFastChecks.add(record.id);\n\t\t\t\t\tthis.#scheduleReconcile();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (const change of publication.changes) {\n\t\t\tif (change.type === \"conversation\" && !this.#edges.has(change.value.id)) {\n\t\t\t\tthis.#setEdge(change.value.id, change.value.owner?.taskId ?? null);\n\t\t\t}\n\t\t}\n\t\tfor (const change of publication.changes) {\n\t\t\t// A queued input below a cancelled owner is withdrawn, even after its cascade.\n\t\t\tif (change.type !== \"submission\" || change.value.status !== \"queued\" || change.value.type !== \"input\")\n\t\t\t\tcontinue;\n\t\t\tconst up = { conversation: change.value.conversationId };\n\t\t\tif (!this.#chainKnown(up) || this.#belowCancelled(up)) this.#cascadePending = true;\n\t\t}\n\t\tfor (const record of updated) {\n\t\t\t// Work created below a cancelled owner, even after its cascade, is aborted too.\n\t\t\tif (!this.#chainKnown(parentOf(record))) this.#scheduleReconcile();\n\t\t\telse if (!record.background && !record.abortRequested && this.#belowCancelled(parentOf(record))) {\n\t\t\t\tthis.#cascadePending = true;\n\t\t\t}\n\t\t}\n\t\t// Also retries, with the next commit of any kind, a cascade whose commit failed.\n\t\tif (this.#cascadePending) this.#scheduleReconcile();\n\t\tif (!changed) return;\n\t\tthis.#resolveIdleWaiters();\n\t\tthis.#kick();\n\t}\n\n\t#resolveIdleWaiters(): void {\n\t\tfor (const conversationId of this.#idleWaiters.keys()) {\n\t\t\tif (this.#idle(conversationId)) this.#idleWaiters.resolve(conversationId);\n\t\t}\n\t}\n\n\t// ─── Ownership ───────────────────────────────────────────────────────────\n\n\t#scheduleReconcile(): void {\n\t\tif (this.#reconcileScheduled || this.#closing) return;\n\t\tthis.#reconcileScheduled = true;\n\t\tqueueMicrotask(() => void this.#reconcile());\n\t}\n\n\t/**\n\t * One commit that applies what committed records imply: abort marks below live owners with cancellation intent\n\t * (spec §5.4), `failFast` marks (spec §5.5), withdrawn queued inputs below cancelled owners, and the final terminal\n\t * record of every `completing` task whose ordinary owned work is gone. The durable records are the intent, so this\n\t * also repairs whatever a crash left unapplied. Resolves idle waiters that the loaded edges decide.\n\t */\n\tasync #reconcile(): Promise<void> {\n\t\tthis.#reconcileScheduled = false;\n\t\tconst cascade = this.#cascadePending;\n\t\tthis.#cascadePending = false;\n\t\tconst checks = [...this.#failFastChecks];\n\t\tthis.#failFastChecks.clear();\n\t\ttry {\n\t\t\tawait this.#session.commitWith(async (tx) => {\n\t\t\t\tif (this.#closing) return;\n\t\t\t\tconst queued = await this.#loadScopes(cascade);\n\t\t\t\tconst marked = new Set<TaskId>();\n\t\t\t\tconst mark = (record: AnyTaskRecord): void => {\n\t\t\t\t\tif (record.abortRequested || marked.has(record.id)) return;\n\t\t\t\t\tmarked.add(record.id);\n\t\t\t\t\ttx.setTask({ ...record, abortRequested: true });\n\t\t\t\t};\n\t\t\t\t// Loading edges can reveal a cancelled owner, so marks are derived on every pass.\n\t\t\t\tfor (const record of this.#live.values()) {\n\t\t\t\t\tif (!record.background && this.#belowCancelled(parentOf(record))) mark(record);\n\t\t\t\t}\n\t\t\t\tfor (const id of checks) {\n\t\t\t\t\tconst waiter = this.#live.get(id);\n\t\t\t\t\tif (waiter?.state.status !== \"waiting\" || !(await this.#anyFailed(waiter.state.on))) continue;\n\t\t\t\t\t// Every other live task: the failed one keeps its own outcome.\n\t\t\t\t\tfor (const member of waiter.state.on) {\n\t\t\t\t\t\tconst record = this.#live.get(member);\n\t\t\t\t\t\tif (record !== undefined && !failedOutcome(record)) mark(record);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (const id of queued) if (this.#belowCancelled({ conversation: id })) await this.#withdrawInputs(tx, id);\n\t\t\t\tawait this.#finalize(tx);\n\t\t\t}, this.#context);\n\t\t} catch (error) {\n\t\t\t// Any pass may have staged marks, so a failed one is retried with the next commit.\n\t\t\tthis.#cascadePending = true;\n\t\t\tfor (const id of checks) this.#failFastChecks.add(id);\n\t\t\tif (!this.#closing) this.#report(error);\n\t\t}\n\t\tthis.#resolveIdleWaiters();\n\t}\n\n\t/** Whether any of `ids` holds or ended with an outcome other than `completed`. */\n\tasync #anyFailed(ids: readonly TaskId[]): Promise<boolean> {\n\t\tfor (const id of ids) {\n\t\t\tconst record = this.#live.get(id) ?? (await this.#storage.task(id, this.#context));\n\t\t\tif (record !== undefined && failedOutcome(record)) return true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Write the terminal record of every `completing` task without live ordinary owned work. Finalizing one can free its\n\t * owner, so this repeats over the commit's candidates until nothing changes. A held scheduler outcome gets its\n\t * Harness cleanup here.\n\t */\n\tasync #finalize(tx: Transaction): Promise<void> {\n\t\tfor (;;) {\n\t\t\tconst overlay = overlayOf(tx);\n\t\t\tconst owned = this.#ownedLive(overlay);\n\t\t\tconst done = [...this.#liveRecords(overlay)].filter(\n\t\t\t\t(record) => record.state.status === \"completing\" && !owned.has(record.id),\n\t\t\t);\n\t\t\tif (done.length === 0) return;\n\t\t\tfor (const record of done) {\n\t\t\t\tconst outcome = (record.state as { readonly outcome: TaskOutcome<JsonValue> }).outcome;\n\t\t\t\ttx.setTask(withState(record, { status: \"terminal\", outcome }));\n\t\t\t\t// REMINDER: only the scheduler writes `faulted` and `orphaned` (spec §5.4); their cleanup waits for this commit.\n\t\t\t\tif (outcome.status === \"faulted\" || outcome.status === \"orphaned\") {\n\t\t\t\t\tawait this.#settleOutcome(tx, record, outcome);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Load the owner chains of every live task and, with `queued`, of every conversation with queued submissions, on the\n\t * Session line; returns the latter. Reads committed Storage directly, so it may run inside a commit callback.\n\t */\n\tasync #loadScopes(queued: boolean): Promise<ConversationId[]> {\n\t\tfor (const record of [...this.#live.values()]) {\n\t\t\tif (!this.#chainKnown(parentOf(record))) await this.#loadChain(parentOf(record));\n\t\t}\n\t\tif (!queued) return [];\n\t\tconst submissions = await scanAll((cursor) =>\n\t\t\tthis.#storage.scanSubmissions({ status: \"queued\" }, SCAN_PAGE_SIZE, cursor, this.#context),\n\t\t);\n\t\tconst conversations = [...new Set(submissions.map((submission) => submission.conversationId))];\n\t\tfor (const id of conversations) await this.#loadChain({ conversation: id });\n\t\treturn conversations;\n\t}\n\n\t/** Load the owner edges and task nodes from `start` up to its ownerless root. */\n\tasync #loadChain(start: Up, overlay?: Overlay): Promise<void> {\n\t\tlet at: Up | undefined = start;\n\t\twhile (at !== undefined) {\n\t\t\tif (\"task\" in at) {\n\t\t\t\tlet node = this.#node(at.task, overlay);\n\t\t\t\tif (node === undefined) {\n\t\t\t\t\tconst record = await this.#storage.task(at.task, this.#context);\n\t\t\t\t\tif (record === undefined) return;\n\t\t\t\t\tnode = nodeOf(record);\n\t\t\t\t\tif (record.state.status === \"terminal\") this.#settled.set(record.id, node);\n\t\t\t\t}\n\t\t\t\tat = parentOf(node);\n\t\t\t} else {\n\t\t\t\tlet edge = this.#edge(at.conversation, overlay);\n\t\t\t\tif (edge === undefined) {\n\t\t\t\t\tconst record = await this.#storage.conversation(at.conversation, this.#context);\n\t\t\t\t\tedge = record?.owner?.taskId ?? null;\n\t\t\t\t\tthis.#setEdge(at.conversation, edge);\n\t\t\t\t}\n\t\t\t\tat = edge === null ? undefined : { task: edge };\n\t\t\t}\n\t\t}\n\t}\n\n\t#setEdge(conversationId: ConversationId, owner: TaskId | null): void {\n\t\tthis.#edges.set(conversationId, owner);\n\t\tif (owner !== null) this.#conversationOwners.add(owner);\n\t}\n\n\t/** Owner task of a conversation, `null` when ownerless, `undefined` while not loaded. */\n\t#edge(id: ConversationId, overlay?: Overlay): TaskId | null | undefined {\n\t\treturn overlay?.edges.has(id) === true ? overlay.edges.get(id) : this.#edges.get(id);\n\t}\n\n\t#node(id: TaskId, overlay?: Overlay): TaskNode | undefined {\n\t\treturn overlay?.tasks.get(id) ?? this.#live.get(id) ?? this.#settled.get(id);\n\t}\n\n\t/** Walk up from `start`: owner tasks and conversations, ending at an ownerless root or an edge not loaded yet. */\n\t*#above(start: Up, overlay?: Overlay): Generator<Step> {\n\t\tlet at: Up | undefined = start;\n\t\twhile (at !== undefined) {\n\t\t\tif (\"task\" in at) {\n\t\t\t\tconst node = this.#node(at.task, overlay);\n\t\t\t\tif (node === undefined) {\n\t\t\t\t\tyield { unknown: true };\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tyield { task: at.task, node };\n\t\t\t\tat = parentOf(node);\n\t\t\t} else {\n\t\t\t\tyield { conversation: at.conversation };\n\t\t\t\tconst edge = this.#edge(at.conversation, overlay);\n\t\t\t\tif (edge === undefined) {\n\t\t\t\t\tyield { unknown: true };\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tat = edge === null ? undefined : { task: edge };\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Whether every owner above `start` is loaded. */\n\t#chainKnown(start: Up, overlay?: Overlay): boolean {\n\t\tfor (const step of this.#above(start, overlay)) if (\"unknown\" in step) return false;\n\t\treturn true;\n\t}\n\n\t/** Live records, with the overlay's candidates replacing committed ones; terminal candidates are gone. */\n\t*#liveRecords(overlay?: Overlay): Generator<AnyTaskRecord> {\n\t\tfor (const record of this.#live.values()) {\n\t\t\tconst candidate = overlay?.tasks.get(record.id) ?? record;\n\t\t\tif (candidate.state.status !== \"terminal\") yield candidate;\n\t\t}\n\t\tif (overlay === undefined) return;\n\t\tfor (const record of overlay.tasks.values()) {\n\t\t\tif (!this.#live.has(record.id) && record.state.status !== \"terminal\") yield record;\n\t\t}\n\t}\n\n\t/**\n\t * Every task with live ordinary owned work (spec §5.5), mapped to that work: each live non-background task counts for\n\t * every owner task above it up to and including the first background one. Owner chains must be loaded.\n\t */\n\t#ownedLive(overlay?: Overlay): Map<TaskId, TaskId[]> {\n\t\tconst owned = new Map<TaskId, TaskId[]>();\n\t\tfor (const record of this.#liveRecords(overlay)) {\n\t\t\tif (record.background) continue;\n\t\t\tfor (const step of this.#above(parentOf(record), overlay)) {\n\t\t\t\tif (\"unknown\" in step) break;\n\t\t\t\tif (!(\"task\" in step)) continue;\n\t\t\t\tconst below = owned.get(step.task);\n\t\t\t\tif (below === undefined) owned.set(step.task, [record.id]);\n\t\t\t\telse below.push(record.id);\n\t\t\t\tif (step.node.background) break;\n\t\t\t}\n\t\t}\n\t\treturn owned;\n\t}\n\n\t/**\n\t * Whether ordinary traversal from `scope` reaches `start`: walking up reaches the scope's conversation, or an\n\t * ownerless one for `roots`, without crossing a background owner, unless `crossBackground`. `undefined` while an\n\t * edge is not loaded.\n\t */\n\t#inScope(start: Up, scope: Scope, crossBackground = false): boolean | undefined {\n\t\tfor (const step of this.#above(start)) {\n\t\t\tif (\"unknown\" in step) return undefined;\n\t\t\tif (\"conversation\" in step) {\n\t\t\t\tif (\"conversation\" in scope && step.conversation === scope.conversation) return true;\n\t\t\t} else if (step.node.background && !crossBackground) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn \"roots\" in scope;\n\t}\n\n\t/**\n\t * Whether a live owner's cancellation intent reaches `start`: walking up finds an owner with intent before a\n\t * background owner without it. Terminal owners never cascade (spec §5.4).\n\t */\n\t#belowCancelled(start: Up): boolean {\n\t\tfor (const step of this.#above(start)) {\n\t\t\tif (\"unknown\" in step) return false;\n\t\t\tif (!(\"task\" in step)) continue;\n\t\t\tconst live = this.#live.get(step.task);\n\t\t\tif (live !== undefined && cancellationIntent(live)) return true;\n\t\t\tif (step.node.background) return false;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/** Close listener: runs synchronously once admission is sealed, before `join()`. */\n\t#seal(): void {\n\t\tthis.#closing = true;\n\t\tthis.#unsubscribeRegistry();\n\t\tconst error = closedError();\n\t\tthis.#taskWaiters.rejectAll(error);\n\t\tthis.#idleWaiters.rejectAll(error);\n\t\tfor (const invocation of this.#invocations.values()) invocation.controller.abort();\n\t}\n\n\t#kick(): void {\n\t\tthis.#dirty = true;\n\t\tif (this.#draining || !this.#enabled || this.#closing) return;\n\t\tthis.#draining = true;\n\t\t// Never commit synchronously from a commit or registry listener.\n\t\tqueueMicrotask(() => void this.#drain());\n\t}\n\n\tasync #drain(): Promise<void> {\n\t\ttry {\n\t\t\twhile (this.#dirty && this.#enabled && !this.#closing) {\n\t\t\t\tthis.#dirty = false;\n\t\t\t\tfor (const reservation of await this.#reserve()) this.#start(reservation);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (!this.#closing) this.#report(error);\n\t\t} finally {\n\t\t\tthis.#draining = false;\n\t\t\t// A wakeup that arrived during a failed pass still needs its pass.\n\t\t\tif (this.#dirty) this.#kick();\n\t\t}\n\t}\n\n\t/** Reserve every eligible task in one commit; orphan abort-marked tasks no definition can take. */\n\tasync #reserve(): Promise<Reservation[]> {\n\t\tconst reservations: Reservation[] = [];\n\t\ttry {\n\t\t\tawait this.#session.commitWith(async (tx) => {\n\t\t\t\tif (!this.#enabled || this.#closing) return;\n\t\t\t\tawait this.#loadScopes(false);\n\t\t\t\tconst owned = this.#ownedLive();\n\t\t\t\t// Taken once per pass, and only when some task is a candidate.\n\t\t\t\tlet snapshot: RegistrySnapshot | undefined;\n\t\t\t\tfor (const record of [...this.#live.values()]) {\n\t\t\t\t\tif (this.#invocations.has(record.id) || this.#waitingOn(record, owned).length > 0) continue;\n\t\t\t\t\tif (record.state.status === \"completing\") continue;\n\t\t\t\t\tconst runnable = record as RunnableTaskRecord;\n\t\t\t\t\tconst mode = record.abortRequested ? \"abort\" : \"run\";\n\t\t\t\t\tsnapshot ??= this.#registry.snapshot();\n\t\t\t\t\tconst resolution = this.#resolve(runnable, snapshot);\n\t\t\t\t\tif (resolution.kind === \"blocked\") {\n\t\t\t\t\t\tif (mode === \"abort\") {\n\t\t\t\t\t\t\tawait this.#terminate(tx, record, { status: \"orphaned\", reason: resolution.reason });\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (resolution.record !== runnable || record.state.status !== \"running\") {\n\t\t\t\t\t\ttx.setTask(\n\t\t\t\t\t\t\twithState(resolution.record, {\n\t\t\t\t\t\t\t\tstatus: \"running\",\n\t\t\t\t\t\t\t\tcheckpoint: resolution.record.state.checkpoint,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\t// Registered on the line, so marks and later reservations see it and close joins it.\n\t\t\t\t\tconst invocation = this.#createInvocation(record, mode);\n\t\t\t\t\treservations.push({ invocation, task: resolution.task, snapshot });\n\t\t\t\t}\n\t\t\t}, this.#context);\n\t\t} catch (error) {\n\t\t\tfor (const { invocation } of reservations) {\n\t\t\t\tthis.#invocations.delete(invocation.taskId);\n\t\t\t\tinvocation.finish();\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\treturn reservations;\n\t}\n\n\t/**\n\t * Live tasks a task waits for before its next invocation: its live ordinary owned work when abort-marked, since\n\t * abort runs bottom-up, otherwise the live part of the `on` of a wait.\n\t */\n\t#waitingOn(record: AnyTaskRecord, owned: ReadonlyMap<TaskId, readonly TaskId[]>): readonly TaskId[] {\n\t\tif (record.abortRequested) return owned.get(record.id) ?? [];\n\t\tif (record.state.status !== \"waiting\") return [];\n\t\treturn record.state.on.filter((id) => this.#live.has(id));\n\t}\n\n\t/** Resolve the record's definition by kind, migrating an older stored version. */\n\t#resolve(record: RunnableTaskRecord, snapshot: RegistrySnapshot): Resolution {\n\t\tconst fit = this.#fit(record, snapshot.task(record.kind));\n\t\tif (\"reason\" in fit) return { kind: \"blocked\", reason: fit.reason };\n\t\tif (!fit.migrates) return { kind: \"ready\", task: fit.task, record };\n\t\tconst definition = erased(fit.task);\n\t\ttry {\n\t\t\tif (definition.migrate === undefined) throw missingMigration(record, definition);\n\t\t\tconst migrated = definition.migrate(record.input, record.state.checkpoint, record.version);\n\t\t\tconst state = { ...record.state, checkpoint: copyJson(migrated.checkpoint) };\n\t\t\tconst migratedRecord = { ...record, version: definition.version, input: copyJson(migrated.input), state };\n\t\t\treturn { kind: \"ready\", task: fit.task, record: migratedRecord as RunnableTaskRecord };\n\t\t} catch (error) {\n\t\t\tthis.#failedMigrations.set(record.id, { task: fit.task, error });\n\t\t\tthis.#report(error);\n\t\t\treturn { kind: \"blocked\", reason: \"migration_failed\" };\n\t\t}\n\t}\n\n\t#fit(record: AnyTaskRecord, task: AnyTask | undefined): Fit {\n\t\tif (task === undefined) return { reason: \"missing_task\" };\n\t\tconst version = task.definition.version;\n\t\tif (version === record.version) return { task, migrates: false };\n\t\tif (version < record.version) return { reason: \"task_too_old\" };\n\t\tconst failed = this.#failedMigrations.get(record.id);\n\t\tif (failed?.task === task) return { reason: \"migration_failed\", error: failed.error };\n\t\treturn { task, migrates: true };\n\t}\n\n\t/**\n\t * Scheduling state and every live task with its derived state, read on the Session line. Runs no task code: a\n\t * pending migration shows as `ready` with `migrates`, and only a migration the scheduler already tried, or one that\n\t * cannot exist, shows as failed.\n\t */\n\tasync inspect(\n\t\tsnapshot: RegistrySnapshot,\n\t): Promise<{ scheduling: HarnessInspection[\"scheduling\"]; tasks: TaskInspection[] }> {\n\t\tawait this.#loadScopes(false);\n\t\tconst owned = this.#ownedLive();\n\t\tconst tasks: TaskInspection[] = [];\n\t\tfor (const record of this.#live.values()) {\n\t\t\ttasks.push({ record, state: this.#inspectTask(record, snapshot, owned) });\n\t\t}\n\t\tconst scheduling = this.#closing ? \"closing\" : this.#enabled ? \"running\" : \"paused\";\n\t\treturn { scheduling, tasks };\n\t}\n\n\t#inspectTask(\n\t\trecord: AnyTaskRecord,\n\t\tsnapshot: RegistrySnapshot,\n\t\towned: ReadonlyMap<TaskId, readonly TaskId[]>,\n\t): TaskInspection[\"state\"] {\n\t\tif (this.#invocations.has(record.id)) return { kind: \"running\" };\n\t\tif (record.state.status === \"completing\") return { kind: \"completing\" };\n\t\tconst on = this.#waitingOn(record, owned);\n\t\tif (on.length > 0) return { kind: \"waiting\", on };\n\t\tconst fit = this.#fit(record, snapshot.task(record.kind));\n\t\tif (\"reason\" in fit) return { kind: \"blocked\", ...fit };\n\t\tif (fit.migrates && fit.task.definition.migrate === undefined) {\n\t\t\treturn { kind: \"blocked\", reason: \"migration_failed\", error: missingMigration(record, erased(fit.task)) };\n\t\t}\n\t\treturn { kind: \"ready\", migrates: fit.migrates };\n\t}\n\n\t#createInvocation(record: AnyTaskRecord, mode: \"run\" | \"abort\"): Invocation {\n\t\tconst controller = new AbortController();\n\t\tconst { promise: done, resolve: finish } = Promise.withResolvers<void>();\n\t\tconst invocation: Invocation = {\n\t\t\ttaskId: record.id,\n\t\t\tconversationId: record.conversationId,\n\t\t\tmode,\n\t\t\tcontroller,\n\t\t\tcontext: withAbortSignal(controller.signal, this.#context),\n\t\t\twatches: new Set(),\n\t\t\tended: false,\n\t\t\tdone,\n\t\t\tfinish: () => finish(),\n\t\t};\n\t\tthis.#invocations.set(record.id, invocation);\n\t\treturn invocation;\n\t}\n\n\t#start(reservation: Reservation): void {\n\t\tconst invocation = reservation.invocation;\n\t\tvoid (async () => {\n\t\t\ttry {\n\t\t\t\tif (invocation.mode === \"run\") await this.#run(reservation);\n\t\t\t\telse await this.#runAbort(reservation);\n\t\t\t} catch (error) {\n\t\t\t\tthis.#report(error);\n\t\t\t} finally {\n\t\t\t\tthis.#end(invocation);\n\t\t\t\tinvocation.finish();\n\t\t\t\tthis.#kick();\n\t\t\t}\n\t\t})();\n\t}\n\n\t/** Run phase handlers, each preceded by a step that decides on the line whether the invocation continues. */\n\tasync #run(reservation: Reservation): Promise<void> {\n\t\tconst invocation = reservation.invocation;\n\t\tconst state = { task: reservation.task, snapshot: reservation.snapshot, reported: undefined as ReportedTask };\n\t\tconst runtime = this.#runtime(\n\t\t\tinvocation,\n\t\t\t() => state.snapshot,\n\t\t\t() => state.task,\n\t\t);\n\t\tlet previous: PhaseResult | undefined;\n\t\tfor (;;) {\n\t\t\tconst current = await this.#step(invocation, (tx, current) => this.#decide(tx, current, previous, state));\n\t\t\t// Close may seal between the decision and dispatch.\n\t\t\tif (current === undefined || this.#closing) return;\n\t\t\tconst checkpoint = current.state.checkpoint;\n\t\t\ttry {\n\t\t\t\tawait erased(state.task).phases[checkpoint.phase]!(current, runtime, invocation.context);\n\t\t\t\tprevious = { checkpoint };\n\t\t\t} catch (error) {\n\t\t\t\tprevious = { checkpoint, failure: { error } };\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Precedence rules for a run invocation, on the line. Rules 1 (terminal, `completing`, or `waiting`) and 2 (closing)\n\t * are applied by `#step`. Returns whether the invocation continues with the next phase.\n\t */\n\t#decide(\n\t\ttx: Transaction,\n\t\tcurrent: ErasedRunningTask,\n\t\tprevious: PhaseResult | undefined,\n\t\tstate: { task: AnyTask; snapshot: RegistrySnapshot; reported: ReportedTask },\n\t): Decision {\n\t\t// 3. abort mark: end; a fresh abort invocation starts once the task's ordinary owned work is gone.\n\t\tif (current.abortRequested) return false;\n\t\tif (previous === undefined) return true;\n\t\t// 4. uncaught error.\n\t\tif (previous.failure !== undefined) return { fault: previous.failure.error };\n\t\t// 6. no durable progress.\n\t\tif (jsonEqual(current.state.checkpoint, previous.checkpoint)) {\n\t\t\tconst message = `Task ${current.kind} phase ${previous.checkpoint.phase} returned without durable progress`;\n\t\t\treturn { fault: new Error(message) };\n\t\t}\n\t\t// 5. progress: refresh the snapshot; hand over to a replacement definition that can take the task.\n\t\tstate.snapshot = this.#registry.snapshot();\n\t\tconst next = state.snapshot.task(current.kind);\n\t\tif (next !== state.task) {\n\t\t\tif (next !== undefined && canReserve(next, current)) {\n\t\t\t\ttx.setTask(withState(current, { status: \"pending\", checkpoint: current.state.checkpoint }));\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (state.reported === undefined || state.reported.task !== next) {\n\t\t\t\tstate.reported = { task: next };\n\t\t\t\tconst cause = next === undefined ? \"missing_task\" : \"incompatible_task\";\n\t\t\t\tthis.#report(\n\t\t\t\t\tnew Error(`Task ${current.id} keeps running under its old ${current.kind} definition`, { cause }),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\t/** Run the abort handler once; rules 1, 2, and 4 apply, and returning without an outcome faults. */\n\tasync #runAbort(reservation: Reservation): Promise<void> {\n\t\tconst invocation = reservation.invocation;\n\t\tconst current = this.#live.get(invocation.taskId) as ErasedRunningTask | undefined;\n\t\tif (current === undefined || this.#closing) return;\n\t\tlet failure: { readonly error: unknown } | undefined;\n\t\ttry {\n\t\t\tconst runtime = this.#runtime(\n\t\t\t\tinvocation,\n\t\t\t\t() => reservation.snapshot,\n\t\t\t\t() => reservation.task,\n\t\t\t);\n\t\t\tawait erased(reservation.task).abort(current, runtime, invocation.context);\n\t\t} catch (error) {\n\t\t\tfailure = { error };\n\t\t}\n\t\tconst message = `Abort handler of task ${invocation.taskId} returned without a terminal outcome`;\n\t\tawait this.#step(invocation, () => ({ fault: failure?.error ?? new Error(message) }));\n\t}\n\n\t/**\n\t * One synchronous decision on the Session line. A task that is no longer running (rule 1: terminal, `completing`, or\n\t * `waiting`) or a closing Harness (rule 2) ends the invocation without a write; otherwise `decide` may stage a write\n\t * and returns whether the invocation continues. Ending happens inside the callback, before a fault's Harness\n\t * cleanup. A rejected step, such as admission after close, also ends the invocation.\n\t */\n\tasync #step(\n\t\tinvocation: Invocation,\n\t\tdecide: (tx: Transaction, current: ErasedRunningTask) => Decision,\n\t): Promise<ErasedRunningTask | undefined> {\n\t\ttry {\n\t\t\treturn await this.#session.commitWith(async (tx) => {\n\t\t\t\tconst found = this.#live.get(invocation.taskId);\n\t\t\t\tconst current = found?.state.status === \"running\" ? (found as ErasedRunningTask) : undefined;\n\t\t\t\tconst decision = current !== undefined && !this.#closing ? decide(tx, current) : false;\n\t\t\t\tif (decision === true) return current;\n\t\t\t\tthis.#end(invocation);\n\t\t\t\tif (decision !== false) {\n\t\t\t\t\tconst message = decision.fault instanceof Error ? decision.fault.message : String(decision.fault);\n\t\t\t\t\tawait this.#terminate(tx, current!, { status: \"faulted\", error: { message } });\n\t\t\t\t}\n\t\t\t\treturn undefined;\n\t\t\t}, this.#context);\n\t\t} catch (error) {\n\t\t\tthis.#end(invocation);\n\t\t\tif (!this.#closing) this.#report(error);\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\t/**\n\t * Write an outcome the scheduler decided. While the task's ordinary owned work is live it holds as `completing` and\n\t * its Harness cleanup waits for the final commit (spec §5.5, rule 4); otherwise it is terminal with its cleanup.\n\t */\n\tasync #terminate(tx: Transaction, record: AnyTaskRecord, outcome: SchedulerOutcome): Promise<void> {\n\t\tawait this.#loadScopes(false);\n\t\tif (this.#ownedLive(overlayOf(tx)).has(record.id)) {\n\t\t\ttx.setTask(withState(record, { status: \"completing\", outcome }));\n\t\t\treturn;\n\t\t}\n\t\ttx.setTask(withState(record, { status: \"terminal\", outcome }));\n\t\tawait this.#settleOutcome(tx, record, outcome);\n\t}\n\n\t/**\n\t * Replace a running task's state with what it committed. A terminal state holds as `completing` while ordinary owned\n\t * work is live, judged on the commit's candidates, so work the same commit creates below the task counts. A wait is\n\t * validated first.\n\t */\n\tasync #commitState(\n\t\ttx: Transaction,\n\t\tinvocation: Invocation,\n\t\tcurrent: ErasedRunningTask,\n\t\tnext: NextTaskState<Checkpoint, JsonValue>,\n\t): Promise<void> {\n\t\tif (next.status === \"waiting\") await this.#validateWait(tx, invocation, current, next.on, next.policy);\n\t\tif (next.status === \"terminal\") {\n\t\t\tconst overlay = overlayOf(tx);\n\t\t\tawait this.#loadScopes(false);\n\t\t\tfor (const record of overlay.tasks.values()) await this.#loadChain(parentOf(record), overlay);\n\t\t\tif (this.#ownedLive(overlay).has(current.id)) {\n\t\t\t\ttx.setTask(withState(current, { status: \"completing\", outcome: next.outcome }));\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\ttx.setTask(withState(current, next));\n\t}\n\n\t/**\n\t * A wait names existing tasks other than the waiter and its owners, which could never finish first; `failFast` only\n\t * tasks the waiter owns. An abort handler cannot wait.\n\t */\n\tasync #validateWait(\n\t\ttx: Transaction,\n\t\tinvocation: Invocation,\n\t\tcurrent: ErasedRunningTask,\n\t\ton: readonly TaskId[],\n\t\tpolicy: string,\n\t): Promise<void> {\n\t\tif (invocation.mode === \"abort\") throw new Error(`Abort handler of task ${current.id} cannot wait`);\n\t\tconst overlay = overlayOf(tx);\n\t\tawait this.#loadChain(parentOf(current));\n\t\tconst owners = new Set<TaskId>();\n\t\tfor (const step of this.#above(parentOf(current))) if (\"task\" in step) owners.add(step.task);\n\t\tfor (const id of on) {\n\t\t\tif (id === current.id || owners.has(id)) {\n\t\t\t\tthrow new Error(`Task ${current.id} cannot wait on itself or its owner ${id}`);\n\t\t\t}\n\t\t\tconst member = overlay.tasks.get(id) ?? this.#live.get(id) ?? (await this.#storage.task(id, this.#context));\n\t\t\tif (member === undefined) throw new Error(`Task ${id} does not exist`);\n\t\t\tif (policy === \"failFast\" && member.owner !== current.id) {\n\t\t\t\tthrow new Error(`Task ${current.id} can wait failFast only on tasks it owns; ${id} is not one`);\n\t\t\t}\n\t\t}\n\t}\n\n\t/** End an invocation: its runtime operations reject from now on, its signal aborts, its watches stop, and its task is free. */\n\t#end(invocation: Invocation): void {\n\t\tif (invocation.ended) return;\n\t\tinvocation.ended = true;\n\t\tif (this.#invocations.get(invocation.taskId) === invocation) this.#invocations.delete(invocation.taskId);\n\t\tfor (const watch of invocation.watches) void watch.stop();\n\t\t// Pending waits bound to the invocation, such as a tool's waitForTask(), reject with it.\n\t\tinvocation.controller.abort(endedError(invocation));\n\t}\n\n\t/** No live non-background task in the scope; a task whose owner edges are not loaded yet counts as inside. */\n\t#idle(conversationId: ConversationId | undefined): boolean {\n\t\tconst scope: Scope = conversationId === undefined ? { roots: true } : { conversation: conversationId };\n\t\tfor (const record of this.#live.values()) {\n\t\t\tif (!record.background && this.#inScope(parentOf(record), scope) !== false) return false;\n\t\t}\n\t\treturn true;\n\t}\n\n\t// ─── Invocation runtime ──────────────────────────────────────────────────\n\n\t#runtime(invocation: Invocation, snapshot: () => RegistrySnapshot, task: () => AnyTask): ErasedRuntime {\n\t\tconst hooks: HookRunner<Record<string, unknown>> = {\n\t\t\teach: async (name, invoke) => {\n\t\t\t\tif (invocation.ended) throw endedError(invocation);\n\t\t\t\tfor (const { handlers, scope } of snapshot().hooks(task())) {\n\t\t\t\t\tconst handler = (handlers as Record<string, unknown>)[name];\n\t\t\t\t\tif (typeof handler !== \"function\") continue;\n\t\t\t\t\tif (scope !== undefined && !(await this.#hookMatches(invocation, scope))) continue;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait invoke(handler.bind(handlers));\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (invocation.controller.signal.aborted) throw error;\n\t\t\t\t\t\tthis.#report(error);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t};\n\t\treturn {\n\t\t\ttaskId: invocation.taskId as TaskId<JsonValue>,\n\t\t\tconversationId: invocation.conversationId,\n\t\t\tsignal: invocation.controller.signal,\n\t\t\tmodels: this.#models,\n\t\t\tenv: this.#env,\n\t\t\thooks: hooks as ErasedRuntime[\"hooks\"],\n\t\t\tget registry() {\n\t\t\t\treturn snapshot();\n\t\t\t},\n\t\t\tcommit: (change, context) =>\n\t\t\t\tthis.#gated(\n\t\t\t\t\tinvocation,\n\t\t\t\t\tasync (tx, current) => {\n\t\t\t\t\t\tconst next = await change(tx, current);\n\t\t\t\t\t\tif (next !== undefined) await this.#commitState(tx, invocation, current, next);\n\t\t\t\t\t},\n\t\t\t\t\tcontext,\n\t\t\t\t),\n\t\t\tmemo: ((name: string, ...rest: readonly unknown[]) => {\n\t\t\t\tif (rest.length === 1) {\n\t\t\t\t\treturn this.#read(invocation, async () => memoOf(this.#live.get(invocation.taskId), name));\n\t\t\t\t}\n\t\t\t\tconst candidate = rest[0] as JsonValue;\n\t\t\t\treturn this.#gated(\n\t\t\t\t\tinvocation,\n\t\t\t\t\t(tx, current) => {\n\t\t\t\t\t\tconst winner = memoOf(current, name);\n\t\t\t\t\t\tif (winner !== undefined) return winner;\n\t\t\t\t\t\ttx.setTask({ ...current, memos: { ...current.memos, [name]: candidate } } as AnyTaskRecord);\n\t\t\t\t\t\treturn candidate;\n\t\t\t\t\t},\n\t\t\t\t\trest[1] as Context,\n\t\t\t\t);\n\t\t\t}) as ErasedRuntime[\"memo\"],\n\t\t\tsleep: (until, context) => this.#sleep(invocation, until, context),\n\t\t\twatchDoc: ((...args: readonly unknown[]) => this.#watchDoc(invocation, args)) as ErasedRuntime[\"watchDoc\"],\n\t\t\tsnapshot: ((...args: readonly unknown[]) =>\n\t\t\t\tthis.#read(invocation, () =>\n\t\t\t\t\tsessionMethod(this.#session, \"snapshot\")(...args),\n\t\t\t\t)) as ErasedRuntime[\"snapshot\"],\n\t\t\tsnapshotAsOf: ((...args: readonly unknown[]) =>\n\t\t\t\tthis.#read(invocation, () =>\n\t\t\t\t\tsessionMethod(this.#session, \"snapshotAsOf\")(...args),\n\t\t\t\t)) as ErasedRuntime[\"snapshotAsOf\"],\n\t\t\tgetTask: ((id: TaskId, context: Context) =>\n\t\t\t\tthis.#read(invocation, () =>\n\t\t\t\t\tthis.#session.readOnLine(() => this.#storage.task(id, context)),\n\t\t\t\t)) as ErasedRuntime[\"getTask\"],\n\t\t\twaitForTask: ((id: TaskId, context: Context) =>\n\t\t\t\tthis.#read(invocation, () =>\n\t\t\t\t\tthis.waitForTask(id, withAbortSignal(invocation.controller.signal, context)),\n\t\t\t\t)) as ErasedRuntime[\"waitForTask\"],\n\t\t\toutcomes: ((ids: readonly TaskId[], context: Context) =>\n\t\t\t\tthis.#read(invocation, () =>\n\t\t\t\t\tthis.#session.readOnLine(async () => {\n\t\t\t\t\t\tconst outcomes: TaskOutcome<JsonValue>[] = [];\n\t\t\t\t\t\tfor (const id of ids) {\n\t\t\t\t\t\t\tconst state = (await this.#storage.task(id, context))?.state;\n\t\t\t\t\t\t\tif (state?.status !== \"terminal\") throw new Error(`Task ${id} is not terminal`);\n\t\t\t\t\t\t\toutcomes.push(state.outcome);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn outcomes;\n\t\t\t\t\t}),\n\t\t\t\t)) as ErasedRuntime[\"outcomes\"],\n\t\t\tconversation: (id, context) =>\n\t\t\t\tthis.#read(invocation, () =>\n\t\t\t\t\tthis.#conversation(\n\t\t\t\t\t\tid,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsignal: invocation.controller.signal,\n\t\t\t\t\t\t\tcheck: () => {\n\t\t\t\t\t\t\t\tif (invocation.ended) throw endedError(invocation);\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tcontext,\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\tentry: ((...args: readonly unknown[]) => {\n\t\t\t\tconst [token, id, context] =\n\t\t\t\t\targs.length === 2\n\t\t\t\t\t\t? [undefined, args[0] as EntryId, args[1] as Context]\n\t\t\t\t\t\t: [args[0] as { readonly kind: string }, args[1] as EntryId, args[2] as Context];\n\t\t\t\treturn this.#read(invocation, async () => {\n\t\t\t\t\tconst found = await this.#session.readOnLine(() =>\n\t\t\t\t\t\tthis.#storage.entry(invocation.conversationId, id, context),\n\t\t\t\t\t);\n\t\t\t\t\tconst entry: EntryRecord | undefined = found?.entry;\n\t\t\t\t\treturn token === undefined || entry?.kind === token.kind ? entry : undefined;\n\t\t\t\t});\n\t\t\t}) as ErasedRuntime[\"entry\"],\n\t\t\tcontext: (conversationId, context, at) =>\n\t\t\t\tthis.#read(invocation, () => readContext(this.#session, this.#storage, conversationId, context, at)),\n\t\t\tnow: () => this.#now(),\n\t\t\treport: (error) => this.#report(error),\n\t\t};\n\t}\n\n\t/** Whether a scoped hook registration matches the invocation's conversation: itself, or an owner for `subtree`. */\n\tasync #hookMatches(invocation: Invocation, scope: HookScope): Promise<boolean> {\n\t\tif (scope.conversationId === invocation.conversationId) return true;\n\t\tif (scope.subtree !== true) return false;\n\t\tconst start = { conversation: invocation.conversationId };\n\t\tif (!this.#chainKnown(start)) await this.#session.readOnLine(() => this.#loadChain(start));\n\t\tfor (const step of this.#above(start)) {\n\t\t\tif (\"conversation\" in step && step.conversation === scope.conversationId) return true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/** Run a committed-state read unless the invocation has ended. */\n\tasync #read<T>(invocation: Invocation, read: () => Promise<T>): Promise<T> {\n\t\tif (invocation.ended) throw endedError(invocation);\n\t\treturn read();\n\t}\n\n\t/** Commit after rereading the task on the line and gating the invocation. */\n\t#gated<T>(\n\t\tinvocation: Invocation,\n\t\tchange: (tx: Transaction, current: ErasedRunningTask) => T | Promise<T>,\n\t\tcontext: Context,\n\t): Promise<T> {\n\t\tif (invocation.ended) return Promise.reject(endedError(invocation));\n\t\treturn this.#session.commitWith(\n\t\t\tasync (tx) => {\n\t\t\t\tif (invocation.ended) throw endedError(invocation);\n\t\t\t\tif (this.#closing) throw closedError();\n\t\t\t\tconst found = this.#live.get(invocation.taskId);\n\t\t\t\tif (found === undefined) throw new Error(`Task ${invocation.taskId} is terminal`);\n\t\t\t\tif (found.state.status !== \"running\") throw new Error(`Task ${invocation.taskId} is ${found.state.status}`);\n\t\t\t\tconst current = found as ErasedRunningTask;\n\t\t\t\tif (invocation.mode === \"run\" && current.abortRequested) {\n\t\t\t\t\tthrow new Error(`Task ${invocation.taskId} has a durable abort mark`);\n\t\t\t\t}\n\t\t\t\treturn change(tx, current);\n\t\t\t},\n\t\t\tcontext,\n\t\t\t{ conversationId: invocation.conversationId, taskId: invocation.taskId },\n\t\t);\n\t}\n\n\t/** Wait until the Harness clock reaches `until`, rechecking it after every timer. */\n\tasync #sleep(invocation: Invocation, until: number, context: Context): Promise<void> {\n\t\tif (invocation.ended) throw endedError(invocation);\n\t\tconst signals = [invocation.controller.signal];\n\t\tif (context.abortSignal !== undefined) signals.push(context.abortSignal);\n\t\tconst signal = AbortSignal.any(signals);\n\t\tfor (;;) {\n\t\t\tsignal.throwIfAborted();\n\t\t\tconst remaining = until - this.#now();\n\t\t\tif (remaining <= 0) return;\n\t\t\tawait delay(Math.min(remaining, MAX_TIMER_DELAY), signal);\n\t\t}\n\t}\n\n\tasync #watchDoc(invocation: Invocation, args: readonly unknown[]): Promise<DocumentWatch<JsonObject> | undefined> {\n\t\tif (invocation.ended) throw endedError(invocation);\n\t\tconst watch = (await sessionMethod(this.#session, \"watchDoc\")(...args)) as DocumentWatch<JsonObject> | undefined;\n\t\tif (watch === undefined) return undefined;\n\t\tif (invocation.ended) {\n\t\t\tvoid watch.stop();\n\t\t\tthrow endedError(invocation);\n\t\t}\n\t\tinvocation.watches.add(watch);\n\t\tvoid watch.closed.then(() => invocation.watches.delete(watch));\n\t\treturn watch;\n\t}\n}\n\n/** A live owner's durable cancellation intent: its abort mark, or a held outcome other than `completed`. */\nfunction cancellationIntent(record: AnyTaskRecord): boolean {\n\treturn record.state.status !== \"terminal\" && (record.abortRequested || failedOutcome(record));\n}\n\n/** Whether the record holds or ends with an outcome other than `completed`. */\nfunction failedOutcome(record: AnyTaskRecord): boolean {\n\tconst state = record.state;\n\treturn (state.status === \"completing\" || state.status === \"terminal\") && state.outcome.status !== \"completed\";\n}\n\nfunction parentOf(node: TaskNode): Up {\n\treturn node.owner !== undefined ? { task: node.owner } : { conversation: node.conversationId };\n}\n\nfunction nodeOf(record: AnyTaskRecord): TaskNode {\n\treturn {\n\t\tconversationId: record.conversationId,\n\t\t...(record.owner === undefined ? {} : { owner: record.owner }),\n\t\tbackground: record.background,\n\t};\n}\n\nfunction overlayOf(tx: Transaction): Overlay {\n\tconst tasks = new Map(tx.stagedTasks().map((record) => [record.id, record]));\n\tconst edges = new Map(tx.stagedConversations().map((record) => [record.id, record.owner?.taskId ?? null]));\n\treturn { tasks, edges };\n}\n\n/** Own memo entry only; memo names such as `toString` must not resolve to inherited properties. */\nfunction memoOf(record: AnyTaskRecord | undefined, name: string): JsonValue | undefined {\n\tconst memos = record?.memos;\n\treturn memos !== undefined && Object.hasOwn(memos, name) ? memos[name] : undefined;\n}\n\n/** Overloaded Session method bound for forwarding an argument list unchanged. */\nfunction sessionMethod(\n\tsession: SessionImpl,\n\tname: \"snapshot\" | \"snapshotAsOf\" | \"watchDoc\",\n): (...args: readonly unknown[]) => Promise<unknown> {\n\treturn (session[name] as (...args: readonly unknown[]) => Promise<unknown>).bind(session);\n}\n\nfunction missingMigration(record: AnyTaskRecord, definition: ErasedDefinition): Error {\n\treturn new Error(`Task ${record.kind} version ${definition.version} has no migration from ${record.version}`);\n}\n\nfunction erased(task: AnyTask): ErasedDefinition {\n\treturn task.definition as unknown as ErasedDefinition;\n}\n\nfunction endedError(invocation: Invocation): Error {\n\treturn new Error(`Task ${invocation.taskId} invocation has ended`);\n}\n\n/** Replace a live record's state; memos disappear once an outcome is decided. */\nfunction withState(record: AnyTaskRecord, state: TaskState<JsonValue, JsonValue>): AnyTaskRecord {\n\tif (state.status !== \"terminal\" && state.status !== \"completing\") return { ...record, state } as AnyTaskRecord;\n\tconst { memos: _memos, ...rest } = record;\n\treturn { ...rest, state };\n}\n\n/** Whether a definition can take the task at reservation: same version, or newer with a migration. */\nfunction canReserve(task: AnyTask, record: AnyTaskRecord): boolean {\n\tconst definition = task.definition;\n\treturn (\n\t\tdefinition.version === record.version || (definition.version > record.version && definition.migrate !== undefined)\n\t);\n}\n\nfunction delay(ms: number, signal: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst onAbort = (): void => {\n\t\t\tclearTimeout(timer);\n\t\t\treject(signal.reason);\n\t\t};\n\t\tconst timer = setTimeout(() => {\n\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\tresolve();\n\t\t}, ms);\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t});\n}\n\n/** Structural equality of two JSON values; object key order is ignored. */\nfunction jsonEqual(left: JsonValue | undefined, right: JsonValue | undefined): boolean {\n\tif (left === right) return true;\n\tif (typeof left !== \"object\" || typeof right !== \"object\" || left === null || right === null) return false;\n\tif (Array.isArray(left) || Array.isArray(right)) {\n\t\tif (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) return false;\n\t\treturn left.every((value, index) => jsonEqual(value, right[index]));\n\t}\n\tconst keys = Object.keys(left);\n\tif (keys.length !== Object.keys(right).length) return false;\n\treturn keys.every((key) => Object.hasOwn(right, key) && jsonEqual(left[key], right[key]));\n}\n"]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type Context } from "@earendil-works/chord";
|
|
2
2
|
import type { SessionImpl } from "../session/session.ts";
|
|
3
|
+
import type { Transaction } from "../session/transaction.ts";
|
|
3
4
|
import type { ConversationId, Storage, SubmissionId, SubmissionRecord } from "../types.ts";
|
|
4
5
|
import type { SettledSubmissionRecord, Submission, SubmissionDraft } from "./types.ts";
|
|
5
6
|
type AbortResult = "aborted" | "already_placed" | "settled";
|
|
@@ -7,18 +8,22 @@ type AbortResult = "aborted" | "already_placed" | "settled";
|
|
|
7
8
|
export declare class Submissions {
|
|
8
9
|
#private;
|
|
9
10
|
constructor(session: SessionImpl, storage: Storage, now: () => number, resume: () => void);
|
|
10
|
-
/**
|
|
11
|
-
* Admit a submission in one commit. A known request ID returns its existing submission without writing. Until the
|
|
12
|
-
* inbox exists, a busy conversation rejects with `ConversationBusy` and writes nothing. Idle input places a user
|
|
13
|
-
* entry and starts a generation run; an idle write appends its entry and settles `done`.
|
|
14
|
-
*/
|
|
11
|
+
/** Admit a submission in one commit; see `admitSubmission()`. */
|
|
15
12
|
submit(conversationId: ConversationId, draft: SubmissionDraft, context: Context): Promise<Submission>;
|
|
16
13
|
/** Handle for an existing submission, or `undefined`. */
|
|
17
14
|
get(id: SubmissionId, context: Context): Promise<Submission | undefined>;
|
|
18
15
|
status(id: SubmissionId, context: Context): Promise<SubmissionRecord>;
|
|
19
16
|
wait(id: SubmissionId, context: Context): Promise<SettledSubmissionRecord>;
|
|
20
|
-
/** Withdraw a queued submission; placed inputs and settled submissions are reported
|
|
17
|
+
/** Withdraw a queued submission and remove its inbox item; placed inputs and settled submissions are reported. */
|
|
21
18
|
abort(id: SubmissionId, context: Context, conversationId?: ConversationId): Promise<AbortResult | "not_found">;
|
|
22
19
|
}
|
|
20
|
+
/**
|
|
21
|
+
* Admit a submission inside a commit (spec §6); `Conversation.submit()` and conversation-owned compactions share it. A
|
|
22
|
+
* known request ID returns its existing submission without writing. A busy conversation queues it in `pi.inbox`, or
|
|
23
|
+
* rejects `whenBusy: "reject"` input with `ConversationBusy`. An idle conversation with queued items queues it behind
|
|
24
|
+
* them and runs a final boundary. Otherwise idle input places a user entry and starts a run, and an idle write appends
|
|
25
|
+
* its entry and settles `done`, or `stale` when its head reaches before the active range.
|
|
26
|
+
*/
|
|
27
|
+
export declare function admitSubmission(tx: Transaction, conversationId: ConversationId, draft: SubmissionDraft, now: number): Promise<SubmissionId>;
|
|
23
28
|
export {};
|
|
24
29
|
//# sourceMappingURL=submissions.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"submissions.d.ts","sourceRoot":"","sources":["../../src/harness/submissions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"submissions.d.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D;AA8BD;;;;;;GAMG;AACH,wBAAsB,eAAe,CACpC,EAAE,EAAE,WAAW,EACf,cAAc,EAAE,cAAc,EAC9B,KAAK,EAAE,eAAe,EACtB,GAAG,EAAE,MAAM,GACT,OAAO,CAAC,YAAY,CAAC,CAqDvB"}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
|
+
import { copyJson } from "@earendil-works/chord";
|
|
1
2
|
import { UserEntry } from "../entries.js";
|
|
2
3
|
import { ConversationBusy } from "../errors.js";
|
|
3
|
-
import {
|
|
4
|
+
import { startRun } from "./generation.js";
|
|
5
|
+
import { applyBoundary, InboxDoc, isStale, prepareBoundary, removeInboxItem } from "./inbox.js";
|
|
4
6
|
import { LiveDoc } from "./live.js";
|
|
5
7
|
import { closedError, Waiters } from "./util.js";
|
|
6
8
|
/** Admission, waits, and withdrawal of the durable submissions of one Harness. */
|
|
@@ -23,39 +25,10 @@ export class Submissions {
|
|
|
23
25
|
this.#waiters.rejectAll(closedError());
|
|
24
26
|
});
|
|
25
27
|
}
|
|
26
|
-
/**
|
|
27
|
-
* Admit a submission in one commit. A known request ID returns its existing submission without writing. Until the
|
|
28
|
-
* inbox exists, a busy conversation rejects with `ConversationBusy` and writes nothing. Idle input places a user
|
|
29
|
-
* entry and starts a generation run; an idle write appends its entry and settles `done`.
|
|
30
|
-
*/
|
|
28
|
+
/** Admit a submission in one commit; see `admitSubmission()`. */
|
|
31
29
|
async submit(conversationId, draft, context) {
|
|
32
30
|
this.#resume();
|
|
33
|
-
const id = await this.#session.commitWith(
|
|
34
|
-
if (draft.requestId !== undefined) {
|
|
35
|
-
const existing = await tx.submissionByRequest(conversationId, draft.requestId);
|
|
36
|
-
if (existing !== undefined) {
|
|
37
|
-
if (existing.type !== draft.type) {
|
|
38
|
-
throw new Error(`Request ${draft.requestId} already identifies a submission of type ${existing.type}`);
|
|
39
|
-
}
|
|
40
|
-
return existing.id;
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
const live = await tx.doc(LiveDoc, conversationId);
|
|
44
|
-
if (live.run !== undefined)
|
|
45
|
-
throw new ConversationBusy(conversationId);
|
|
46
|
-
const requestId = draft.requestId === undefined ? {} : { requestId: draft.requestId };
|
|
47
|
-
if (draft.type === "write") {
|
|
48
|
-
const entry = await tx.appendEntry(conversationId, draft.entry);
|
|
49
|
-
const write = { conversationId, ...requestId, type: "write", status: "done", entry: entry.id };
|
|
50
|
-
return (await tx.createSubmission(write)).id;
|
|
51
|
-
}
|
|
52
|
-
const message = { role: "user", content: draft.content, timestamp: this.#now() };
|
|
53
|
-
const entry = await tx.appendEntry(UserEntry, conversationId, { model: [message] });
|
|
54
|
-
const input = { conversationId, ...requestId, type: "input", status: "placed", entry: entry.id };
|
|
55
|
-
const { id } = await tx.createSubmission(input);
|
|
56
|
-
live.run = { taskId: await tx.createTask(GenerationTask, {}, { conversationId }), inputs: [id] };
|
|
57
|
-
return id;
|
|
58
|
-
}, context);
|
|
31
|
+
const id = await this.#session.commitWith((tx) => admitSubmission(tx, conversationId, draft, this.#now()), context);
|
|
59
32
|
return new SubmissionHandle(id, this);
|
|
60
33
|
}
|
|
61
34
|
/** Handle for an existing submission, or `undefined`. */
|
|
@@ -85,7 +58,7 @@ export class Submissions {
|
|
|
85
58
|
});
|
|
86
59
|
return found.promise;
|
|
87
60
|
}
|
|
88
|
-
/** Withdraw a queued submission; placed inputs and settled submissions are reported
|
|
61
|
+
/** Withdraw a queued submission and remove its inbox item; placed inputs and settled submissions are reported. */
|
|
89
62
|
abort(id, context, conversationId) {
|
|
90
63
|
return this.#session.commitWith(async (tx) => {
|
|
91
64
|
const record = await tx.submission(id);
|
|
@@ -94,6 +67,7 @@ export class Submissions {
|
|
|
94
67
|
}
|
|
95
68
|
if (record.status === "queued") {
|
|
96
69
|
tx.settleSubmission(id, { status: "unanswered", reason: "aborted" });
|
|
70
|
+
await removeInboxItem(tx, record.conversationId, id);
|
|
97
71
|
return "aborted";
|
|
98
72
|
}
|
|
99
73
|
return record.status === "placed" ? "already_placed" : "settled";
|
|
@@ -130,4 +104,69 @@ class SubmissionHandle {
|
|
|
130
104
|
function isSettled(record) {
|
|
131
105
|
return record.status === "done" || record.status === "unanswered";
|
|
132
106
|
}
|
|
107
|
+
/**
|
|
108
|
+
* Admit a submission inside a commit (spec §6); `Conversation.submit()` and conversation-owned compactions share it. A
|
|
109
|
+
* known request ID returns its existing submission without writing. A busy conversation queues it in `pi.inbox`, or
|
|
110
|
+
* rejects `whenBusy: "reject"` input with `ConversationBusy`. An idle conversation with queued items queues it behind
|
|
111
|
+
* them and runs a final boundary. Otherwise idle input places a user entry and starts a run, and an idle write appends
|
|
112
|
+
* its entry and settles `done`, or `stale` when its head reaches before the active range.
|
|
113
|
+
*/
|
|
114
|
+
export async function admitSubmission(tx, conversationId, draft, now) {
|
|
115
|
+
if (draft.requestId !== undefined) {
|
|
116
|
+
const existing = await tx.submissionByRequest(conversationId, draft.requestId);
|
|
117
|
+
if (existing !== undefined) {
|
|
118
|
+
if (existing.type !== draft.type) {
|
|
119
|
+
throw new Error(`Request ${draft.requestId} already identifies a submission of type ${existing.type}`);
|
|
120
|
+
}
|
|
121
|
+
return existing.id;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
const live = await tx.doc(LiveDoc, conversationId);
|
|
125
|
+
const busy = live.run !== undefined;
|
|
126
|
+
if (busy && draft.type === "input" && draft.whenBusy === "reject")
|
|
127
|
+
throw new ConversationBusy(conversationId);
|
|
128
|
+
const requestId = draft.requestId === undefined ? {} : { requestId: draft.requestId };
|
|
129
|
+
// A boundary reads the table, so it is prepared before the first table write; a busy one needs none.
|
|
130
|
+
const boundary = busy ? undefined : await prepareBoundary(tx, conversationId);
|
|
131
|
+
if (boundary === undefined || boundary.inbox.items.length > 0) {
|
|
132
|
+
const { id } = await tx.createSubmission({
|
|
133
|
+
conversationId,
|
|
134
|
+
...requestId,
|
|
135
|
+
type: draft.type,
|
|
136
|
+
status: "queued",
|
|
137
|
+
});
|
|
138
|
+
// Hosts may leave optional fields `undefined`; drafts take strict JSON.
|
|
139
|
+
const value = copyJson(draft.type === "write" ? draft.entry : draft.content, {
|
|
140
|
+
omitUndefinedProperties: true,
|
|
141
|
+
});
|
|
142
|
+
const items = (boundary?.inbox ?? (await tx.doc(InboxDoc, conversationId))).items;
|
|
143
|
+
if (draft.type === "write")
|
|
144
|
+
items.push({ id, mode: "write", entry: value });
|
|
145
|
+
else {
|
|
146
|
+
const mode = draft.whenBusy === "steer" ? "steer" : "followUp";
|
|
147
|
+
items.push({ id, mode, content: value });
|
|
148
|
+
}
|
|
149
|
+
if (boundary === undefined)
|
|
150
|
+
return id;
|
|
151
|
+
const { users } = await applyBoundary(tx, boundary, "final", now);
|
|
152
|
+
if (users.length > 0)
|
|
153
|
+
await startRun(tx, conversationId, live, users);
|
|
154
|
+
return id;
|
|
155
|
+
}
|
|
156
|
+
if (draft.type === "write") {
|
|
157
|
+
if (isStale(boundary, draft.entry)) {
|
|
158
|
+
const stale = { status: "unanswered", reason: "stale" };
|
|
159
|
+
return (await tx.createSubmission({ conversationId, ...requestId, type: "write", ...stale })).id;
|
|
160
|
+
}
|
|
161
|
+
const entry = await tx.appendEntry(conversationId, draft.entry);
|
|
162
|
+
const write = { conversationId, ...requestId, type: "write", status: "done", entry: entry.id };
|
|
163
|
+
return (await tx.createSubmission(write)).id;
|
|
164
|
+
}
|
|
165
|
+
const message = { role: "user", content: draft.content, timestamp: now };
|
|
166
|
+
const entry = await tx.appendEntry(UserEntry, conversationId, { model: [message] });
|
|
167
|
+
const input = { conversationId, ...requestId, type: "input", status: "placed", entry: entry.id };
|
|
168
|
+
const { id } = await tx.createSubmission(input);
|
|
169
|
+
await startRun(tx, conversationId, live, [id]);
|
|
170
|
+
return id;
|
|
171
|
+
}
|
|
133
172
|
//# sourceMappingURL=submissions.js.map
|