Skip to content

Runtime reference

Durable PostgreSQL runtime state and S3 artifact storage.

(c) Mike Casale 2025. Licensed under the MIT License.

WireModel

Bases: BaseModel

Base model for strict, camel-case worker API payloads.

Source code in agent_k/stores.py
85
86
87
88
89
90
91
92
93
class WireModel(BaseModel):
    """Base model for strict, camel-case worker API payloads."""

    model_config = ConfigDict(
        alias_generator=to_camel,
        extra="forbid",
        populate_by_name=True,
        validate_default=True,
    )

JobStatus

Bases: StrEnum

Durable runtime job states.

Source code in agent_k/stores.py
 96
 97
 98
 99
100
101
102
103
104
105
class JobStatus(StrEnum):
    """Durable runtime job states."""

    QUEUED = "queued"
    LEASED = "leased"
    RUNNING = "running"
    PAUSED = "paused"
    COMPLETED = "completed"
    FAILED = "failed"
    CANCELED = "canceled"

ControlAction

Bases: StrEnum

Control actions returned to a leased worker.

Source code in agent_k/stores.py
108
109
110
111
112
113
class ControlAction(StrEnum):
    """Control actions returned to a leased worker."""

    CONTINUE = "continue"
    PAUSE = "pause"
    CANCEL = "cancel"

JobCommandType

Bases: StrEnum

Mission commands accepted by a worker.

Source code in agent_k/stores.py
116
117
118
119
120
class JobCommandType(StrEnum):
    """Mission commands accepted by a worker."""

    START = "start"
    RESUME = "resume"

MigrationSourceKind

Bases: StrEnum

Supported legacy import source families.

Source code in agent_k/stores.py
123
124
125
126
127
class MigrationSourceKind(StrEnum):
    """Supported legacy import source families."""

    MISSION_STATE = "mission-state"
    EXPERIMENT_DB = "experiment-db"

MigrationStatus

Bases: StrEnum

Durable migration processing states.

Source code in agent_k/stores.py
130
131
132
133
134
135
136
137
class MigrationStatus(StrEnum):
    """Durable migration processing states."""

    AWAITING_UPLOAD = "awaiting-upload"
    QUEUED = "queued"
    RUNNING = "running"
    COMPLETED = "completed"
    FAILED = "failed"

JobCommand

Bases: WireModel

Command and resume information for a mission lease.

Source code in agent_k/stores.py
140
141
142
143
144
145
146
class JobCommand(WireModel):
    """Command and resume information for a mission lease."""

    type: JobCommandType
    competition_id: str | None = Field(default=None, min_length=1, max_length=255)
    criteria: dict[str, Any] = Field(default_factory=dict)
    checkpoint_id: uuid.UUID | None = None

JobWorkspace

Bases: WireModel

Artifact namespace assigned to one job.

Source code in agent_k/stores.py
149
150
151
152
153
154
155
156
157
158
159
160
161
class JobWorkspace(WireModel):
    """Artifact namespace assigned to one job."""

    artifact_prefix: str = Field(min_length=1, max_length=768)

    @field_validator("artifact_prefix")
    @classmethod
    def validate_artifact_prefix(cls, value: str) -> str:
        """Reject absolute and traversing S3 key prefixes."""
        path = PurePosixPath(value)
        if path.is_absolute() or ".." in path.parts:
            raise ValueError("artifactPrefix must be a relative, non-traversing key")
        return value.strip("/")

validate_artifact_prefix classmethod

validate_artifact_prefix(value: str) -> str

Reject absolute and traversing S3 key prefixes.

Source code in agent_k/stores.py
154
155
156
157
158
159
160
161
@field_validator("artifact_prefix")
@classmethod
def validate_artifact_prefix(cls, value: str) -> str:
    """Reject absolute and traversing S3 key prefixes."""
    path = PurePosixPath(value)
    if path.is_absolute() or ".." in path.parts:
        raise ValueError("artifactPrefix must be a relative, non-traversing key")
    return value.strip("/")

JobLease

Bases: WireModel

Fenced lease returned by the runtime queue.

Source code in agent_k/stores.py
164
165
166
167
168
169
170
171
172
173
174
175
class JobLease(WireModel):
    """Fenced lease returned by the runtime queue."""

    schema_version: str = SCHEMA_VERSION
    job_id: uuid.UUID
    mission_id: uuid.UUID
    attempt: int = Field(ge=1)
    lease_id: uuid.UUID = Field(repr=False)
    lease_expires_at: AwareDatetime
    command: JobCommand
    workspace: JobWorkspace
    event_sequence: int = Field(default=0, ge=0)

ClaimJobsRequest

Bases: WireModel

Atomic worker claim request.

Source code in agent_k/stores.py
178
179
180
181
182
183
184
class ClaimJobsRequest(WireModel):
    """Atomic worker claim request."""

    worker_id: str = Field(min_length=1, max_length=255)
    capabilities: tuple[str, ...] = ()
    lease_seconds: int = Field(default=60, ge=15, le=3600)
    max_jobs: int = Field(default=1, ge=1, le=16)

ClaimJobsResponse

Bases: WireModel

Leases returned to a worker poll.

Source code in agent_k/stores.py
187
188
189
190
191
class ClaimJobsResponse(WireModel):
    """Leases returned to a worker poll."""

    jobs: tuple[JobLease, ...] = ()
    server_time: AwareDatetime

ControlDirective

Bases: WireModel

Current server-side control directive.

Source code in agent_k/stores.py
194
195
196
197
198
199
200
class ControlDirective(WireModel):
    """Current server-side control directive."""

    action: ControlAction = ControlAction.CONTINUE
    reason: str | None = Field(default=None, max_length=2000)
    requested_at: AwareDatetime | None = None
    server_time: AwareDatetime | None = None

HeartbeatRequest

Bases: WireModel

Lease renewal and progress update.

Source code in agent_k/stores.py
203
204
205
206
207
208
209
210
class HeartbeatRequest(WireModel):
    """Lease renewal and progress update."""

    worker_id: str = Field(min_length=1, max_length=255)
    lease_id: uuid.UUID = Field(repr=False)
    progress: float | None = Field(default=None, ge=0, le=100)
    current_phase: str | None = Field(default=None, max_length=100)
    current_task_id: str | None = Field(default=None, max_length=255)

HeartbeatResponse

Bases: WireModel

Renewed lease and current control directive.

Source code in agent_k/stores.py
213
214
215
216
217
218
219
220
class HeartbeatResponse(WireModel):
    """Renewed lease and current control directive."""

    job_id: uuid.UUID
    lease_id: uuid.UUID = Field(repr=False)
    lease_expires_at: AwareDatetime
    control: ControlDirective
    server_time: AwareDatetime

WorkerEvent

Bases: WireModel

One durable mission event emitted by a worker.

Source code in agent_k/stores.py
223
224
225
226
227
228
229
230
class WorkerEvent(WireModel):
    """One durable mission event emitted by a worker."""

    event_id: uuid.UUID
    sequence: int = Field(ge=1)
    type: str = Field(min_length=1, max_length=100)
    timestamp: AwareDatetime
    data: JsonValue = Field(default_factory=dict)

AppendEventsRequest

Bases: WireModel

Ordered, idempotent event append request.

Source code in agent_k/stores.py
233
234
235
236
237
238
239
240
241
242
243
244
245
246
class AppendEventsRequest(WireModel):
    """Ordered, idempotent event append request."""

    worker_id: str = Field(min_length=1, max_length=255)
    lease_id: uuid.UUID = Field(repr=False)
    events: tuple[WorkerEvent, ...] = Field(min_length=1, max_length=256)

    @model_validator(mode="after")
    def validate_order(self) -> AppendEventsRequest:
        """Require strictly increasing event sequences within a batch."""
        sequences = [event.sequence for event in self.events]
        if sequences != sorted(set(sequences)):
            raise ValueError("events must have unique, increasing sequences")
        return self

validate_order

validate_order() -> AppendEventsRequest

Require strictly increasing event sequences within a batch.

Source code in agent_k/stores.py
240
241
242
243
244
245
246
@model_validator(mode="after")
def validate_order(self) -> AppendEventsRequest:
    """Require strictly increasing event sequences within a batch."""
    sequences = [event.sequence for event in self.events]
    if sequences != sorted(set(sequences)):
        raise ValueError("events must have unique, increasing sequences")
    return self

AppendEventsReceipt

Bases: WireModel

Acknowledgement for a durable event batch.

Source code in agent_k/stores.py
249
250
251
252
253
254
class AppendEventsReceipt(WireModel):
    """Acknowledgement for a durable event batch."""

    accepted_through: int = Field(ge=0)
    duplicate_sequences: tuple[int, ...] = ()
    control: ControlDirective

EventRecord

Bases: WorkerEvent

Persisted event with a durable replay cursor.

Source code in agent_k/stores.py
257
258
259
260
261
262
class EventRecord(WorkerEvent):
    """Persisted event with a durable replay cursor."""

    stream_sequence: int = Field(ge=1)
    mission_id: uuid.UUID
    job_id: uuid.UUID

MissionSnapshot

Bases: WireModel

Immutable graph snapshot uploaded by a worker.

Source code in agent_k/stores.py
265
266
267
268
269
270
271
272
class MissionSnapshot(WireModel):
    """Immutable graph snapshot uploaded by a worker."""

    schema_version: str = STATE_SCHEMA_VERSION
    sequence: int = Field(ge=0)
    created_at: AwareDatetime
    content_type: Literal["application/json"] = "application/json"
    payload: dict[str, Any]

SnapshotReceipt

Bases: WireModel

Receipt for an idempotently stored snapshot.

Source code in agent_k/stores.py
275
276
277
278
279
280
class SnapshotReceipt(WireModel):
    """Receipt for an idempotently stored snapshot."""

    snapshot_id: uuid.UUID
    sequence: int = Field(ge=0)
    created_at: AwareDatetime

ArtifactReference

Bases: WireModel

Reference to an immutable uploaded artifact.

Source code in agent_k/stores.py
283
284
285
286
287
class ArtifactReference(WireModel):
    """Reference to an immutable uploaded artifact."""

    artifact_id: uuid.UUID
    role: str = Field(min_length=1, max_length=100)

MissionSnapshotRecord

Bases: MissionSnapshot

Fenced snapshot payload and its immutable workspace artifacts.

Source code in agent_k/stores.py
290
291
292
293
294
295
296
class MissionSnapshotRecord(MissionSnapshot):
    """Fenced snapshot payload and its immutable workspace artifacts."""

    snapshot_id: uuid.UUID
    job_id: uuid.UUID
    mission_id: uuid.UUID
    artifacts: tuple[ArtifactReference, ...] = ()

ArtifactUploadSpec

Bases: WireModel

Metadata required before signing an artifact upload.

Source code in agent_k/stores.py
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
class ArtifactUploadSpec(WireModel):
    """Metadata required before signing an artifact upload."""

    worker_id: str = Field(min_length=1, max_length=255)
    lease_id: uuid.UUID = Field(repr=False)
    name: str = Field(min_length=1, max_length=255)
    content_type: str = Field(min_length=1, max_length=255)
    size_bytes: int = Field(ge=0)
    sha256: str
    role: str = Field(min_length=1, max_length=100)

    @field_validator("name")
    @classmethod
    def validate_name(cls, value: str) -> str:
        """Accept only portable artifact basenames."""
        if not SAFE_ARTIFACT_NAME.fullmatch(value):
            raise ValueError("name must be a portable artifact basename")
        return value

    @field_validator("sha256")
    @classmethod
    def validate_sha256(cls, value: str) -> str:
        """Require a lowercase SHA-256 digest."""
        if not SHA256_PATTERN.fullmatch(value):
            raise ValueError("sha256 must be a lowercase hexadecimal digest")
        return value

validate_name classmethod

validate_name(value: str) -> str

Accept only portable artifact basenames.

Source code in agent_k/stores.py
310
311
312
313
314
315
316
@field_validator("name")
@classmethod
def validate_name(cls, value: str) -> str:
    """Accept only portable artifact basenames."""
    if not SAFE_ARTIFACT_NAME.fullmatch(value):
        raise ValueError("name must be a portable artifact basename")
    return value

validate_sha256 classmethod

validate_sha256(value: str) -> str

Require a lowercase SHA-256 digest.

Source code in agent_k/stores.py
318
319
320
321
322
323
324
@field_validator("sha256")
@classmethod
def validate_sha256(cls, value: str) -> str:
    """Require a lowercase SHA-256 digest."""
    if not SHA256_PATTERN.fullmatch(value):
        raise ValueError("sha256 must be a lowercase hexadecimal digest")
    return value

ArtifactCompleteSpec

Bases: WireModel

Worker identity and immutable metadata for an uploaded artifact.

Source code in agent_k/stores.py
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
class ArtifactCompleteSpec(WireModel):
    """Worker identity and immutable metadata for an uploaded artifact."""

    worker_id: str = Field(min_length=1, max_length=255)
    lease_id: uuid.UUID = Field(repr=False)
    sha256: str
    size_bytes: int = Field(ge=0)

    @field_validator("sha256")
    @classmethod
    def validate_sha256(cls, value: str) -> str:
        """Require a lowercase SHA-256 digest."""
        if not SHA256_PATTERN.fullmatch(value):
            raise ValueError("sha256 must be a lowercase hexadecimal digest")
        return value

validate_sha256 classmethod

validate_sha256(value: str) -> str

Require a lowercase SHA-256 digest.

Source code in agent_k/stores.py
335
336
337
338
339
340
341
@field_validator("sha256")
@classmethod
def validate_sha256(cls, value: str) -> str:
    """Require a lowercase SHA-256 digest."""
    if not SHA256_PATTERN.fullmatch(value):
        raise ValueError("sha256 must be a lowercase hexadecimal digest")
    return value

ArtifactCompleteResponse

Bases: WireModel

Server-verified artifact completion receipt.

Source code in agent_k/stores.py
344
345
346
347
348
349
class ArtifactCompleteResponse(WireModel):
    """Server-verified artifact completion receipt."""

    artifact_id: uuid.UUID
    status: Literal["available"] = "available"
    verified_at: AwareDatetime

SignedArtifactURL

Bases: WireModel

Short-lived job-scoped S3 operation.

Source code in agent_k/stores.py
352
353
354
355
356
357
358
359
class SignedArtifactURL(WireModel):
    """Short-lived job-scoped S3 operation."""

    artifact_id: uuid.UUID
    method: Literal["GET", "PUT"]
    url: str = Field(min_length=1, repr=False)
    headers: dict[str, str] = Field(default_factory=dict)
    expires_at: AwareDatetime

MissionRunResult

Bases: WireModel

Successful mission result returned by the isolated mission process.

Source code in agent_k/stores.py
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
class MissionRunResult(WireModel):
    """Successful mission result returned by the isolated mission process."""

    schema_version: str = SCHEMA_VERSION
    success: Literal[True] = True
    mission_id: uuid.UUID
    competition_id: str | None = Field(default=None, min_length=1, max_length=255)
    final_rank: int | None = Field(default=None, ge=1)
    final_score: float | None = None
    total_submissions: int = Field(default=0, ge=0)
    evolution_generations: int = Field(default=0, ge=0)
    evolution_iterations: int = Field(default=0, ge=0)
    duration_ms: int = Field(default=0, ge=0)
    phases_completed: tuple[str, ...] = ()
    final_event_sequence: int = Field(default=0, ge=0)
    artifacts: tuple[ArtifactReference, ...] = ()

JobCompletionRequest

Bases: WireModel

Idempotent completion mutation for a fenced job.

Source code in agent_k/stores.py
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
class JobCompletionRequest(WireModel):
    """Idempotent completion mutation for a fenced job."""

    worker_id: str = Field(min_length=1, max_length=255)
    lease_id: uuid.UUID = Field(repr=False)
    idempotency_key: str = Field(min_length=16, max_length=255)
    result: MissionRunResult
    final_event_sequence: int = Field(ge=0)
    artifacts: tuple[ArtifactReference, ...] = ()

    @model_validator(mode="after")
    def validate_result_envelope(self) -> JobCompletionRequest:
        """Require duplicated terminal metadata to match the signed result body."""
        if self.final_event_sequence != self.result.final_event_sequence:
            raise ValueError("finalEventSequence must match result.finalEventSequence")
        if self.artifacts != self.result.artifacts:
            raise ValueError("artifacts must match result.artifacts")
        return self

validate_result_envelope

validate_result_envelope() -> JobCompletionRequest

Require duplicated terminal metadata to match the signed result body.

Source code in agent_k/stores.py
390
391
392
393
394
395
396
397
@model_validator(mode="after")
def validate_result_envelope(self) -> JobCompletionRequest:
    """Require duplicated terminal metadata to match the signed result body."""
    if self.final_event_sequence != self.result.final_event_sequence:
        raise ValueError("finalEventSequence must match result.finalEventSequence")
    if self.artifacts != self.result.artifacts:
        raise ValueError("artifacts must match result.artifacts")
    return self

JobCompletionResponse

Bases: WireModel

Durable job completion receipt.

Source code in agent_k/stores.py
400
401
402
403
404
405
406
class JobCompletionResponse(WireModel):
    """Durable job completion receipt."""

    job_id: uuid.UUID
    mission_id: uuid.UUID
    status: Literal["completed"] = "completed"
    completed_at: AwareDatetime

JobFailure

Bases: WireModel

Structured failure safe for storage and transport.

Source code in agent_k/stores.py
409
410
411
412
413
414
415
416
class JobFailure(WireModel):
    """Structured failure safe for storage and transport."""

    code: str = Field(min_length=1, max_length=100)
    message: str = Field(min_length=1, max_length=4000)
    retryable: bool
    category: str | None = Field(default=None, max_length=100)
    details: dict[str, Any] | None = None

JobFailureRequest

Bases: WireModel

Idempotent failure mutation for a fenced job.

Source code in agent_k/stores.py
419
420
421
422
423
424
425
426
class JobFailureRequest(WireModel):
    """Idempotent failure mutation for a fenced job."""

    worker_id: str = Field(min_length=1, max_length=255)
    lease_id: uuid.UUID = Field(repr=False)
    idempotency_key: str = Field(min_length=16, max_length=255)
    error: JobFailure
    final_event_sequence: int = Field(ge=0)

JobFailureResponse

Bases: WireModel

Failure receipt indicating whether another attempt is queued.

Source code in agent_k/stores.py
429
430
431
432
433
434
435
436
437
class JobFailureResponse(WireModel):
    """Failure receipt indicating whether another attempt is queued."""

    job_id: uuid.UUID
    mission_id: uuid.UUID
    status: Literal["failed", "queued"]
    attempt: int = Field(ge=1)
    next_attempt_at: AwareDatetime | None = None
    failed_at: AwareDatetime | None = None

JobEnqueueRequest

Bases: WireModel

Idempotent job creation request used by the API.

Source code in agent_k/stores.py
440
441
442
443
444
445
446
447
448
449
450
451
class JobEnqueueRequest(WireModel):
    """Idempotent job creation request used by the API."""

    job_id: uuid.UUID = Field(default_factory=uuid.uuid4)
    mission_id: uuid.UUID
    command: JobCommand
    workspace: JobWorkspace
    requirements: tuple[str, ...] = ()
    idempotency_key: str = Field(min_length=16, max_length=255)
    priority: int = Field(default=0, ge=-1000, le=1000)
    max_attempts: int = Field(default=3, ge=1, le=20)
    available_at: AwareDatetime = Field(default_factory=lambda: datetime.now(UTC))

MissionRecord

Bases: WireModel

Persisted mission state returned by the runtime store.

Source code in agent_k/stores.py
454
455
456
457
458
459
460
461
462
463
464
class MissionRecord(WireModel):
    """Persisted mission state returned by the runtime store."""

    mission_id: uuid.UUID
    owner_id: str
    schema_version: str
    status: str
    state: dict[str, Any]
    requested_control: ControlAction
    created_at: AwareDatetime
    updated_at: AwareDatetime

MigrationSource

Bases: WireModel

Immutable legacy source metadata.

Source code in agent_k/stores.py
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
class MigrationSource(WireModel):
    """Immutable legacy source metadata."""

    kind: MigrationSourceKind
    schema_version: str = Field(min_length=1, max_length=64)
    sha256: str
    size_bytes: int = Field(ge=0)

    @field_validator("sha256")
    @classmethod
    def validate_sha256(cls, value: str) -> str:
        """Require a lowercase SHA-256 digest."""
        if not SHA256_PATTERN.fullmatch(value):
            raise ValueError("sha256 must be a lowercase hexadecimal digest")
        return value

validate_sha256 classmethod

validate_sha256(value: str) -> str

Require a lowercase SHA-256 digest.

Source code in agent_k/stores.py
475
476
477
478
479
480
481
@field_validator("sha256")
@classmethod
def validate_sha256(cls, value: str) -> str:
    """Require a lowercase SHA-256 digest."""
    if not SHA256_PATTERN.fullmatch(value):
        raise ValueError("sha256 must be a lowercase hexadecimal digest")
    return value

MigrationCreateRequest

Bases: WireModel

Request a signed upload for a legacy source.

Source code in agent_k/stores.py
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
class MigrationCreateRequest(WireModel):
    """Request a signed upload for a legacy source."""

    worker_id: str = Field(min_length=1, max_length=255)
    idempotency_key: str = Field(min_length=16, max_length=255)
    source: MigrationSource
    content_type: Literal["application/json", "application/x-sqlite3"]

    @model_validator(mode="after")
    def validate_content_type(self) -> MigrationCreateRequest:
        """Match the content type to the legacy source family."""
        expected = {
            MigrationSourceKind.MISSION_STATE: "application/json",
            MigrationSourceKind.EXPERIMENT_DB: "application/x-sqlite3",
        }[self.source.kind]
        if self.content_type != expected:
            raise ValueError(f"contentType must be {expected!r} for {self.source.kind}")
        return self

validate_content_type

validate_content_type() -> MigrationCreateRequest

Match the content type to the legacy source family.

Source code in agent_k/stores.py
492
493
494
495
496
497
498
499
500
501
@model_validator(mode="after")
def validate_content_type(self) -> MigrationCreateRequest:
    """Match the content type to the legacy source family."""
    expected = {
        MigrationSourceKind.MISSION_STATE: "application/json",
        MigrationSourceKind.EXPERIMENT_DB: "application/x-sqlite3",
    }[self.source.kind]
    if self.content_type != expected:
        raise ValueError(f"contentType must be {expected!r} for {self.source.kind}")
    return self

MigrationCreateResponse

Bases: WireModel

Signed migration upload and durable identifier.

Source code in agent_k/stores.py
504
505
506
507
508
509
class MigrationCreateResponse(WireModel):
    """Signed migration upload and durable identifier."""

    migration_id: uuid.UUID
    upload: SignedArtifactURL
    status: Literal["awaiting-upload"] = "awaiting-upload"

MigrationRecord

Bases: WireModel

Current status of a legacy source import.

Source code in agent_k/stores.py
512
513
514
515
516
517
518
class MigrationRecord(WireModel):
    """Current status of a legacy source import."""

    migration_id: uuid.UUID
    status: MigrationStatus
    counts: dict[str, int] | None = None
    error: JobFailure | None = None

APIError

Bases: WireModel

Stable worker API error body.

Source code in agent_k/stores.py
521
522
523
524
525
526
527
class APIError(WireModel):
    """Stable worker API error body."""

    code: str
    message: str
    retryable: bool
    details: dict[str, Any] | None = None

APIErrorEnvelope

Bases: WireModel

Stable worker API error envelope.

Source code in agent_k/stores.py
530
531
532
533
534
class APIErrorEnvelope(WireModel):
    """Stable worker API error envelope."""

    error: APIError
    request_id: str

RuntimeStoreError

Bases: RuntimeError

Base error raised by runtime persistence.

Source code in agent_k/stores.py
537
538
539
540
541
class RuntimeStoreError(RuntimeError):
    """Base error raised by runtime persistence."""

    code = "runtime_store_error"
    retryable = False

MissionInterrupted

Bases: RuntimeError

Signal a durably checkpointed pause or cancellation to the worker.

Source code in agent_k/stores.py
544
545
546
547
548
549
550
551
552
553
554
555
556
557
class MissionInterrupted(RuntimeError):
    """Signal a durably checkpointed pause or cancellation to the worker."""

    def __init__(
        self,
        action: Literal["pause", "cancel"],
        reason: str | None = None,
        *,
        final_event_sequence: int,
    ) -> None:
        super().__init__(reason or action)
        self.action = action
        self.reason = reason
        self.final_event_sequence = final_event_sequence

StoreConflictError

Bases: RuntimeStoreError

A durable idempotency or sequence invariant was violated.

Source code in agent_k/stores.py
560
561
562
563
564
565
566
567
class StoreConflictError(RuntimeStoreError):
    """A durable idempotency or sequence invariant was violated."""

    code = "store_conflict"

    def __init__(self, message: str, *, details: dict[str, Any] | None = None) -> None:
        super().__init__(message)
        self.details = details

LeaseFenceError

Bases: StoreConflictError

A stale or expired lease attempted a mutation.

Source code in agent_k/stores.py
570
571
572
573
class LeaseFenceError(StoreConflictError):
    """A stale or expired lease attempted a mutation."""

    code = "stale_lease"

PostgresRuntimeStore

Async PostgreSQL store for mission state, queue leases, and events.

Source code in agent_k/stores.py
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
class PostgresRuntimeStore:
    """Async PostgreSQL store for mission state, queue leases, and events."""

    def __init__(
        self,
        database_url: str,
        *,
        migrations_dir: Path | None = None,
        min_pool_size: int = 1,
        max_pool_size: int = 10,
    ) -> None:
        if not database_url.startswith(("postgresql://", "postgresql+psycopg://")):
            raise ValueError("database_url must be a PostgreSQL URL")
        self._database_url = database_url.replace("postgresql+psycopg://", "postgresql://", 1)
        self._migrations_dir = migrations_dir
        self._min_pool_size = min_pool_size
        self._max_pool_size = max_pool_size
        self._pool: Any = None
        self._dict_row: Any = None

    async def __aenter__(self) -> PostgresRuntimeStore:
        await self.open()
        return self

    async def __aexit__(self, *_args: object) -> None:
        await self.close()

    async def open(self) -> None:
        """Open and validate the PostgreSQL connection pool."""
        if self._pool is not None:
            return
        try:
            from psycopg.rows import dict_row
            from psycopg_pool import AsyncConnectionPool
        except ImportError as error:
            raise RuntimeError("PostgreSQL support requires `psycopg[binary,pool]`.") from error
        self._dict_row = dict_row
        self._pool = AsyncConnectionPool(
            self._database_url,
            min_size=self._min_pool_size,
            max_size=self._max_pool_size,
            open=False,
            kwargs={"row_factory": dict_row},
        )
        await self._pool.open()
        await self._pool.wait()

    async def close(self) -> None:
        """Close the PostgreSQL connection pool."""
        if self._pool is None:
            return
        pool = self._pool
        self._pool = None
        await pool.close()

    async def initialize(self) -> None:
        """Apply checksum-protected SQL migrations in filename order."""
        pool = self._require_pool()
        migration_paths: list[Any]
        if self._migrations_dir is None:
            resource_root = files("agent_k").joinpath("resources")
            migration_paths = sorted(
                (
                    resource
                    for resource in resource_root.iterdir()
                    if re.fullmatch(r"[0-9]{4}_.+\.sql", resource.name)
                ),
                key=lambda resource: resource.name,
            )
            location = "agent_k/resources"
        else:
            migration_paths = sorted(self._migrations_dir.glob("[0-9][0-9][0-9][0-9]_*.sql"))
            location = str(self._migrations_dir)
        if not migration_paths:
            raise RuntimeStoreError(f"No SQL migrations found in {location}")
        async with pool.connection() as connection:
            await connection.execute(
                "SELECT pg_advisory_lock(hashtext('agent-k-runtime-migrations'))"
            )
            try:
                await connection.execute(
                    """
                    CREATE TABLE IF NOT EXISTS runtime_schema_migrations (
                        version TEXT PRIMARY KEY,
                        sha256 TEXT NOT NULL,
                        applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
                    )
                    """
                )
                for migration_path in migration_paths:
                    sql = migration_path.read_text(encoding="utf-8")
                    digest = hashlib.sha256(sql.encode()).hexdigest()
                    row = await (
                        await connection.execute(
                            "SELECT sha256 FROM runtime_schema_migrations WHERE version = %s",
                            (migration_path.name,),
                        )
                    ).fetchone()
                    if row is not None:
                        if row["sha256"] != digest:
                            raise StoreConflictError(
                                f"Applied migration changed: {migration_path.name}",
                            )
                        continue
                    async with connection.transaction():
                        await connection.execute(sql, prepare=False)
                        await connection.execute(
                            """
                            INSERT INTO runtime_schema_migrations (version, sha256)
                            VALUES (%s, %s)
                            """,
                            (migration_path.name, digest),
                        )
            finally:
                await connection.execute(
                    "SELECT pg_advisory_unlock(hashtext('agent-k-runtime-migrations'))"
                )

    async def create_mission(
        self,
        mission_id: uuid.UUID,
        owner_id: str,
        *,
        state: dict[str, Any] | None = None,
        schema_version: str = STATE_SCHEMA_VERSION,
    ) -> MissionRecord:
        """Create a mission idempotently and return its durable state."""
        pool = self._require_pool()
        payload = state or {}
        state_sha256 = _canonical_sha256(payload)
        async with pool.connection() as connection:
            await connection.execute(
                """
                INSERT INTO runtime_missions (
                    mission_id, owner_id, schema_version, state, state_sha256
                ) VALUES (%s, %s, %s, %s::jsonb, %s)
                ON CONFLICT (mission_id) DO NOTHING
                """,
                (mission_id, owner_id, schema_version, _json(payload), state_sha256),
            )
            row = await self._fetch_mission(connection, mission_id)
        if row["owner_id"] != owner_id:
            raise StoreConflictError("missionId is already owned by another principal")
        return _mission_record(row)

    async def get_mission(self, mission_id: uuid.UUID) -> MissionRecord | None:
        """Return one mission or ``None`` when it does not exist."""
        pool = self._require_pool()
        async with pool.connection() as connection:
            row = await (
                await connection.execute(
                    "SELECT * FROM runtime_missions WHERE mission_id = %s",
                    (mission_id,),
                )
            ).fetchone()
            if row is not None:
                await self._decorate_mission_row(connection, row)
        return _mission_record(row) if row is not None else None

    async def require_owner(self, mission_id: uuid.UUID, owner_id: str) -> MissionRecord:
        """Return a mission only when the caller owns it."""
        mission = await self.get_mission(mission_id)
        if mission is None:
            raise KeyError(str(mission_id))
        if mission.owner_id != owner_id:
            raise PermissionError("mission owner does not match")
        return mission

    async def request_control(
        self,
        mission_id: uuid.UUID,
        action: ControlAction,
        *,
        reason: str | None = None,
    ) -> ControlDirective:
        """Persist a pause, cancel, or continue directive for a mission."""
        pool = self._require_pool()
        requested_at = datetime.now(UTC)
        async with pool.connection() as connection, connection.transaction():
            row = await (
                await connection.execute(
                    """
                    UPDATE runtime_missions
                    SET requested_control = %s,
                        control_reason = %s,
                        control_requested_at = %s,
                        status = CASE
                            WHEN %s = 'continue' AND status IN ('paused', 'migrated')
                            THEN 'queued'
                            ELSE status
                        END,
                        updated_at = NOW()
                    WHERE mission_id = %s
                    RETURNING requested_control, control_reason, control_requested_at
                    """,
                    (action.value, reason, requested_at, action.value, mission_id),
                )
            ).fetchone()
            if action is ControlAction.CONTINUE:
                await connection.execute(
                    """
                    UPDATE runtime_jobs
                    SET status = 'queued', available_at = NOW(), updated_at = NOW()
                    WHERE mission_id = %s AND status = 'paused'
                    """,
                    (mission_id,),
                )
        if row is None:
            raise KeyError(str(mission_id))
        return _control(row)

    async def enqueue_job(self, request: JobEnqueueRequest) -> uuid.UUID:
        """Create one queue job idempotently."""
        pool = self._require_pool()
        async with pool.connection() as connection:
            await connection.execute(
                """
                INSERT INTO runtime_jobs (
                    job_id, mission_id, command, workspace, requirements,
                    idempotency_key, priority, max_attempts, available_at
                ) VALUES (%s, %s, %s::jsonb, %s::jsonb, %s, %s, %s, %s, %s)
                ON CONFLICT (idempotency_key) DO NOTHING
                """,
                (
                    request.job_id,
                    request.mission_id,
                    request.command.model_dump_json(by_alias=True),
                    request.workspace.model_dump_json(by_alias=True),
                    list(request.requirements),
                    request.idempotency_key,
                    request.priority,
                    request.max_attempts,
                    request.available_at,
                ),
            )
            row = await (
                await connection.execute(
                    "SELECT job_id FROM runtime_jobs WHERE idempotency_key = %s",
                    (request.idempotency_key,),
                )
            ).fetchone()
        if row is None:
            raise RuntimeStoreError("job insert did not return an id")
        return uuid.UUID(str(row["job_id"]))

    async def claim_jobs(self, request: ClaimJobsRequest) -> ClaimJobsResponse:
        """Atomically claim available jobs using row locks and lease fencing."""
        pool = self._require_pool()
        leases: list[JobLease] = []
        async with pool.connection() as connection, connection.transaction():
            for _index in range(request.max_jobs):
                row = await (
                    await connection.execute(
                        """
                        SELECT j.*,
                            (
                                SELECT COALESCE(MAX(e.job_sequence), 0)
                                FROM runtime_events AS e
                                WHERE e.job_id = j.job_id
                            ) AS event_sequence
                        FROM runtime_jobs AS j
                        JOIN runtime_missions AS m USING (mission_id)
                        WHERE (
                            (j.status = 'queued' AND j.available_at <= NOW())
                            OR (
                                j.status IN ('leased', 'running')
                                AND j.lease_expires_at < NOW()
                            )
                        )
                        AND j.attempt < j.max_attempts
                        AND m.requested_control = 'continue'
                        AND %s::text[] @> j.requirements
                        ORDER BY j.priority DESC, j.available_at, j.created_at
                        FOR UPDATE OF j SKIP LOCKED
                        LIMIT 1
                        """,
                        (list(request.capabilities),),
                    )
                ).fetchone()
                if row is None:
                    break
                await connection.execute(
                    """
                    UPDATE runtime_job_attempts
                    SET ended_at = NOW(), outcome = 'fenced'
                    WHERE job_id = %s AND ended_at IS NULL
                    """,
                    (row["job_id"],),
                )
                lease_id = uuid.uuid4()
                attempt = int(row["attempt"]) + 1
                expires_at = datetime.now(UTC) + timedelta(seconds=request.lease_seconds)
                checkpoint = await (
                    await connection.execute(
                        """
                        SELECT snapshot_id FROM runtime_snapshots
                        WHERE job_id = %s ORDER BY sequence DESC LIMIT 1
                        """,
                        (row["job_id"],),
                    )
                ).fetchone()
                command = dict(row["command"])
                if checkpoint is not None:
                    command["type"] = JobCommandType.RESUME.value
                    command["checkpointId"] = str(checkpoint["snapshot_id"])
                claimed = await (
                    await connection.execute(
                        """
                        UPDATE runtime_jobs
                        SET status = 'leased', attempt = %s, worker_id = %s,
                            lease_id = %s, lease_expires_at = %s,
                            heartbeat_at = NOW(), updated_at = NOW(), error = NULL,
                            command = %s::jsonb
                        WHERE job_id = %s
                        RETURNING *
                        """,
                        (
                            attempt,
                            request.worker_id,
                            lease_id,
                            expires_at,
                            _json(command),
                            row["job_id"],
                        ),
                    )
                ).fetchone()
                claimed["event_sequence"] = row["event_sequence"]
                await connection.execute(
                    """
                    INSERT INTO runtime_job_attempts (
                        job_id, attempt, lease_id, worker_id
                    ) VALUES (%s, %s, %s, %s)
                    """,
                    (row["job_id"], attempt, lease_id, request.worker_id),
                )
                await connection.execute(
                    """
                    UPDATE runtime_missions
                    SET status = 'running', updated_at = NOW()
                    WHERE mission_id = %s AND status NOT IN ('completed', 'canceled')
                    """,
                    (row["mission_id"],),
                )
                leases.append(_job_lease(claimed))
        return ClaimJobsResponse(jobs=tuple(leases), server_time=datetime.now(UTC))

    async def heartbeat(
        self,
        job_id: uuid.UUID,
        request: HeartbeatRequest,
        *,
        lease_seconds: int | None = None,
    ) -> HeartbeatResponse:
        """Renew an active lease and return its mission control directive."""
        pool = self._require_pool()
        async with pool.connection() as connection, connection.transaction():
            job = await self._lock_lease(
                connection,
                job_id,
                request.worker_id,
                request.lease_id,
            )
            persisted_seconds = int((job["lease_expires_at"] - job["heartbeat_at"]).total_seconds())
            renewal_seconds = lease_seconds or max(15, min(3600, persisted_seconds))
            expires_at = datetime.now(UTC) + timedelta(seconds=renewal_seconds)
            row = await (
                await connection.execute(
                    """
                    UPDATE runtime_jobs
                    SET status = 'running', lease_expires_at = %s,
                        heartbeat_at = NOW(), progress = COALESCE(%s, progress),
                        current_phase = COALESCE(%s, current_phase),
                        current_task_id = COALESCE(%s, current_task_id),
                        updated_at = NOW()
                    WHERE job_id = %s
                    RETURNING lease_expires_at
                    """,
                    (
                        expires_at,
                        request.progress,
                        request.current_phase,
                        request.current_task_id,
                        job_id,
                    ),
                )
            ).fetchone()
            await connection.execute(
                """
                UPDATE runtime_job_attempts
                SET heartbeat_at = NOW()
                WHERE job_id = %s AND attempt = %s
                """,
                (job_id, job["attempt"]),
            )
            control = await self._control_for_mission(connection, job["mission_id"])
        return HeartbeatResponse(
            job_id=job_id,
            lease_id=request.lease_id,
            lease_expires_at=row["lease_expires_at"],
            control=control,
            server_time=datetime.now(UTC),
        )

    async def append_events(
        self,
        job_id: uuid.UUID,
        request: AppendEventsRequest,
    ) -> AppendEventsReceipt:
        """Append a contiguous event batch with event-id deduplication."""
        pool = self._require_pool()
        duplicates: list[int] = []
        accepted_through = 0
        async with pool.connection() as connection, connection.transaction():
            job = await self._lock_lease(
                connection,
                job_id,
                request.worker_id,
                request.lease_id,
            )
            sequence_row = await (
                await connection.execute(
                    "SELECT MAX(job_sequence) AS maximum FROM runtime_events WHERE job_id = %s",
                    (job_id,),
                )
            ).fetchone()
            expected = int(sequence_row["maximum"] or 0) + 1
            for event in request.events:
                if event.sequence < expected:
                    existing = await (
                        await connection.execute(
                            """
                            SELECT event_id FROM runtime_events
                            WHERE job_id = %s AND job_sequence = %s
                            """,
                            (job_id, event.sequence),
                        )
                    ).fetchone()
                    if existing is None or existing["event_id"] != event.event_id:
                        raise StoreConflictError(
                            "event sequence already contains different data",
                            details={
                                "sequence": event.sequence,
                                "expectedSequence": expected,
                            },
                        )
                    duplicates.append(event.sequence)
                    accepted_through = max(accepted_through, event.sequence)
                    continue
                if event.sequence != expected:
                    raise StoreConflictError(
                        "event sequence gap",
                        details={"expectedSequence": expected},
                    )
                await connection.execute(
                    """
                    INSERT INTO runtime_events (
                        event_id, mission_id, job_id, job_sequence,
                        event_type, event_timestamp, data
                    ) VALUES (%s, %s, %s, %s, %s, %s, %s::jsonb)
                    """,
                    (
                        event.event_id,
                        job["mission_id"],
                        job_id,
                        event.sequence,
                        event.type,
                        event.timestamp,
                        _json(event.data),
                    ),
                )
                accepted_through = event.sequence
                expected += 1
            control = await self._control_for_mission(connection, job["mission_id"])
        return AppendEventsReceipt(
            accepted_through=accepted_through,
            duplicate_sequences=tuple(duplicates),
            control=control,
        )

    async def save_snapshot(
        self,
        job_id: uuid.UUID,
        worker_id: str,
        lease_id: uuid.UUID,
        snapshot: MissionSnapshot,
    ) -> SnapshotReceipt:
        """Store a content-addressed mission snapshot idempotently."""
        pool = self._require_pool()
        payload_sha256 = _canonical_sha256(snapshot.payload)
        async with pool.connection() as connection, connection.transaction():
            job = await self._lock_lease(connection, job_id, worker_id, lease_id)
            existing = await (
                await connection.execute(
                    """
                    SELECT snapshot_id, payload_sha256, created_at
                    FROM runtime_snapshots WHERE job_id = %s AND sequence = %s
                    """,
                    (job_id, snapshot.sequence),
                )
            ).fetchone()
            if existing is not None:
                if existing["payload_sha256"] != payload_sha256:
                    raise StoreConflictError("snapshot sequence has different content")
                return SnapshotReceipt(
                    snapshot_id=existing["snapshot_id"],
                    sequence=snapshot.sequence,
                    created_at=existing["created_at"],
                )
            snapshot_id = uuid.uuid4()
            await connection.execute(
                """
                INSERT INTO runtime_snapshots (
                    snapshot_id, mission_id, job_id, sequence, schema_version,
                    content_type, payload, payload_sha256, created_at
                ) VALUES (%s, %s, %s, %s, %s, %s, %s::jsonb, %s, %s)
                """,
                (
                    snapshot_id,
                    job["mission_id"],
                    job_id,
                    snapshot.sequence,
                    snapshot.schema_version,
                    snapshot.content_type,
                    _json(snapshot.payload),
                    payload_sha256,
                    snapshot.created_at,
                ),
            )
            state = snapshot.payload.get("state")
            if isinstance(state, dict):
                await connection.execute(
                    """
                    UPDATE runtime_missions
                    SET state = %s::jsonb, state_sha256 = %s, updated_at = NOW()
                    WHERE mission_id = %s
                    """,
                    (_json(state), _canonical_sha256(state), job["mission_id"]),
                )
        return SnapshotReceipt(
            snapshot_id=snapshot_id,
            sequence=snapshot.sequence,
            created_at=snapshot.created_at,
        )

    async def get_snapshot(
        self,
        job_id: uuid.UUID,
        worker_id: str,
        lease_id: uuid.UUID,
        snapshot_id: uuid.UUID,
    ) -> MissionSnapshotRecord | None:
        """Return one snapshot only to the current fenced job lease."""
        pool = self._require_pool()
        async with pool.connection() as connection, connection.transaction():
            job = await self._lock_lease(connection, job_id, worker_id, lease_id)
            row = await (
                await connection.execute(
                    """
                    SELECT * FROM runtime_snapshots
                    WHERE snapshot_id = %s AND mission_id = %s
                    """,
                    (snapshot_id, job["mission_id"]),
                )
            ).fetchone()
            if row is None:
                return None
            artifact_rows = await (
                await connection.execute(
                    """
                    SELECT artifact_id, role FROM runtime_artifacts
                    WHERE job_id = %s AND status = 'available'
                    ORDER BY created_at, artifact_id
                    """,
                    (row["job_id"],),
                )
            ).fetchall()
        return MissionSnapshotRecord(
            snapshot_id=row["snapshot_id"],
            job_id=row["job_id"],
            mission_id=row["mission_id"],
            schema_version=row["schema_version"],
            sequence=row["sequence"],
            created_at=row["created_at"],
            content_type=row["content_type"],
            payload=row["payload"],
            artifacts=tuple(
                ArtifactReference(artifact_id=artifact["artifact_id"], role=artifact["role"])
                for artifact in artifact_rows
            ),
        )

    async def complete_job(
        self,
        job_id: uuid.UUID,
        request: JobCompletionRequest,
    ) -> JobCompletionResponse:
        """Complete a fenced job exactly once."""
        pool = self._require_pool()
        async with pool.connection() as connection, connection.transaction():
            saved = await self._idempotent_response(
                connection,
                job_id,
                "complete",
                request.idempotency_key,
                JobCompletionResponse,
            )
            if saved is not None:
                return JobCompletionResponse.model_validate(saved)
            job = await self._lock_lease(
                connection,
                job_id,
                request.worker_id,
                request.lease_id,
            )
            if request.result.mission_id != job["mission_id"]:
                raise StoreConflictError("result missionId does not match leased mission")
            await self._require_terminal_event(
                connection,
                job_id,
                request.final_event_sequence,
                success=True,
            )
            await self._require_available_artifacts(
                connection,
                job_id,
                request.artifacts,
            )
            completed_at = datetime.now(UTC)
            response = JobCompletionResponse(
                job_id=job_id,
                mission_id=job["mission_id"],
                completed_at=completed_at,
            )
            await connection.execute(
                """
                UPDATE runtime_jobs
                SET status = 'completed', result = %s::jsonb, completed_at = %s,
                    updated_at = NOW(), lease_expires_at = NULL
                WHERE job_id = %s
                """,
                (request.result.model_dump_json(by_alias=True), completed_at, job_id),
            )
            await connection.execute(
                """
                UPDATE runtime_job_attempts
                SET ended_at = %s, outcome = 'completed'
                WHERE job_id = %s AND attempt = %s
                """,
                (completed_at, job_id, job["attempt"]),
            )
            await connection.execute(
                """
                UPDATE runtime_missions
                SET status = 'completed', state = %s::jsonb,
                    state_sha256 = %s, completed_at = %s, updated_at = NOW()
                WHERE mission_id = %s
                """,
                (
                    request.result.model_dump_json(by_alias=True),
                    _canonical_sha256(request.result.model_dump(mode="json", by_alias=True)),
                    completed_at,
                    job["mission_id"],
                ),
            )
            await self._save_idempotent_response(
                connection,
                job_id,
                "complete",
                request.idempotency_key,
                response,
            )
        return response

    async def fail_job(
        self,
        job_id: uuid.UUID,
        request: JobFailureRequest,
    ) -> JobFailureResponse:
        """Fail or requeue a fenced job according to retry and control state."""
        pool = self._require_pool()
        async with pool.connection() as connection, connection.transaction():
            saved = await self._idempotent_response(
                connection,
                job_id,
                "fail",
                request.idempotency_key,
                JobFailureResponse,
            )
            if saved is not None:
                return JobFailureResponse.model_validate(saved)
            job = await self._lock_lease(
                connection,
                job_id,
                request.worker_id,
                request.lease_id,
            )
            await self._require_event_cursor(
                connection,
                job_id,
                request.final_event_sequence,
            )
            control = await self._control_for_mission(connection, job["mission_id"])
            can_retry = request.error.retryable and job["attempt"] < job["max_attempts"]
            queued = can_retry and control.action is not ControlAction.CANCEL
            now = datetime.now(UTC)
            delay = min(300, 5 * (2 ** (int(job["attempt"]) - 1)))
            next_attempt_at = now + timedelta(seconds=delay) if queued else None
            database_status = "queued" if queued else "failed"
            outcome = "requeued" if queued else "failed"
            if control.action is ControlAction.PAUSE:
                queued = True
                database_status = "paused"
                next_attempt_at = now
                outcome = "paused"
            if control.action is ControlAction.CANCEL:
                database_status = "canceled"
                outcome = "canceled"
            if not queued:
                await self._ensure_failure_terminal_event(
                    connection,
                    job,
                    request.final_event_sequence,
                    request.error,
                )
            snapshot_row = await (
                await connection.execute(
                    """
                    SELECT snapshot_id FROM runtime_snapshots
                    WHERE job_id = %s ORDER BY sequence DESC LIMIT 1
                    """,
                    (job_id,),
                )
            ).fetchone()
            checkpoint_id = snapshot_row["snapshot_id"] if snapshot_row is not None else None
            response = JobFailureResponse(
                job_id=job_id,
                mission_id=job["mission_id"],
                status="queued" if queued else "failed",
                attempt=job["attempt"],
                next_attempt_at=next_attempt_at,
                failed_at=None if queued else now,
            )
            await connection.execute(
                """
                UPDATE runtime_jobs
                SET status = %s, error = %s::jsonb, available_at = COALESCE(%s, available_at),
                    failed_at = CASE WHEN %s = 'failed' THEN %s ELSE failed_at END,
                    command = CASE
                        WHEN %s::uuid IS NOT NULL AND %s IN ('queued', 'paused')
                        THEN jsonb_set(
                            jsonb_set(command, '{checkpointId}', to_jsonb(%s::text), TRUE),
                            '{type}', '"resume"'::jsonb, TRUE
                        )
                        ELSE command
                    END,
                    max_attempts = CASE
                        WHEN %s = 'paused' THEN max_attempts + 1
                        ELSE max_attempts
                    END,
                    lease_id = NULL, lease_expires_at = NULL, worker_id = NULL,
                    updated_at = NOW()
                WHERE job_id = %s
                """,
                (
                    database_status,
                    request.error.model_dump_json(by_alias=True),
                    next_attempt_at,
                    database_status,
                    now,
                    checkpoint_id,
                    database_status,
                    checkpoint_id,
                    database_status,
                    job_id,
                ),
            )
            await connection.execute(
                """
                UPDATE runtime_job_attempts
                SET ended_at = %s, outcome = %s, error = %s::jsonb
                WHERE job_id = %s AND attempt = %s
                """,
                (
                    now,
                    outcome,
                    request.error.model_dump_json(by_alias=True),
                    job_id,
                    job["attempt"],
                ),
            )
            if control.action is ControlAction.PAUSE:
                await connection.execute(
                    """
                    UPDATE runtime_missions
                    SET status = 'paused', updated_at = NOW()
                    WHERE mission_id = %s AND status != 'completed'
                    """,
                    (job["mission_id"],),
                )
            elif not queued:
                await connection.execute(
                    """
                    UPDATE runtime_missions
                    SET status = %s, updated_at = NOW()
                    WHERE mission_id = %s AND status != 'completed'
                    """,
                    (
                        "canceled" if control.action is ControlAction.CANCEL else "failed",
                        job["mission_id"],
                    ),
                )
            await self._save_idempotent_response(
                connection,
                job_id,
                "fail",
                request.idempotency_key,
                response,
            )
        return response

    async def get_control(
        self,
        job_id: uuid.UUID,
        worker_id: str,
        lease_id: uuid.UUID,
    ) -> ControlDirective:
        """Return control only for the current fenced lease."""
        pool = self._require_pool()
        async with pool.connection() as connection, connection.transaction():
            job = await self._lock_lease(connection, job_id, worker_id, lease_id)
            return await self._control_for_mission(connection, job["mission_id"])

    async def list_events(
        self,
        mission_id: uuid.UUID,
        *,
        after_sequence: int = 0,
        limit: int = 1000,
    ) -> tuple[EventRecord, ...]:
        """Replay durable mission events after a global stream cursor."""
        if limit < 1 or limit > 5000:
            raise ValueError("limit must be between 1 and 5000")
        pool = self._require_pool()
        async with pool.connection() as connection:
            rows = await (
                await connection.execute(
                    """
                    SELECT * FROM runtime_events
                    WHERE mission_id = %s AND stream_sequence > %s
                    ORDER BY stream_sequence LIMIT %s
                    """,
                    (mission_id, after_sequence, limit),
                )
            ).fetchall()
        return tuple(
            EventRecord(
                event_id=row["event_id"],
                sequence=row["job_sequence"],
                type=row["event_type"],
                timestamp=row["event_timestamp"],
                data=row["data"],
                stream_sequence=row["stream_sequence"],
                mission_id=row["mission_id"],
                job_id=row["job_id"],
            )
            for row in rows
        )

    async def list_best_results(
        self,
        owner_id: str,
        limit: int,
    ) -> tuple[dict[str, Any], ...]:
        """List an owner's completed mission results ordered by best available rank."""
        if limit < 1 or limit > 100:
            raise ValueError("limit must be between 1 and 100")
        pool = self._require_pool()
        async with pool.connection() as connection:
            rows = await (
                await connection.execute(
                    """
                    SELECT mission_id, state, completed_at
                    FROM runtime_missions
                    WHERE owner_id = %s AND status = 'completed'
                    ORDER BY
                        NULLIF(state->>'finalRank', '')::integer ASC NULLS LAST,
                        NULLIF(state->>'finalScore', '')::double precision DESC NULLS LAST,
                        completed_at DESC
                    LIMIT %s
                    """,
                    (owner_id, limit),
                )
            ).fetchall()
        return tuple(
            {
                **row["state"],
                "missionId": str(row["mission_id"]),
                "completedAt": row["completed_at"].isoformat(),
            }
            for row in rows
        )

    async def reserve_artifact(
        self,
        job_id: uuid.UUID,
        spec: ArtifactUploadSpec,
        *,
        bucket: str,
    ) -> dict[str, Any]:
        """Authorize a lease and reserve immutable artifact metadata."""
        pool = self._require_pool()
        async with pool.connection() as connection, connection.transaction():
            job = await self._lock_lease(connection, job_id, spec.worker_id, spec.lease_id)
            artifact_id = uuid.uuid4()
            workspace = JobWorkspace.model_validate(job["workspace"])
            object_key = (
                f"{workspace.artifact_prefix}/attempt-artifacts/{artifact_id.hex}/{spec.name}"
            )
            await connection.execute(
                """
                INSERT INTO runtime_artifacts (
                    artifact_id, mission_id, job_id, attempt, role, name,
                    content_type, size_bytes, sha256, bucket, object_key
                ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
                """,
                (
                    artifact_id,
                    job["mission_id"],
                    job_id,
                    job["attempt"],
                    spec.role,
                    spec.name,
                    spec.content_type,
                    spec.size_bytes,
                    spec.sha256,
                    bucket,
                    object_key,
                ),
            )
        return {
            "artifact_id": artifact_id,
            "bucket": bucket,
            "object_key": object_key,
            "sha256": spec.sha256,
            "size_bytes": spec.size_bytes,
        }

    async def get_artifact_for_verification(
        self,
        job_id: uuid.UUID,
        worker_id: str,
        lease_id: uuid.UUID,
        artifact_id: uuid.UUID,
    ) -> dict[str, Any]:
        """Authorize access to reserved metadata under the current lease."""
        pool = self._require_pool()
        async with pool.connection() as connection, connection.transaction():
            await self._lock_lease(connection, job_id, worker_id, lease_id)
            row = await (
                await connection.execute(
                    """
                    SELECT * FROM runtime_artifacts
                    WHERE artifact_id = %s AND job_id = %s
                    """,
                    (artifact_id, job_id),
                )
            ).fetchone()
        if row is None:
            raise KeyError(str(artifact_id))
        return dict(row)

    async def get_artifact_for_download(
        self,
        job_id: uuid.UUID,
        worker_id: str,
        lease_id: uuid.UUID,
        artifact_id: uuid.UUID,
    ) -> dict[str, Any]:
        """Authorize a job-scoped artifact download."""
        pool = self._require_pool()
        async with pool.connection() as connection, connection.transaction():
            job = await self._lock_lease(connection, job_id, worker_id, lease_id)
            row = await (
                await connection.execute(
                    """
                    SELECT * FROM runtime_artifacts
                    WHERE artifact_id = %s AND mission_id = %s AND status = 'available'
                    """,
                    (artifact_id, job["mission_id"]),
                )
            ).fetchone()
        if row is None:
            raise KeyError(str(artifact_id))
        return dict(row)

    async def mark_artifact_available(
        self,
        job_id: uuid.UUID,
        worker_id: str,
        lease_id: uuid.UUID,
        artifact_id: uuid.UUID,
        *,
        actual_size: int,
        actual_sha256: str,
    ) -> ArtifactCompleteResponse:
        """Finalize an upload only when immutable metadata matches."""
        pool = self._require_pool()
        verified_at = datetime.now(UTC)
        async with pool.connection() as connection, connection.transaction():
            await self._lock_lease(connection, job_id, worker_id, lease_id)
            row = await (
                await connection.execute(
                    """
                    UPDATE runtime_artifacts
                    SET status = CASE
                            WHEN size_bytes = %s AND sha256 = %s THEN 'available'
                            ELSE 'invalid'
                        END,
                        available_at = CASE
                            WHEN size_bytes = %s AND sha256 = %s THEN NOW()
                            ELSE NULL
                        END
                    WHERE artifact_id = %s AND job_id = %s
                    RETURNING status
                    """,
                    (
                        actual_size,
                        actual_sha256,
                        actual_size,
                        actual_sha256,
                        artifact_id,
                        job_id,
                    ),
                )
            ).fetchone()
        if row is None:
            raise KeyError(str(artifact_id))
        if row["status"] != "available":
            raise StoreConflictError("uploaded artifact metadata did not match reservation")
        return ArtifactCompleteResponse(artifact_id=artifact_id, verified_at=verified_at)

    async def create_migration_record(
        self,
        request: MigrationCreateRequest,
        *,
        migration_id: uuid.UUID,
        bucket: str,
        object_key: str,
    ) -> dict[str, Any]:
        """Create or reuse an idempotent migration upload record."""
        pool = self._require_pool()
        async with pool.connection() as connection:
            await connection.execute(
                """
                INSERT INTO runtime_migrations (
                    migration_id, worker_id, idempotency_key, source_kind,
                    source_schema_version, source_sha256, size_bytes,
                    content_type, bucket, object_key
                ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
                ON CONFLICT (idempotency_key) DO NOTHING
                """,
                (
                    migration_id,
                    request.worker_id,
                    request.idempotency_key,
                    request.source.kind.value,
                    request.source.schema_version,
                    request.source.sha256,
                    request.source.size_bytes,
                    request.content_type,
                    bucket,
                    object_key,
                ),
            )
            row = await (
                await connection.execute(
                    """
                    SELECT * FROM runtime_migrations
                    WHERE idempotency_key = %s
                    """,
                    (request.idempotency_key,),
                )
            ).fetchone()
        if row is None:
            raise RuntimeStoreError("migration insert did not return an id")
        if (
            row["source_kind"] != request.source.kind.value
            or row["source_sha256"] != request.source.sha256
            or row["size_bytes"] != request.source.size_bytes
        ):
            raise StoreConflictError("migration idempotency key has different source metadata")
        if row["status"] != MigrationStatus.AWAITING_UPLOAD.value:
            raise StoreConflictError(
                "migration source was already accepted",
                details={"migrationId": str(row["migration_id"]), "status": row["status"]},
            )
        return dict(row)

    async def complete_migration_upload(
        self,
        migration_id: uuid.UUID,
        worker_id: str,
        sha256: str,
        size_bytes: int,
    ) -> MigrationRecord:
        """Queue a verified legacy upload exactly once."""
        pool = self._require_pool()
        async with pool.connection() as connection:
            row = await (
                await connection.execute(
                    """
                    UPDATE runtime_migrations
                    SET status = CASE
                            WHEN source_sha256 = %s AND size_bytes = %s THEN 'queued'
                            ELSE 'failed'
                        END,
                        error = CASE
                            WHEN source_sha256 = %s AND size_bytes = %s THEN NULL
                            ELSE '{"code":"source_mismatch","message":"Uploaded source metadata did not match","retryable":false}'::jsonb
                        END,
                        queued_at = CASE
                            WHEN source_sha256 = %s AND size_bytes = %s THEN NOW()
                            ELSE NULL
                        END
                    WHERE migration_id = %s AND worker_id = %s
                        AND status IN ('awaiting-upload', 'queued')
                    RETURNING *
                    """,
                    (
                        sha256,
                        size_bytes,
                        sha256,
                        size_bytes,
                        sha256,
                        size_bytes,
                        migration_id,
                        worker_id,
                    ),
                )
            ).fetchone()
        if row is None:
            raise KeyError(str(migration_id))
        return _migration_record(row)

    async def get_migration_for_verification(
        self,
        migration_id: uuid.UUID,
        worker_id: str,
    ) -> dict[str, Any]:
        """Return private S3 metadata for a worker-owned pending migration."""
        pool = self._require_pool()
        async with pool.connection() as connection:
            row = await (
                await connection.execute(
                    """
                    SELECT * FROM runtime_migrations
                    WHERE migration_id = %s AND worker_id = %s
                        AND status IN ('awaiting-upload', 'queued')
                    """,
                    (migration_id, worker_id),
                )
            ).fetchone()
        if row is None:
            raise KeyError(str(migration_id))
        return dict(row)

    async def claim_migration(
        self,
        migration_id: uuid.UUID,
        *,
        lease_seconds: int = 900,
    ) -> dict[str, Any]:
        """Claim one queued migration with an expiring processing token."""
        if lease_seconds < 60 or lease_seconds > 3600:
            raise ValueError("lease_seconds must be between 60 and 3600")
        pool = self._require_pool()
        token = uuid.uuid4()
        expires_at = datetime.now(UTC) + timedelta(seconds=lease_seconds)
        async with pool.connection() as connection:
            row = await (
                await connection.execute(
                    """
                    UPDATE runtime_migrations
                    SET status = 'running', processing_token = %s,
                        processing_expires_at = %s
                    WHERE migration_id = %s
                        AND (
                            status = 'queued'
                            OR (status = 'running' AND processing_expires_at < NOW())
                        )
                    RETURNING *
                    """,
                    (token, expires_at, migration_id),
                )
            ).fetchone()
        if row is None:
            raise StoreConflictError("migration is not queued or its processing lease is active")
        result = dict(row)
        result["processing_token"] = token
        return result

    async def complete_legacy_import(
        self,
        migration_id: uuid.UUID,
        processing_token: uuid.UUID,
        *,
        mission_states: tuple[dict[str, Any], ...] = (),
        experiments: tuple[dict[str, Any], ...] = (),
        hints: tuple[dict[str, Any], ...] = (),
        submissions: tuple[dict[str, Any], ...] = (),
    ) -> dict[str, int]:
        """Import validated legacy records and source ledger in one transaction."""
        pool = self._require_pool()
        async with pool.connection() as connection, connection.transaction():
            migration = await (
                await connection.execute(
                    """
                    SELECT * FROM runtime_migrations
                    WHERE migration_id = %s AND status = 'running'
                        AND processing_token = %s AND processing_expires_at > NOW()
                    FOR UPDATE
                    """,
                    (migration_id, processing_token),
                )
            ).fetchone()
            if migration is None:
                raise StoreConflictError("migration processing lease is stale")
            ledger = await (
                await connection.execute(
                    """
                    SELECT counts FROM legacy_source_ledger
                    WHERE source_kind = %s AND source_sha256 = %s
                    """,
                    (migration["source_kind"], migration["source_sha256"]),
                )
            ).fetchone()
            if ledger is not None:
                counts = {str(key): int(value) for key, value in ledger["counts"].items()}
                await self._finish_migration(connection, migration_id, counts)
                return counts
            for state in mission_states:
                await self._import_legacy_mission(
                    connection,
                    migration["source_sha256"],
                    state,
                )
            await self._insert_legacy_rows(
                connection,
                "legacy_experiments",
                migration["source_sha256"],
                experiments,
            )
            await self._insert_legacy_rows(
                connection,
                "legacy_hint_attempts",
                migration["source_sha256"],
                hints,
            )
            await self._insert_legacy_rows(
                connection,
                "legacy_submissions",
                migration["source_sha256"],
                submissions,
                history_only=True,
            )
            if submissions:
                await self._refresh_legacy_submission_guards(connection)
            counts = {
                "missionStates": len(mission_states),
                "experiments": len(experiments),
                "hintAttempts": len(hints),
                "submissions": len(submissions),
            }
            await connection.execute(
                """
                INSERT INTO legacy_source_ledger (
                    source_kind, source_sha256, source_schema_version,
                    migration_id, counts
                ) VALUES (%s, %s, %s, %s, %s::jsonb)
                """,
                (
                    migration["source_kind"],
                    migration["source_sha256"],
                    migration["source_schema_version"],
                    migration_id,
                    _json(counts),
                ),
            )
            await self._finish_migration(connection, migration_id, counts)
        return counts

    async def fail_migration_import(
        self,
        migration_id: uuid.UUID,
        processing_token: uuid.UUID,
        error: JobFailure,
    ) -> None:
        """Persist a safe terminal error under the active processing lease."""
        pool = self._require_pool()
        async with pool.connection() as connection:
            row = await (
                await connection.execute(
                    """
                    UPDATE runtime_migrations
                    SET status = 'failed', error = %s::jsonb,
                        processing_token = NULL, processing_expires_at = NULL,
                        completed_at = NOW()
                    WHERE migration_id = %s AND processing_token = %s
                    RETURNING migration_id
                    """,
                    (error.model_dump_json(by_alias=True), migration_id, processing_token),
                )
            ).fetchone()
        if row is None:
            raise StoreConflictError("migration processing lease is stale")

    async def get_migration(self, migration_id: uuid.UUID) -> MigrationRecord | None:
        """Return migration status without exposing its object-store location."""
        pool = self._require_pool()
        async with pool.connection() as connection:
            row = await (
                await connection.execute(
                    "SELECT * FROM runtime_migrations WHERE migration_id = %s",
                    (migration_id,),
                )
            ).fetchone()
        return _migration_record(row) if row is not None else None

    async def _import_legacy_mission(
        self,
        connection: Any,
        source_sha256: str,
        record: dict[str, Any],
    ) -> None:
        mission_id = uuid.UUID(record["legacyMissionId"])
        owner_id = record["ownerId"]
        snapshot_payload = record["snapshotPayload"]
        competition_id = snapshot_payload["migration"].get("competitionId")
        submission_rows = []
        if competition_id:
            submission_rows = await (
                await connection.execute(
                    """
                    SELECT payload FROM legacy_submissions
                    WHERE payload->>'competition_id' = %s
                    ORDER BY imported_at, record_id
                    """,
                    (competition_id,),
                )
            ).fetchall()
        snapshot_payload = _with_submission_guard(
            snapshot_payload,
            tuple(row["payload"] for row in submission_rows),
        )
        job_id = uuid.uuid5(mission_id, f"agent-k-legacy-job:{source_sha256}")
        snapshot_id = uuid.uuid5(mission_id, f"agent-k-legacy-snapshot:{source_sha256}")
        existing = await (
            await connection.execute(
                "SELECT owner_id, state FROM runtime_missions WHERE mission_id = %s",
                (mission_id,),
            )
        ).fetchone()
        if existing is not None and (
            existing["owner_id"] != owner_id
            or existing["state"].get("migration", {}).get("sourceSha256") != source_sha256
        ):
            raise StoreConflictError(f"legacy missionId collides with runtime mission {mission_id}")
        await connection.execute(
            """
            INSERT INTO legacy_mission_states (
                source_sha256, legacy_mission_id, owner_id, snapshot_payload
            ) VALUES (%s, %s, %s, %s::jsonb)
            ON CONFLICT (source_sha256, legacy_mission_id) DO NOTHING
            """,
            (source_sha256, mission_id, owner_id, _json(snapshot_payload)),
        )
        await connection.execute(
            """
            INSERT INTO runtime_missions (
                mission_id, owner_id, schema_version, status, state, state_sha256,
                requested_control, control_reason, control_requested_at
            ) VALUES (%s, %s, '1.0.0', 'paused', %s::jsonb, %s,
                'pause', 'legacy_import_requires_explicit_resume', NOW())
            ON CONFLICT (mission_id) DO NOTHING
            """,
            (
                mission_id,
                owner_id,
                _json(snapshot_payload),
                _canonical_sha256(snapshot_payload),
            ),
        )
        migration = snapshot_payload["migration"]
        command = {
            "type": "resume",
            "competitionId": migration.get("competitionId"),
            "criteria": migration.get("criteria", {}),
            "checkpointId": str(snapshot_id),
        }
        workspace = {"artifactPrefix": f"missions/{mission_id}"}
        await connection.execute(
            """
            INSERT INTO runtime_jobs (
                job_id, mission_id, status, command, workspace,
                idempotency_key, max_attempts
            ) VALUES (%s, %s, 'queued', %s::jsonb, %s::jsonb, %s, 3)
            ON CONFLICT (idempotency_key) DO NOTHING
            """,
            (
                job_id,
                mission_id,
                _json(command),
                _json(workspace),
                f"legacy:{source_sha256}:{mission_id}",
            ),
        )
        await connection.execute(
            """
            INSERT INTO runtime_snapshots (
                snapshot_id, mission_id, job_id, sequence, schema_version,
                content_type, payload, payload_sha256, created_at
            ) VALUES (%s, %s, %s, 0, '1.0.0', 'application/json',
                %s::jsonb, %s, NOW())
            ON CONFLICT (snapshot_id) DO NOTHING
            """,
            (
                snapshot_id,
                mission_id,
                job_id,
                _json(snapshot_payload),
                _canonical_sha256(snapshot_payload),
            ),
        )

    async def _insert_legacy_rows(
        self,
        connection: Any,
        table: str,
        source_sha256: str,
        records: tuple[dict[str, Any], ...],
        *,
        history_only: bool = False,
    ) -> None:
        if table not in {"legacy_experiments", "legacy_hint_attempts", "legacy_submissions"}:
            raise ValueError("unsupported legacy target table")
        for record in records:
            values: tuple[Any, ...]
            columns = "source_sha256, record_id, payload"
            placeholders = "%s, %s, %s::jsonb"
            values = (source_sha256, record["recordId"], _json(record["payload"]))
            if history_only:
                columns += ", history_only"
                placeholders += ", TRUE"
            await connection.execute(
                f"INSERT INTO {table} ({columns}) VALUES ({placeholders}) "
                "ON CONFLICT (source_sha256, record_id) DO NOTHING",
                values,
            )

    async def _refresh_legacy_submission_guards(self, connection: Any) -> None:
        snapshots = await (
            await connection.execute(
                """
                SELECT snapshot_id, mission_id, payload
                FROM runtime_snapshots
                WHERE payload->'migration'->>'kind' = 'legacy-v1'
                FOR UPDATE
                """
            )
        ).fetchall()
        for snapshot in snapshots:
            competition_id = snapshot["payload"]["migration"].get("competitionId")
            rows = []
            if competition_id:
                rows = await (
                    await connection.execute(
                        """
                        SELECT payload FROM legacy_submissions
                        WHERE payload->>'competition_id' = %s
                        ORDER BY imported_at, record_id
                        """,
                        (competition_id,),
                    )
                ).fetchall()
            payload = _with_submission_guard(
                snapshot["payload"],
                tuple(row["payload"] for row in rows),
            )
            digest = _canonical_sha256(payload)
            await connection.execute(
                """
                UPDATE runtime_snapshots SET payload = %s::jsonb, payload_sha256 = %s
                WHERE snapshot_id = %s
                """,
                (_json(payload), digest, snapshot["snapshot_id"]),
            )
            await connection.execute(
                """
                UPDATE runtime_missions SET state = %s::jsonb, state_sha256 = %s,
                    updated_at = NOW()
                WHERE mission_id = %s AND status IN ('migrated', 'paused')
                """,
                (_json(payload), digest, snapshot["mission_id"]),
            )

    async def _finish_migration(
        self,
        connection: Any,
        migration_id: uuid.UUID,
        counts: dict[str, int],
    ) -> None:
        await connection.execute(
            """
            UPDATE runtime_migrations
            SET status = 'completed', counts = %s::jsonb, error = NULL,
                processing_token = NULL, processing_expires_at = NULL,
                completed_at = NOW()
            WHERE migration_id = %s
            """,
            (_json(counts), migration_id),
        )

    def _require_pool(self) -> Any:
        if self._pool is None:
            raise RuntimeStoreError("PostgresRuntimeStore.open() must be called first")
        return self._pool

    async def _fetch_mission(self, connection: Any, mission_id: uuid.UUID) -> dict[str, Any]:
        row = await (
            await connection.execute(
                "SELECT * FROM runtime_missions WHERE mission_id = %s",
                (mission_id,),
            )
        ).fetchone()
        if row is None:
            raise RuntimeStoreError("mission insert did not return a row")
        return dict(row)

    async def _decorate_mission_row(self, connection: Any, row: dict[str, Any]) -> None:
        job = await (
            await connection.execute(
                """
                SELECT progress, current_phase FROM runtime_jobs
                WHERE mission_id = %s ORDER BY created_at DESC LIMIT 1
                """,
                (row["mission_id"],),
            )
        ).fetchone()
        event = await (
            await connection.execute(
                """
                SELECT COALESCE(MAX(stream_sequence), 0) AS latest_sequence
                FROM runtime_events WHERE mission_id = %s
                """,
                (row["mission_id"],),
            )
        ).fetchone()
        state = dict(row["state"])
        state["currentPhase"] = (
            job["current_phase"]
            if job is not None and job["current_phase"] is not None
            else state.get("current_phase", state.get("currentPhase"))
        )
        state["progress"] = (
            job["progress"]
            if job is not None and job["progress"] is not None
            else state.get("overall_progress", state.get("progress", 0.0))
        )
        state["latestSequence"] = int(event["latest_sequence"] if event is not None else 0)
        state["competitionId"] = state.get("competition_id", state.get("competitionId"))
        state["evolutionIterations"] = state.get(
            "evolution_iterations",
            state.get("evolutionIterations"),
        )
        row["state"] = state

    async def _lock_lease(
        self,
        connection: Any,
        job_id: uuid.UUID,
        worker_id: str,
        lease_id: uuid.UUID,
    ) -> dict[str, Any]:
        row = await (
            await connection.execute(
                "SELECT * FROM runtime_jobs WHERE job_id = %s FOR UPDATE",
                (job_id,),
            )
        ).fetchone()
        if row is None:
            raise KeyError(str(job_id))
        valid = (
            row["worker_id"] == worker_id
            and row["lease_id"] == lease_id
            and row["status"] in {"leased", "running"}
            and row["lease_expires_at"] is not None
            and row["lease_expires_at"] > datetime.now(UTC)
        )
        if not valid:
            raise LeaseFenceError("lease is stale, expired, or owned by another worker")
        return dict(row)

    async def _control_for_mission(
        self,
        connection: Any,
        mission_id: uuid.UUID,
    ) -> ControlDirective:
        row = await (
            await connection.execute(
                """
                SELECT requested_control, control_reason, control_requested_at
                FROM runtime_missions WHERE mission_id = %s
                """,
                (mission_id,),
            )
        ).fetchone()
        if row is None:
            raise KeyError(str(mission_id))
        return _control(row)

    async def _require_terminal_event(
        self,
        connection: Any,
        job_id: uuid.UUID,
        final_sequence: int,
        *,
        success: bool,
    ) -> None:
        row = await (
            await connection.execute(
                """
                SELECT event_type, data,
                    (SELECT COUNT(*) FROM runtime_events WHERE job_id = %s) AS event_count
                FROM runtime_events
                WHERE job_id = %s AND job_sequence = %s
                """,
                (job_id, job_id, final_sequence),
            )
        ).fetchone()
        valid = (
            row is not None
            and row["event_type"] == "mission-complete"
            and row["event_count"] == final_sequence
            and isinstance(row["data"], dict)
            and row["data"].get("success") is success
        )
        if not valid:
            raise StoreConflictError(
                "finalEventSequence must identify the contiguous mission-complete event",
                details={"finalEventSequence": final_sequence},
            )

    async def _require_event_cursor(
        self,
        connection: Any,
        job_id: uuid.UUID,
        final_sequence: int,
    ) -> None:
        row = await (
            await connection.execute(
                """
                SELECT COUNT(*) AS event_count,
                    COUNT(*) FILTER (WHERE job_sequence = %s) AS cursor_count
                FROM runtime_events WHERE job_id = %s
                """,
                (final_sequence, job_id),
            )
        ).fetchone()
        if row is None or row["event_count"] != final_sequence or row["cursor_count"] != 1:
            raise StoreConflictError(
                "finalEventSequence must identify the contiguous durable event cursor",
                details={"finalEventSequence": final_sequence},
            )

    async def _ensure_failure_terminal_event(
        self,
        connection: Any,
        job: dict[str, Any],
        final_sequence: int,
        error: JobFailure,
    ) -> None:
        row = await (
            await connection.execute(
                """
                SELECT event_type, data FROM runtime_events
                WHERE job_id = %s AND job_sequence = %s
                """,
                (job["job_id"], final_sequence),
            )
        ).fetchone()
        if row is not None and row["event_type"] == "mission-complete":
            if not isinstance(row["data"], dict) or row["data"].get("success") is not False:
                raise StoreConflictError("failure terminal event must have success false")
            return
        sequence = final_sequence + 1
        event_id = uuid.uuid5(
            uuid.NAMESPACE_URL,
            f"agent-k:{job['job_id']}:{sequence}",
        )
        await connection.execute(
            """
            INSERT INTO runtime_events (
                event_id, mission_id, job_id, job_sequence,
                event_type, event_timestamp, data
            ) VALUES (%s, %s, %s, %s, 'mission-complete', NOW(), %s::jsonb)
            """,
            (
                event_id,
                job["mission_id"],
                job["job_id"],
                sequence,
                _json(
                    {
                        "success": False,
                        "finalRank": None,
                        "finalScore": None,
                        "errorMessage": error.message,
                        "totalSubmissions": 0,
                        "evolutionGenerations": 0,
                        "evolutionIterations": 0,
                        "evolutionFailureSummary": {},
                        "durationMs": 0,
                        "phasesCompleted": [],
                    }
                ),
            ),
        )

    async def _require_available_artifacts(
        self,
        connection: Any,
        job_id: uuid.UUID,
        references: tuple[ArtifactReference, ...],
    ) -> None:
        if not references:
            return
        expected = {reference.artifact_id: reference.role for reference in references}
        if len(expected) != len(references):
            raise StoreConflictError("completion artifacts contain duplicate artifactIds")
        rows = await (
            await connection.execute(
                """
                SELECT artifact_id, role, status FROM runtime_artifacts
                WHERE job_id = %s AND artifact_id = ANY(%s::uuid[])
                """,
                (job_id, list(expected)),
            )
        ).fetchall()
        actual = {row["artifact_id"]: row["role"] for row in rows if row["status"] == "available"}
        if actual != expected:
            raise StoreConflictError("all completion artifacts must be verified and available")

    async def _idempotent_response(
        self,
        connection: Any,
        job_id: uuid.UUID,
        operation: str,
        key: str,
        model_type: type[WireModel],
    ) -> Any | None:
        row = await (
            await connection.execute(
                """
                SELECT response FROM runtime_job_idempotency
                WHERE job_id = %s AND operation = %s AND idempotency_key = %s
                """,
                (job_id, operation, key),
            )
        ).fetchone()
        return model_type.model_validate(row["response"]) if row is not None else None

    async def _save_idempotent_response(
        self,
        connection: Any,
        job_id: uuid.UUID,
        operation: str,
        key: str,
        response: WireModel,
    ) -> None:
        await connection.execute(
            """
            INSERT INTO runtime_job_idempotency (
                job_id, operation, idempotency_key, response
            ) VALUES (%s, %s, %s, %s::jsonb)
            """,
            (job_id, operation, key, response.model_dump_json(by_alias=True)),
        )

open async

open() -> None

Open and validate the PostgreSQL connection pool.

Source code in agent_k/stores.py
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
async def open(self) -> None:
    """Open and validate the PostgreSQL connection pool."""
    if self._pool is not None:
        return
    try:
        from psycopg.rows import dict_row
        from psycopg_pool import AsyncConnectionPool
    except ImportError as error:
        raise RuntimeError("PostgreSQL support requires `psycopg[binary,pool]`.") from error
    self._dict_row = dict_row
    self._pool = AsyncConnectionPool(
        self._database_url,
        min_size=self._min_pool_size,
        max_size=self._max_pool_size,
        open=False,
        kwargs={"row_factory": dict_row},
    )
    await self._pool.open()
    await self._pool.wait()

close async

close() -> None

Close the PostgreSQL connection pool.

Source code in agent_k/stores.py
623
624
625
626
627
628
629
async def close(self) -> None:
    """Close the PostgreSQL connection pool."""
    if self._pool is None:
        return
    pool = self._pool
    self._pool = None
    await pool.close()

initialize async

initialize() -> None

Apply checksum-protected SQL migrations in filename order.

Source code in agent_k/stores.py
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
async def initialize(self) -> None:
    """Apply checksum-protected SQL migrations in filename order."""
    pool = self._require_pool()
    migration_paths: list[Any]
    if self._migrations_dir is None:
        resource_root = files("agent_k").joinpath("resources")
        migration_paths = sorted(
            (
                resource
                for resource in resource_root.iterdir()
                if re.fullmatch(r"[0-9]{4}_.+\.sql", resource.name)
            ),
            key=lambda resource: resource.name,
        )
        location = "agent_k/resources"
    else:
        migration_paths = sorted(self._migrations_dir.glob("[0-9][0-9][0-9][0-9]_*.sql"))
        location = str(self._migrations_dir)
    if not migration_paths:
        raise RuntimeStoreError(f"No SQL migrations found in {location}")
    async with pool.connection() as connection:
        await connection.execute(
            "SELECT pg_advisory_lock(hashtext('agent-k-runtime-migrations'))"
        )
        try:
            await connection.execute(
                """
                CREATE TABLE IF NOT EXISTS runtime_schema_migrations (
                    version TEXT PRIMARY KEY,
                    sha256 TEXT NOT NULL,
                    applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
                )
                """
            )
            for migration_path in migration_paths:
                sql = migration_path.read_text(encoding="utf-8")
                digest = hashlib.sha256(sql.encode()).hexdigest()
                row = await (
                    await connection.execute(
                        "SELECT sha256 FROM runtime_schema_migrations WHERE version = %s",
                        (migration_path.name,),
                    )
                ).fetchone()
                if row is not None:
                    if row["sha256"] != digest:
                        raise StoreConflictError(
                            f"Applied migration changed: {migration_path.name}",
                        )
                    continue
                async with connection.transaction():
                    await connection.execute(sql, prepare=False)
                    await connection.execute(
                        """
                        INSERT INTO runtime_schema_migrations (version, sha256)
                        VALUES (%s, %s)
                        """,
                        (migration_path.name, digest),
                    )
        finally:
            await connection.execute(
                "SELECT pg_advisory_unlock(hashtext('agent-k-runtime-migrations'))"
            )

create_mission async

create_mission(mission_id: UUID, owner_id: str, *, state: dict[str, Any] | None = None, schema_version: str = STATE_SCHEMA_VERSION) -> MissionRecord

Create a mission idempotently and return its durable state.

Source code in agent_k/stores.py
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
async def create_mission(
    self,
    mission_id: uuid.UUID,
    owner_id: str,
    *,
    state: dict[str, Any] | None = None,
    schema_version: str = STATE_SCHEMA_VERSION,
) -> MissionRecord:
    """Create a mission idempotently and return its durable state."""
    pool = self._require_pool()
    payload = state or {}
    state_sha256 = _canonical_sha256(payload)
    async with pool.connection() as connection:
        await connection.execute(
            """
            INSERT INTO runtime_missions (
                mission_id, owner_id, schema_version, state, state_sha256
            ) VALUES (%s, %s, %s, %s::jsonb, %s)
            ON CONFLICT (mission_id) DO NOTHING
            """,
            (mission_id, owner_id, schema_version, _json(payload), state_sha256),
        )
        row = await self._fetch_mission(connection, mission_id)
    if row["owner_id"] != owner_id:
        raise StoreConflictError("missionId is already owned by another principal")
    return _mission_record(row)

get_mission async

get_mission(mission_id: UUID) -> MissionRecord | None

Return one mission or None when it does not exist.

Source code in agent_k/stores.py
721
722
723
724
725
726
727
728
729
730
731
732
733
async def get_mission(self, mission_id: uuid.UUID) -> MissionRecord | None:
    """Return one mission or ``None`` when it does not exist."""
    pool = self._require_pool()
    async with pool.connection() as connection:
        row = await (
            await connection.execute(
                "SELECT * FROM runtime_missions WHERE mission_id = %s",
                (mission_id,),
            )
        ).fetchone()
        if row is not None:
            await self._decorate_mission_row(connection, row)
    return _mission_record(row) if row is not None else None

require_owner async

require_owner(mission_id: UUID, owner_id: str) -> MissionRecord

Return a mission only when the caller owns it.

Source code in agent_k/stores.py
735
736
737
738
739
740
741
742
async def require_owner(self, mission_id: uuid.UUID, owner_id: str) -> MissionRecord:
    """Return a mission only when the caller owns it."""
    mission = await self.get_mission(mission_id)
    if mission is None:
        raise KeyError(str(mission_id))
    if mission.owner_id != owner_id:
        raise PermissionError("mission owner does not match")
    return mission

request_control async

request_control(mission_id: UUID, action: ControlAction, *, reason: str | None = None) -> ControlDirective

Persist a pause, cancel, or continue directive for a mission.

Source code in agent_k/stores.py
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
async def request_control(
    self,
    mission_id: uuid.UUID,
    action: ControlAction,
    *,
    reason: str | None = None,
) -> ControlDirective:
    """Persist a pause, cancel, or continue directive for a mission."""
    pool = self._require_pool()
    requested_at = datetime.now(UTC)
    async with pool.connection() as connection, connection.transaction():
        row = await (
            await connection.execute(
                """
                UPDATE runtime_missions
                SET requested_control = %s,
                    control_reason = %s,
                    control_requested_at = %s,
                    status = CASE
                        WHEN %s = 'continue' AND status IN ('paused', 'migrated')
                        THEN 'queued'
                        ELSE status
                    END,
                    updated_at = NOW()
                WHERE mission_id = %s
                RETURNING requested_control, control_reason, control_requested_at
                """,
                (action.value, reason, requested_at, action.value, mission_id),
            )
        ).fetchone()
        if action is ControlAction.CONTINUE:
            await connection.execute(
                """
                UPDATE runtime_jobs
                SET status = 'queued', available_at = NOW(), updated_at = NOW()
                WHERE mission_id = %s AND status = 'paused'
                """,
                (mission_id,),
            )
    if row is None:
        raise KeyError(str(mission_id))
    return _control(row)

enqueue_job async

enqueue_job(request: JobEnqueueRequest) -> UUID

Create one queue job idempotently.

Source code in agent_k/stores.py
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
async def enqueue_job(self, request: JobEnqueueRequest) -> uuid.UUID:
    """Create one queue job idempotently."""
    pool = self._require_pool()
    async with pool.connection() as connection:
        await connection.execute(
            """
            INSERT INTO runtime_jobs (
                job_id, mission_id, command, workspace, requirements,
                idempotency_key, priority, max_attempts, available_at
            ) VALUES (%s, %s, %s::jsonb, %s::jsonb, %s, %s, %s, %s, %s)
            ON CONFLICT (idempotency_key) DO NOTHING
            """,
            (
                request.job_id,
                request.mission_id,
                request.command.model_dump_json(by_alias=True),
                request.workspace.model_dump_json(by_alias=True),
                list(request.requirements),
                request.idempotency_key,
                request.priority,
                request.max_attempts,
                request.available_at,
            ),
        )
        row = await (
            await connection.execute(
                "SELECT job_id FROM runtime_jobs WHERE idempotency_key = %s",
                (request.idempotency_key,),
            )
        ).fetchone()
    if row is None:
        raise RuntimeStoreError("job insert did not return an id")
    return uuid.UUID(str(row["job_id"]))

claim_jobs async

claim_jobs(request: ClaimJobsRequest) -> ClaimJobsResponse

Atomically claim available jobs using row locks and lease fencing.

Source code in agent_k/stores.py
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
async def claim_jobs(self, request: ClaimJobsRequest) -> ClaimJobsResponse:
    """Atomically claim available jobs using row locks and lease fencing."""
    pool = self._require_pool()
    leases: list[JobLease] = []
    async with pool.connection() as connection, connection.transaction():
        for _index in range(request.max_jobs):
            row = await (
                await connection.execute(
                    """
                    SELECT j.*,
                        (
                            SELECT COALESCE(MAX(e.job_sequence), 0)
                            FROM runtime_events AS e
                            WHERE e.job_id = j.job_id
                        ) AS event_sequence
                    FROM runtime_jobs AS j
                    JOIN runtime_missions AS m USING (mission_id)
                    WHERE (
                        (j.status = 'queued' AND j.available_at <= NOW())
                        OR (
                            j.status IN ('leased', 'running')
                            AND j.lease_expires_at < NOW()
                        )
                    )
                    AND j.attempt < j.max_attempts
                    AND m.requested_control = 'continue'
                    AND %s::text[] @> j.requirements
                    ORDER BY j.priority DESC, j.available_at, j.created_at
                    FOR UPDATE OF j SKIP LOCKED
                    LIMIT 1
                    """,
                    (list(request.capabilities),),
                )
            ).fetchone()
            if row is None:
                break
            await connection.execute(
                """
                UPDATE runtime_job_attempts
                SET ended_at = NOW(), outcome = 'fenced'
                WHERE job_id = %s AND ended_at IS NULL
                """,
                (row["job_id"],),
            )
            lease_id = uuid.uuid4()
            attempt = int(row["attempt"]) + 1
            expires_at = datetime.now(UTC) + timedelta(seconds=request.lease_seconds)
            checkpoint = await (
                await connection.execute(
                    """
                    SELECT snapshot_id FROM runtime_snapshots
                    WHERE job_id = %s ORDER BY sequence DESC LIMIT 1
                    """,
                    (row["job_id"],),
                )
            ).fetchone()
            command = dict(row["command"])
            if checkpoint is not None:
                command["type"] = JobCommandType.RESUME.value
                command["checkpointId"] = str(checkpoint["snapshot_id"])
            claimed = await (
                await connection.execute(
                    """
                    UPDATE runtime_jobs
                    SET status = 'leased', attempt = %s, worker_id = %s,
                        lease_id = %s, lease_expires_at = %s,
                        heartbeat_at = NOW(), updated_at = NOW(), error = NULL,
                        command = %s::jsonb
                    WHERE job_id = %s
                    RETURNING *
                    """,
                    (
                        attempt,
                        request.worker_id,
                        lease_id,
                        expires_at,
                        _json(command),
                        row["job_id"],
                    ),
                )
            ).fetchone()
            claimed["event_sequence"] = row["event_sequence"]
            await connection.execute(
                """
                INSERT INTO runtime_job_attempts (
                    job_id, attempt, lease_id, worker_id
                ) VALUES (%s, %s, %s, %s)
                """,
                (row["job_id"], attempt, lease_id, request.worker_id),
            )
            await connection.execute(
                """
                UPDATE runtime_missions
                SET status = 'running', updated_at = NOW()
                WHERE mission_id = %s AND status NOT IN ('completed', 'canceled')
                """,
                (row["mission_id"],),
            )
            leases.append(_job_lease(claimed))
    return ClaimJobsResponse(jobs=tuple(leases), server_time=datetime.now(UTC))

heartbeat async

heartbeat(job_id: UUID, request: HeartbeatRequest, *, lease_seconds: int | None = None) -> HeartbeatResponse

Renew an active lease and return its mission control directive.

Source code in agent_k/stores.py
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
async def heartbeat(
    self,
    job_id: uuid.UUID,
    request: HeartbeatRequest,
    *,
    lease_seconds: int | None = None,
) -> HeartbeatResponse:
    """Renew an active lease and return its mission control directive."""
    pool = self._require_pool()
    async with pool.connection() as connection, connection.transaction():
        job = await self._lock_lease(
            connection,
            job_id,
            request.worker_id,
            request.lease_id,
        )
        persisted_seconds = int((job["lease_expires_at"] - job["heartbeat_at"]).total_seconds())
        renewal_seconds = lease_seconds or max(15, min(3600, persisted_seconds))
        expires_at = datetime.now(UTC) + timedelta(seconds=renewal_seconds)
        row = await (
            await connection.execute(
                """
                UPDATE runtime_jobs
                SET status = 'running', lease_expires_at = %s,
                    heartbeat_at = NOW(), progress = COALESCE(%s, progress),
                    current_phase = COALESCE(%s, current_phase),
                    current_task_id = COALESCE(%s, current_task_id),
                    updated_at = NOW()
                WHERE job_id = %s
                RETURNING lease_expires_at
                """,
                (
                    expires_at,
                    request.progress,
                    request.current_phase,
                    request.current_task_id,
                    job_id,
                ),
            )
        ).fetchone()
        await connection.execute(
            """
            UPDATE runtime_job_attempts
            SET heartbeat_at = NOW()
            WHERE job_id = %s AND attempt = %s
            """,
            (job_id, job["attempt"]),
        )
        control = await self._control_for_mission(connection, job["mission_id"])
    return HeartbeatResponse(
        job_id=job_id,
        lease_id=request.lease_id,
        lease_expires_at=row["lease_expires_at"],
        control=control,
        server_time=datetime.now(UTC),
    )

append_events async

append_events(job_id: UUID, request: AppendEventsRequest) -> AppendEventsReceipt

Append a contiguous event batch with event-id deduplication.

Source code in agent_k/stores.py
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
async def append_events(
    self,
    job_id: uuid.UUID,
    request: AppendEventsRequest,
) -> AppendEventsReceipt:
    """Append a contiguous event batch with event-id deduplication."""
    pool = self._require_pool()
    duplicates: list[int] = []
    accepted_through = 0
    async with pool.connection() as connection, connection.transaction():
        job = await self._lock_lease(
            connection,
            job_id,
            request.worker_id,
            request.lease_id,
        )
        sequence_row = await (
            await connection.execute(
                "SELECT MAX(job_sequence) AS maximum FROM runtime_events WHERE job_id = %s",
                (job_id,),
            )
        ).fetchone()
        expected = int(sequence_row["maximum"] or 0) + 1
        for event in request.events:
            if event.sequence < expected:
                existing = await (
                    await connection.execute(
                        """
                        SELECT event_id FROM runtime_events
                        WHERE job_id = %s AND job_sequence = %s
                        """,
                        (job_id, event.sequence),
                    )
                ).fetchone()
                if existing is None or existing["event_id"] != event.event_id:
                    raise StoreConflictError(
                        "event sequence already contains different data",
                        details={
                            "sequence": event.sequence,
                            "expectedSequence": expected,
                        },
                    )
                duplicates.append(event.sequence)
                accepted_through = max(accepted_through, event.sequence)
                continue
            if event.sequence != expected:
                raise StoreConflictError(
                    "event sequence gap",
                    details={"expectedSequence": expected},
                )
            await connection.execute(
                """
                INSERT INTO runtime_events (
                    event_id, mission_id, job_id, job_sequence,
                    event_type, event_timestamp, data
                ) VALUES (%s, %s, %s, %s, %s, %s, %s::jsonb)
                """,
                (
                    event.event_id,
                    job["mission_id"],
                    job_id,
                    event.sequence,
                    event.type,
                    event.timestamp,
                    _json(event.data),
                ),
            )
            accepted_through = event.sequence
            expected += 1
        control = await self._control_for_mission(connection, job["mission_id"])
    return AppendEventsReceipt(
        accepted_through=accepted_through,
        duplicate_sequences=tuple(duplicates),
        control=control,
    )

save_snapshot async

save_snapshot(job_id: UUID, worker_id: str, lease_id: UUID, snapshot: MissionSnapshot) -> SnapshotReceipt

Store a content-addressed mission snapshot idempotently.

Source code in agent_k/stores.py
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
async def save_snapshot(
    self,
    job_id: uuid.UUID,
    worker_id: str,
    lease_id: uuid.UUID,
    snapshot: MissionSnapshot,
) -> SnapshotReceipt:
    """Store a content-addressed mission snapshot idempotently."""
    pool = self._require_pool()
    payload_sha256 = _canonical_sha256(snapshot.payload)
    async with pool.connection() as connection, connection.transaction():
        job = await self._lock_lease(connection, job_id, worker_id, lease_id)
        existing = await (
            await connection.execute(
                """
                SELECT snapshot_id, payload_sha256, created_at
                FROM runtime_snapshots WHERE job_id = %s AND sequence = %s
                """,
                (job_id, snapshot.sequence),
            )
        ).fetchone()
        if existing is not None:
            if existing["payload_sha256"] != payload_sha256:
                raise StoreConflictError("snapshot sequence has different content")
            return SnapshotReceipt(
                snapshot_id=existing["snapshot_id"],
                sequence=snapshot.sequence,
                created_at=existing["created_at"],
            )
        snapshot_id = uuid.uuid4()
        await connection.execute(
            """
            INSERT INTO runtime_snapshots (
                snapshot_id, mission_id, job_id, sequence, schema_version,
                content_type, payload, payload_sha256, created_at
            ) VALUES (%s, %s, %s, %s, %s, %s, %s::jsonb, %s, %s)
            """,
            (
                snapshot_id,
                job["mission_id"],
                job_id,
                snapshot.sequence,
                snapshot.schema_version,
                snapshot.content_type,
                _json(snapshot.payload),
                payload_sha256,
                snapshot.created_at,
            ),
        )
        state = snapshot.payload.get("state")
        if isinstance(state, dict):
            await connection.execute(
                """
                UPDATE runtime_missions
                SET state = %s::jsonb, state_sha256 = %s, updated_at = NOW()
                WHERE mission_id = %s
                """,
                (_json(state), _canonical_sha256(state), job["mission_id"]),
            )
    return SnapshotReceipt(
        snapshot_id=snapshot_id,
        sequence=snapshot.sequence,
        created_at=snapshot.created_at,
    )

get_snapshot async

get_snapshot(job_id: UUID, worker_id: str, lease_id: UUID, snapshot_id: UUID) -> MissionSnapshotRecord | None

Return one snapshot only to the current fenced job lease.

Source code in agent_k/stores.py
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
async def get_snapshot(
    self,
    job_id: uuid.UUID,
    worker_id: str,
    lease_id: uuid.UUID,
    snapshot_id: uuid.UUID,
) -> MissionSnapshotRecord | None:
    """Return one snapshot only to the current fenced job lease."""
    pool = self._require_pool()
    async with pool.connection() as connection, connection.transaction():
        job = await self._lock_lease(connection, job_id, worker_id, lease_id)
        row = await (
            await connection.execute(
                """
                SELECT * FROM runtime_snapshots
                WHERE snapshot_id = %s AND mission_id = %s
                """,
                (snapshot_id, job["mission_id"]),
            )
        ).fetchone()
        if row is None:
            return None
        artifact_rows = await (
            await connection.execute(
                """
                SELECT artifact_id, role FROM runtime_artifacts
                WHERE job_id = %s AND status = 'available'
                ORDER BY created_at, artifact_id
                """,
                (row["job_id"],),
            )
        ).fetchall()
    return MissionSnapshotRecord(
        snapshot_id=row["snapshot_id"],
        job_id=row["job_id"],
        mission_id=row["mission_id"],
        schema_version=row["schema_version"],
        sequence=row["sequence"],
        created_at=row["created_at"],
        content_type=row["content_type"],
        payload=row["payload"],
        artifacts=tuple(
            ArtifactReference(artifact_id=artifact["artifact_id"], role=artifact["role"])
            for artifact in artifact_rows
        ),
    )

complete_job async

complete_job(job_id: UUID, request: JobCompletionRequest) -> JobCompletionResponse

Complete a fenced job exactly once.

Source code in agent_k/stores.py
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
async def complete_job(
    self,
    job_id: uuid.UUID,
    request: JobCompletionRequest,
) -> JobCompletionResponse:
    """Complete a fenced job exactly once."""
    pool = self._require_pool()
    async with pool.connection() as connection, connection.transaction():
        saved = await self._idempotent_response(
            connection,
            job_id,
            "complete",
            request.idempotency_key,
            JobCompletionResponse,
        )
        if saved is not None:
            return JobCompletionResponse.model_validate(saved)
        job = await self._lock_lease(
            connection,
            job_id,
            request.worker_id,
            request.lease_id,
        )
        if request.result.mission_id != job["mission_id"]:
            raise StoreConflictError("result missionId does not match leased mission")
        await self._require_terminal_event(
            connection,
            job_id,
            request.final_event_sequence,
            success=True,
        )
        await self._require_available_artifacts(
            connection,
            job_id,
            request.artifacts,
        )
        completed_at = datetime.now(UTC)
        response = JobCompletionResponse(
            job_id=job_id,
            mission_id=job["mission_id"],
            completed_at=completed_at,
        )
        await connection.execute(
            """
            UPDATE runtime_jobs
            SET status = 'completed', result = %s::jsonb, completed_at = %s,
                updated_at = NOW(), lease_expires_at = NULL
            WHERE job_id = %s
            """,
            (request.result.model_dump_json(by_alias=True), completed_at, job_id),
        )
        await connection.execute(
            """
            UPDATE runtime_job_attempts
            SET ended_at = %s, outcome = 'completed'
            WHERE job_id = %s AND attempt = %s
            """,
            (completed_at, job_id, job["attempt"]),
        )
        await connection.execute(
            """
            UPDATE runtime_missions
            SET status = 'completed', state = %s::jsonb,
                state_sha256 = %s, completed_at = %s, updated_at = NOW()
            WHERE mission_id = %s
            """,
            (
                request.result.model_dump_json(by_alias=True),
                _canonical_sha256(request.result.model_dump(mode="json", by_alias=True)),
                completed_at,
                job["mission_id"],
            ),
        )
        await self._save_idempotent_response(
            connection,
            job_id,
            "complete",
            request.idempotency_key,
            response,
        )
    return response

fail_job async

fail_job(job_id: UUID, request: JobFailureRequest) -> JobFailureResponse

Fail or requeue a fenced job according to retry and control state.

Source code in agent_k/stores.py
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
async def fail_job(
    self,
    job_id: uuid.UUID,
    request: JobFailureRequest,
) -> JobFailureResponse:
    """Fail or requeue a fenced job according to retry and control state."""
    pool = self._require_pool()
    async with pool.connection() as connection, connection.transaction():
        saved = await self._idempotent_response(
            connection,
            job_id,
            "fail",
            request.idempotency_key,
            JobFailureResponse,
        )
        if saved is not None:
            return JobFailureResponse.model_validate(saved)
        job = await self._lock_lease(
            connection,
            job_id,
            request.worker_id,
            request.lease_id,
        )
        await self._require_event_cursor(
            connection,
            job_id,
            request.final_event_sequence,
        )
        control = await self._control_for_mission(connection, job["mission_id"])
        can_retry = request.error.retryable and job["attempt"] < job["max_attempts"]
        queued = can_retry and control.action is not ControlAction.CANCEL
        now = datetime.now(UTC)
        delay = min(300, 5 * (2 ** (int(job["attempt"]) - 1)))
        next_attempt_at = now + timedelta(seconds=delay) if queued else None
        database_status = "queued" if queued else "failed"
        outcome = "requeued" if queued else "failed"
        if control.action is ControlAction.PAUSE:
            queued = True
            database_status = "paused"
            next_attempt_at = now
            outcome = "paused"
        if control.action is ControlAction.CANCEL:
            database_status = "canceled"
            outcome = "canceled"
        if not queued:
            await self._ensure_failure_terminal_event(
                connection,
                job,
                request.final_event_sequence,
                request.error,
            )
        snapshot_row = await (
            await connection.execute(
                """
                SELECT snapshot_id FROM runtime_snapshots
                WHERE job_id = %s ORDER BY sequence DESC LIMIT 1
                """,
                (job_id,),
            )
        ).fetchone()
        checkpoint_id = snapshot_row["snapshot_id"] if snapshot_row is not None else None
        response = JobFailureResponse(
            job_id=job_id,
            mission_id=job["mission_id"],
            status="queued" if queued else "failed",
            attempt=job["attempt"],
            next_attempt_at=next_attempt_at,
            failed_at=None if queued else now,
        )
        await connection.execute(
            """
            UPDATE runtime_jobs
            SET status = %s, error = %s::jsonb, available_at = COALESCE(%s, available_at),
                failed_at = CASE WHEN %s = 'failed' THEN %s ELSE failed_at END,
                command = CASE
                    WHEN %s::uuid IS NOT NULL AND %s IN ('queued', 'paused')
                    THEN jsonb_set(
                        jsonb_set(command, '{checkpointId}', to_jsonb(%s::text), TRUE),
                        '{type}', '"resume"'::jsonb, TRUE
                    )
                    ELSE command
                END,
                max_attempts = CASE
                    WHEN %s = 'paused' THEN max_attempts + 1
                    ELSE max_attempts
                END,
                lease_id = NULL, lease_expires_at = NULL, worker_id = NULL,
                updated_at = NOW()
            WHERE job_id = %s
            """,
            (
                database_status,
                request.error.model_dump_json(by_alias=True),
                next_attempt_at,
                database_status,
                now,
                checkpoint_id,
                database_status,
                checkpoint_id,
                database_status,
                job_id,
            ),
        )
        await connection.execute(
            """
            UPDATE runtime_job_attempts
            SET ended_at = %s, outcome = %s, error = %s::jsonb
            WHERE job_id = %s AND attempt = %s
            """,
            (
                now,
                outcome,
                request.error.model_dump_json(by_alias=True),
                job_id,
                job["attempt"],
            ),
        )
        if control.action is ControlAction.PAUSE:
            await connection.execute(
                """
                UPDATE runtime_missions
                SET status = 'paused', updated_at = NOW()
                WHERE mission_id = %s AND status != 'completed'
                """,
                (job["mission_id"],),
            )
        elif not queued:
            await connection.execute(
                """
                UPDATE runtime_missions
                SET status = %s, updated_at = NOW()
                WHERE mission_id = %s AND status != 'completed'
                """,
                (
                    "canceled" if control.action is ControlAction.CANCEL else "failed",
                    job["mission_id"],
                ),
            )
        await self._save_idempotent_response(
            connection,
            job_id,
            "fail",
            request.idempotency_key,
            response,
        )
    return response

get_control async

get_control(job_id: UUID, worker_id: str, lease_id: UUID) -> ControlDirective

Return control only for the current fenced lease.

Source code in agent_k/stores.py
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
async def get_control(
    self,
    job_id: uuid.UUID,
    worker_id: str,
    lease_id: uuid.UUID,
) -> ControlDirective:
    """Return control only for the current fenced lease."""
    pool = self._require_pool()
    async with pool.connection() as connection, connection.transaction():
        job = await self._lock_lease(connection, job_id, worker_id, lease_id)
        return await self._control_for_mission(connection, job["mission_id"])

list_events async

list_events(mission_id: UUID, *, after_sequence: int = 0, limit: int = 1000) -> tuple[EventRecord, ...]

Replay durable mission events after a global stream cursor.

Source code in agent_k/stores.py
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
async def list_events(
    self,
    mission_id: uuid.UUID,
    *,
    after_sequence: int = 0,
    limit: int = 1000,
) -> tuple[EventRecord, ...]:
    """Replay durable mission events after a global stream cursor."""
    if limit < 1 or limit > 5000:
        raise ValueError("limit must be between 1 and 5000")
    pool = self._require_pool()
    async with pool.connection() as connection:
        rows = await (
            await connection.execute(
                """
                SELECT * FROM runtime_events
                WHERE mission_id = %s AND stream_sequence > %s
                ORDER BY stream_sequence LIMIT %s
                """,
                (mission_id, after_sequence, limit),
            )
        ).fetchall()
    return tuple(
        EventRecord(
            event_id=row["event_id"],
            sequence=row["job_sequence"],
            type=row["event_type"],
            timestamp=row["event_timestamp"],
            data=row["data"],
            stream_sequence=row["stream_sequence"],
            mission_id=row["mission_id"],
            job_id=row["job_id"],
        )
        for row in rows
    )

list_best_results async

list_best_results(owner_id: str, limit: int) -> tuple[dict[str, Any], ...]

List an owner's completed mission results ordered by best available rank.

Source code in agent_k/stores.py
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
async def list_best_results(
    self,
    owner_id: str,
    limit: int,
) -> tuple[dict[str, Any], ...]:
    """List an owner's completed mission results ordered by best available rank."""
    if limit < 1 or limit > 100:
        raise ValueError("limit must be between 1 and 100")
    pool = self._require_pool()
    async with pool.connection() as connection:
        rows = await (
            await connection.execute(
                """
                SELECT mission_id, state, completed_at
                FROM runtime_missions
                WHERE owner_id = %s AND status = 'completed'
                ORDER BY
                    NULLIF(state->>'finalRank', '')::integer ASC NULLS LAST,
                    NULLIF(state->>'finalScore', '')::double precision DESC NULLS LAST,
                    completed_at DESC
                LIMIT %s
                """,
                (owner_id, limit),
            )
        ).fetchall()
    return tuple(
        {
            **row["state"],
            "missionId": str(row["mission_id"]),
            "completedAt": row["completed_at"].isoformat(),
        }
        for row in rows
    )

reserve_artifact async

reserve_artifact(job_id: UUID, spec: ArtifactUploadSpec, *, bucket: str) -> dict[str, Any]

Authorize a lease and reserve immutable artifact metadata.

Source code in agent_k/stores.py
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
async def reserve_artifact(
    self,
    job_id: uuid.UUID,
    spec: ArtifactUploadSpec,
    *,
    bucket: str,
) -> dict[str, Any]:
    """Authorize a lease and reserve immutable artifact metadata."""
    pool = self._require_pool()
    async with pool.connection() as connection, connection.transaction():
        job = await self._lock_lease(connection, job_id, spec.worker_id, spec.lease_id)
        artifact_id = uuid.uuid4()
        workspace = JobWorkspace.model_validate(job["workspace"])
        object_key = (
            f"{workspace.artifact_prefix}/attempt-artifacts/{artifact_id.hex}/{spec.name}"
        )
        await connection.execute(
            """
            INSERT INTO runtime_artifacts (
                artifact_id, mission_id, job_id, attempt, role, name,
                content_type, size_bytes, sha256, bucket, object_key
            ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
            """,
            (
                artifact_id,
                job["mission_id"],
                job_id,
                job["attempt"],
                spec.role,
                spec.name,
                spec.content_type,
                spec.size_bytes,
                spec.sha256,
                bucket,
                object_key,
            ),
        )
    return {
        "artifact_id": artifact_id,
        "bucket": bucket,
        "object_key": object_key,
        "sha256": spec.sha256,
        "size_bytes": spec.size_bytes,
    }

get_artifact_for_verification async

get_artifact_for_verification(job_id: UUID, worker_id: str, lease_id: UUID, artifact_id: UUID) -> dict[str, Any]

Authorize access to reserved metadata under the current lease.

Source code in agent_k/stores.py
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
async def get_artifact_for_verification(
    self,
    job_id: uuid.UUID,
    worker_id: str,
    lease_id: uuid.UUID,
    artifact_id: uuid.UUID,
) -> dict[str, Any]:
    """Authorize access to reserved metadata under the current lease."""
    pool = self._require_pool()
    async with pool.connection() as connection, connection.transaction():
        await self._lock_lease(connection, job_id, worker_id, lease_id)
        row = await (
            await connection.execute(
                """
                SELECT * FROM runtime_artifacts
                WHERE artifact_id = %s AND job_id = %s
                """,
                (artifact_id, job_id),
            )
        ).fetchone()
    if row is None:
        raise KeyError(str(artifact_id))
    return dict(row)

get_artifact_for_download async

get_artifact_for_download(job_id: UUID, worker_id: str, lease_id: UUID, artifact_id: UUID) -> dict[str, Any]

Authorize a job-scoped artifact download.

Source code in agent_k/stores.py
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
async def get_artifact_for_download(
    self,
    job_id: uuid.UUID,
    worker_id: str,
    lease_id: uuid.UUID,
    artifact_id: uuid.UUID,
) -> dict[str, Any]:
    """Authorize a job-scoped artifact download."""
    pool = self._require_pool()
    async with pool.connection() as connection, connection.transaction():
        job = await self._lock_lease(connection, job_id, worker_id, lease_id)
        row = await (
            await connection.execute(
                """
                SELECT * FROM runtime_artifacts
                WHERE artifact_id = %s AND mission_id = %s AND status = 'available'
                """,
                (artifact_id, job["mission_id"]),
            )
        ).fetchone()
    if row is None:
        raise KeyError(str(artifact_id))
    return dict(row)

mark_artifact_available async

mark_artifact_available(job_id: UUID, worker_id: str, lease_id: UUID, artifact_id: UUID, *, actual_size: int, actual_sha256: str) -> ArtifactCompleteResponse

Finalize an upload only when immutable metadata matches.

Source code in agent_k/stores.py
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
async def mark_artifact_available(
    self,
    job_id: uuid.UUID,
    worker_id: str,
    lease_id: uuid.UUID,
    artifact_id: uuid.UUID,
    *,
    actual_size: int,
    actual_sha256: str,
) -> ArtifactCompleteResponse:
    """Finalize an upload only when immutable metadata matches."""
    pool = self._require_pool()
    verified_at = datetime.now(UTC)
    async with pool.connection() as connection, connection.transaction():
        await self._lock_lease(connection, job_id, worker_id, lease_id)
        row = await (
            await connection.execute(
                """
                UPDATE runtime_artifacts
                SET status = CASE
                        WHEN size_bytes = %s AND sha256 = %s THEN 'available'
                        ELSE 'invalid'
                    END,
                    available_at = CASE
                        WHEN size_bytes = %s AND sha256 = %s THEN NOW()
                        ELSE NULL
                    END
                WHERE artifact_id = %s AND job_id = %s
                RETURNING status
                """,
                (
                    actual_size,
                    actual_sha256,
                    actual_size,
                    actual_sha256,
                    artifact_id,
                    job_id,
                ),
            )
        ).fetchone()
    if row is None:
        raise KeyError(str(artifact_id))
    if row["status"] != "available":
        raise StoreConflictError("uploaded artifact metadata did not match reservation")
    return ArtifactCompleteResponse(artifact_id=artifact_id, verified_at=verified_at)

create_migration_record async

create_migration_record(request: MigrationCreateRequest, *, migration_id: UUID, bucket: str, object_key: str) -> dict[str, Any]

Create or reuse an idempotent migration upload record.

Source code in agent_k/stores.py
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
async def create_migration_record(
    self,
    request: MigrationCreateRequest,
    *,
    migration_id: uuid.UUID,
    bucket: str,
    object_key: str,
) -> dict[str, Any]:
    """Create or reuse an idempotent migration upload record."""
    pool = self._require_pool()
    async with pool.connection() as connection:
        await connection.execute(
            """
            INSERT INTO runtime_migrations (
                migration_id, worker_id, idempotency_key, source_kind,
                source_schema_version, source_sha256, size_bytes,
                content_type, bucket, object_key
            ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
            ON CONFLICT (idempotency_key) DO NOTHING
            """,
            (
                migration_id,
                request.worker_id,
                request.idempotency_key,
                request.source.kind.value,
                request.source.schema_version,
                request.source.sha256,
                request.source.size_bytes,
                request.content_type,
                bucket,
                object_key,
            ),
        )
        row = await (
            await connection.execute(
                """
                SELECT * FROM runtime_migrations
                WHERE idempotency_key = %s
                """,
                (request.idempotency_key,),
            )
        ).fetchone()
    if row is None:
        raise RuntimeStoreError("migration insert did not return an id")
    if (
        row["source_kind"] != request.source.kind.value
        or row["source_sha256"] != request.source.sha256
        or row["size_bytes"] != request.source.size_bytes
    ):
        raise StoreConflictError("migration idempotency key has different source metadata")
    if row["status"] != MigrationStatus.AWAITING_UPLOAD.value:
        raise StoreConflictError(
            "migration source was already accepted",
            details={"migrationId": str(row["migration_id"]), "status": row["status"]},
        )
    return dict(row)

complete_migration_upload async

complete_migration_upload(migration_id: UUID, worker_id: str, sha256: str, size_bytes: int) -> MigrationRecord

Queue a verified legacy upload exactly once.

Source code in agent_k/stores.py
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
async def complete_migration_upload(
    self,
    migration_id: uuid.UUID,
    worker_id: str,
    sha256: str,
    size_bytes: int,
) -> MigrationRecord:
    """Queue a verified legacy upload exactly once."""
    pool = self._require_pool()
    async with pool.connection() as connection:
        row = await (
            await connection.execute(
                """
                UPDATE runtime_migrations
                SET status = CASE
                        WHEN source_sha256 = %s AND size_bytes = %s THEN 'queued'
                        ELSE 'failed'
                    END,
                    error = CASE
                        WHEN source_sha256 = %s AND size_bytes = %s THEN NULL
                        ELSE '{"code":"source_mismatch","message":"Uploaded source metadata did not match","retryable":false}'::jsonb
                    END,
                    queued_at = CASE
                        WHEN source_sha256 = %s AND size_bytes = %s THEN NOW()
                        ELSE NULL
                    END
                WHERE migration_id = %s AND worker_id = %s
                    AND status IN ('awaiting-upload', 'queued')
                RETURNING *
                """,
                (
                    sha256,
                    size_bytes,
                    sha256,
                    size_bytes,
                    sha256,
                    size_bytes,
                    migration_id,
                    worker_id,
                ),
            )
        ).fetchone()
    if row is None:
        raise KeyError(str(migration_id))
    return _migration_record(row)

get_migration_for_verification async

get_migration_for_verification(migration_id: UUID, worker_id: str) -> dict[str, Any]

Return private S3 metadata for a worker-owned pending migration.

Source code in agent_k/stores.py
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
async def get_migration_for_verification(
    self,
    migration_id: uuid.UUID,
    worker_id: str,
) -> dict[str, Any]:
    """Return private S3 metadata for a worker-owned pending migration."""
    pool = self._require_pool()
    async with pool.connection() as connection:
        row = await (
            await connection.execute(
                """
                SELECT * FROM runtime_migrations
                WHERE migration_id = %s AND worker_id = %s
                    AND status IN ('awaiting-upload', 'queued')
                """,
                (migration_id, worker_id),
            )
        ).fetchone()
    if row is None:
        raise KeyError(str(migration_id))
    return dict(row)

claim_migration async

claim_migration(migration_id: UUID, *, lease_seconds: int = 900) -> dict[str, Any]

Claim one queued migration with an expiring processing token.

Source code in agent_k/stores.py
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
async def claim_migration(
    self,
    migration_id: uuid.UUID,
    *,
    lease_seconds: int = 900,
) -> dict[str, Any]:
    """Claim one queued migration with an expiring processing token."""
    if lease_seconds < 60 or lease_seconds > 3600:
        raise ValueError("lease_seconds must be between 60 and 3600")
    pool = self._require_pool()
    token = uuid.uuid4()
    expires_at = datetime.now(UTC) + timedelta(seconds=lease_seconds)
    async with pool.connection() as connection:
        row = await (
            await connection.execute(
                """
                UPDATE runtime_migrations
                SET status = 'running', processing_token = %s,
                    processing_expires_at = %s
                WHERE migration_id = %s
                    AND (
                        status = 'queued'
                        OR (status = 'running' AND processing_expires_at < NOW())
                    )
                RETURNING *
                """,
                (token, expires_at, migration_id),
            )
        ).fetchone()
    if row is None:
        raise StoreConflictError("migration is not queued or its processing lease is active")
    result = dict(row)
    result["processing_token"] = token
    return result

complete_legacy_import async

complete_legacy_import(migration_id: UUID, processing_token: UUID, *, mission_states: tuple[dict[str, Any], ...] = (), experiments: tuple[dict[str, Any], ...] = (), hints: tuple[dict[str, Any], ...] = (), submissions: tuple[dict[str, Any], ...] = ()) -> dict[str, int]

Import validated legacy records and source ledger in one transaction.

Source code in agent_k/stores.py
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
async def complete_legacy_import(
    self,
    migration_id: uuid.UUID,
    processing_token: uuid.UUID,
    *,
    mission_states: tuple[dict[str, Any], ...] = (),
    experiments: tuple[dict[str, Any], ...] = (),
    hints: tuple[dict[str, Any], ...] = (),
    submissions: tuple[dict[str, Any], ...] = (),
) -> dict[str, int]:
    """Import validated legacy records and source ledger in one transaction."""
    pool = self._require_pool()
    async with pool.connection() as connection, connection.transaction():
        migration = await (
            await connection.execute(
                """
                SELECT * FROM runtime_migrations
                WHERE migration_id = %s AND status = 'running'
                    AND processing_token = %s AND processing_expires_at > NOW()
                FOR UPDATE
                """,
                (migration_id, processing_token),
            )
        ).fetchone()
        if migration is None:
            raise StoreConflictError("migration processing lease is stale")
        ledger = await (
            await connection.execute(
                """
                SELECT counts FROM legacy_source_ledger
                WHERE source_kind = %s AND source_sha256 = %s
                """,
                (migration["source_kind"], migration["source_sha256"]),
            )
        ).fetchone()
        if ledger is not None:
            counts = {str(key): int(value) for key, value in ledger["counts"].items()}
            await self._finish_migration(connection, migration_id, counts)
            return counts
        for state in mission_states:
            await self._import_legacy_mission(
                connection,
                migration["source_sha256"],
                state,
            )
        await self._insert_legacy_rows(
            connection,
            "legacy_experiments",
            migration["source_sha256"],
            experiments,
        )
        await self._insert_legacy_rows(
            connection,
            "legacy_hint_attempts",
            migration["source_sha256"],
            hints,
        )
        await self._insert_legacy_rows(
            connection,
            "legacy_submissions",
            migration["source_sha256"],
            submissions,
            history_only=True,
        )
        if submissions:
            await self._refresh_legacy_submission_guards(connection)
        counts = {
            "missionStates": len(mission_states),
            "experiments": len(experiments),
            "hintAttempts": len(hints),
            "submissions": len(submissions),
        }
        await connection.execute(
            """
            INSERT INTO legacy_source_ledger (
                source_kind, source_sha256, source_schema_version,
                migration_id, counts
            ) VALUES (%s, %s, %s, %s, %s::jsonb)
            """,
            (
                migration["source_kind"],
                migration["source_sha256"],
                migration["source_schema_version"],
                migration_id,
                _json(counts),
            ),
        )
        await self._finish_migration(connection, migration_id, counts)
    return counts

fail_migration_import async

fail_migration_import(migration_id: UUID, processing_token: UUID, error: JobFailure) -> None

Persist a safe terminal error under the active processing lease.

Source code in agent_k/stores.py
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
async def fail_migration_import(
    self,
    migration_id: uuid.UUID,
    processing_token: uuid.UUID,
    error: JobFailure,
) -> None:
    """Persist a safe terminal error under the active processing lease."""
    pool = self._require_pool()
    async with pool.connection() as connection:
        row = await (
            await connection.execute(
                """
                UPDATE runtime_migrations
                SET status = 'failed', error = %s::jsonb,
                    processing_token = NULL, processing_expires_at = NULL,
                    completed_at = NOW()
                WHERE migration_id = %s AND processing_token = %s
                RETURNING migration_id
                """,
                (error.model_dump_json(by_alias=True), migration_id, processing_token),
            )
        ).fetchone()
    if row is None:
        raise StoreConflictError("migration processing lease is stale")

get_migration async

get_migration(migration_id: UUID) -> MigrationRecord | None

Return migration status without exposing its object-store location.

Source code in agent_k/stores.py
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
async def get_migration(self, migration_id: uuid.UUID) -> MigrationRecord | None:
    """Return migration status without exposing its object-store location."""
    pool = self._require_pool()
    async with pool.connection() as connection:
        row = await (
            await connection.execute(
                "SELECT * FROM runtime_migrations WHERE migration_id = %s",
                (migration_id,),
            )
        ).fetchone()
    return _migration_record(row) if row is not None else None

S3ArtifactStore

Server-side S3 signer that never exposes storage credentials to workers.

Source code in agent_k/stores.py
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
class S3ArtifactStore:
    """Server-side S3 signer that never exposes storage credentials to workers."""

    def __init__(
        self,
        runtime_store: PostgresRuntimeStore,
        *,
        bucket: str,
        region: str | None = None,
        endpoint_url: str | None = None,
        url_ttl_seconds: int = 3600,
    ) -> None:
        if not bucket:
            raise ValueError("bucket is required")
        if url_ttl_seconds < 60 or url_ttl_seconds > 3600:
            raise ValueError("url_ttl_seconds must be between 60 and 3600")
        try:
            import boto3
            from botocore.config import Config
        except ImportError as error:
            raise RuntimeError("S3 support requires `boto3`.") from error
        self._runtime_store = runtime_store
        self._bucket = bucket
        self._url_ttl_seconds = url_ttl_seconds
        self._client = boto3.client(
            "s3",
            region_name=region,
            endpoint_url=endpoint_url,
            config=Config(signature_version="s3v4"),
        )

    async def sign_upload(
        self,
        job_id: uuid.UUID,
        spec: ArtifactUploadSpec,
    ) -> SignedArtifactURL:
        """Reserve metadata and sign a checksum-bound S3 PUT request."""
        artifact = await self._runtime_store.reserve_artifact(
            job_id,
            spec,
            bucket=self._bucket,
        )
        checksum = base64.b64encode(bytes.fromhex(spec.sha256)).decode()
        params = {
            "Bucket": self._bucket,
            "Key": artifact["object_key"],
            "ContentType": spec.content_type,
            "ChecksumSHA256": checksum,
        }
        url = await asyncio.to_thread(
            self._client.generate_presigned_url,
            "put_object",
            Params=params,
            ExpiresIn=self._url_ttl_seconds,
            HttpMethod="PUT",
        )
        return SignedArtifactURL(
            artifact_id=artifact["artifact_id"],
            method="PUT",
            url=url,
            headers={
                "content-type": spec.content_type,
                "x-amz-checksum-sha256": checksum,
            },
            expires_at=datetime.now(UTC) + timedelta(seconds=self._url_ttl_seconds),
        )

    async def complete_upload(
        self,
        job_id: uuid.UUID,
        artifact_id: uuid.UUID,
        spec: ArtifactCompleteSpec,
    ) -> ArtifactCompleteResponse:
        """Verify one S3 object server-side before making it available."""
        artifact = await self._runtime_store.get_artifact_for_verification(
            job_id,
            spec.worker_id,
            spec.lease_id,
            artifact_id,
        )
        if artifact["sha256"] != spec.sha256 or artifact["size_bytes"] != spec.size_bytes:
            raise StoreConflictError("artifact completion metadata differs from reservation")
        response = await asyncio.to_thread(
            self._client.head_object,
            Bucket=artifact["bucket"],
            Key=artifact["object_key"],
            ChecksumMode="ENABLED",
        )
        actual_checksum = response.get("ChecksumSHA256")
        expected_checksum = base64.b64encode(bytes.fromhex(spec.sha256)).decode()
        actual_size = int(response["ContentLength"])
        if actual_size != spec.size_bytes or actual_checksum != expected_checksum:
            raise StoreConflictError("S3 object does not match reserved size and checksum")
        return await self._runtime_store.mark_artifact_available(
            job_id,
            spec.worker_id,
            spec.lease_id,
            artifact_id,
            actual_size=actual_size,
            actual_sha256=spec.sha256,
        )

    async def sign_download(
        self,
        job_id: uuid.UUID,
        worker_id: str,
        lease_id: uuid.UUID,
        artifact_id: uuid.UUID,
    ) -> SignedArtifactURL:
        """Sign a GET request only for an artifact in the leased mission."""
        artifact = await self._runtime_store.get_artifact_for_download(
            job_id,
            worker_id,
            lease_id,
            artifact_id,
        )
        url = await asyncio.to_thread(
            self._client.generate_presigned_url,
            "get_object",
            Params={"Bucket": artifact["bucket"], "Key": artifact["object_key"]},
            ExpiresIn=self._url_ttl_seconds,
            HttpMethod="GET",
        )
        return SignedArtifactURL(
            artifact_id=artifact_id,
            method="GET",
            url=url,
            headers={},
            expires_at=datetime.now(UTC) + timedelta(seconds=self._url_ttl_seconds),
        )

    async def create_migration_upload(
        self,
        request: MigrationCreateRequest,
    ) -> MigrationCreateResponse:
        """Create an idempotent, content-addressed legacy upload."""
        migration_id = uuid.uuid4()
        suffix = "json" if request.source.kind is MigrationSourceKind.MISSION_STATE else "sqlite3"
        object_key = (
            f"migrations/{request.source.kind.value}/{request.source.sha256}/"
            f"{migration_id}.{suffix}"
        )
        migration = await self._runtime_store.create_migration_record(
            request,
            migration_id=migration_id,
            bucket=self._bucket,
            object_key=object_key,
        )
        checksum = base64.b64encode(bytes.fromhex(request.source.sha256)).decode()
        url = await asyncio.to_thread(
            self._client.generate_presigned_url,
            "put_object",
            Params={
                "Bucket": self._bucket,
                "Key": migration["object_key"],
                "ContentType": request.content_type,
                "ChecksumSHA256": checksum,
            },
            ExpiresIn=self._url_ttl_seconds,
            HttpMethod="PUT",
        )
        upload = SignedArtifactURL(
            artifact_id=migration["migration_id"],
            method="PUT",
            url=url,
            headers={
                "content-type": request.content_type,
                "x-amz-checksum-sha256": checksum,
            },
            expires_at=datetime.now(UTC) + timedelta(seconds=self._url_ttl_seconds),
        )
        return MigrationCreateResponse(migration_id=migration["migration_id"], upload=upload)

    async def complete_migration_upload(
        self,
        migration_id: uuid.UUID,
        worker_id: str,
        sha256: str,
        size_bytes: int,
    ) -> MigrationRecord:
        """Verify a legacy source in S3 before queueing its import."""
        migration = await self._runtime_store.get_migration_for_verification(
            migration_id,
            worker_id,
        )
        if migration["source_sha256"] != sha256 or migration["size_bytes"] != size_bytes:
            raise StoreConflictError("migration completion metadata differs from reservation")
        response = await asyncio.to_thread(
            self._client.head_object,
            Bucket=migration["bucket"],
            Key=migration["object_key"],
            ChecksumMode="ENABLED",
        )
        expected_checksum = base64.b64encode(bytes.fromhex(sha256)).decode()
        if (
            int(response["ContentLength"]) != size_bytes
            or response.get("ChecksumSHA256") != expected_checksum
        ):
            raise StoreConflictError("S3 migration object failed size or checksum validation")
        return await self._runtime_store.complete_migration_upload(
            migration_id,
            worker_id,
            sha256,
            size_bytes,
        )

    async def download_claimed_migration(
        self,
        migration: dict[str, Any],
        destination: Path,
    ) -> None:
        """Download and verify a migration held by a database processing lease."""
        temporary = destination.with_name(f".{destination.name}.{uuid.uuid4().hex}.tmp")
        try:
            await asyncio.to_thread(
                self._client.download_file,
                migration["bucket"],
                migration["object_key"],
                str(temporary),
            )
            actual_size = temporary.stat().st_size
            actual_sha256 = await asyncio.to_thread(_file_sha256, temporary)
            if (
                actual_size != migration["size_bytes"]
                or actual_sha256 != migration["source_sha256"]
            ):
                raise StoreConflictError("downloaded migration source failed integrity validation")
            temporary.replace(destination)
        finally:
            temporary.unlink(missing_ok=True)

sign_upload async

sign_upload(job_id: UUID, spec: ArtifactUploadSpec) -> SignedArtifactURL

Reserve metadata and sign a checksum-bound S3 PUT request.

Source code in agent_k/stores.py
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
async def sign_upload(
    self,
    job_id: uuid.UUID,
    spec: ArtifactUploadSpec,
) -> SignedArtifactURL:
    """Reserve metadata and sign a checksum-bound S3 PUT request."""
    artifact = await self._runtime_store.reserve_artifact(
        job_id,
        spec,
        bucket=self._bucket,
    )
    checksum = base64.b64encode(bytes.fromhex(spec.sha256)).decode()
    params = {
        "Bucket": self._bucket,
        "Key": artifact["object_key"],
        "ContentType": spec.content_type,
        "ChecksumSHA256": checksum,
    }
    url = await asyncio.to_thread(
        self._client.generate_presigned_url,
        "put_object",
        Params=params,
        ExpiresIn=self._url_ttl_seconds,
        HttpMethod="PUT",
    )
    return SignedArtifactURL(
        artifact_id=artifact["artifact_id"],
        method="PUT",
        url=url,
        headers={
            "content-type": spec.content_type,
            "x-amz-checksum-sha256": checksum,
        },
        expires_at=datetime.now(UTC) + timedelta(seconds=self._url_ttl_seconds),
    )

complete_upload async

complete_upload(job_id: UUID, artifact_id: UUID, spec: ArtifactCompleteSpec) -> ArtifactCompleteResponse

Verify one S3 object server-side before making it available.

Source code in agent_k/stores.py
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
async def complete_upload(
    self,
    job_id: uuid.UUID,
    artifact_id: uuid.UUID,
    spec: ArtifactCompleteSpec,
) -> ArtifactCompleteResponse:
    """Verify one S3 object server-side before making it available."""
    artifact = await self._runtime_store.get_artifact_for_verification(
        job_id,
        spec.worker_id,
        spec.lease_id,
        artifact_id,
    )
    if artifact["sha256"] != spec.sha256 or artifact["size_bytes"] != spec.size_bytes:
        raise StoreConflictError("artifact completion metadata differs from reservation")
    response = await asyncio.to_thread(
        self._client.head_object,
        Bucket=artifact["bucket"],
        Key=artifact["object_key"],
        ChecksumMode="ENABLED",
    )
    actual_checksum = response.get("ChecksumSHA256")
    expected_checksum = base64.b64encode(bytes.fromhex(spec.sha256)).decode()
    actual_size = int(response["ContentLength"])
    if actual_size != spec.size_bytes or actual_checksum != expected_checksum:
        raise StoreConflictError("S3 object does not match reserved size and checksum")
    return await self._runtime_store.mark_artifact_available(
        job_id,
        spec.worker_id,
        spec.lease_id,
        artifact_id,
        actual_size=actual_size,
        actual_sha256=spec.sha256,
    )

sign_download async

sign_download(job_id: UUID, worker_id: str, lease_id: UUID, artifact_id: UUID) -> SignedArtifactURL

Sign a GET request only for an artifact in the leased mission.

Source code in agent_k/stores.py
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
async def sign_download(
    self,
    job_id: uuid.UUID,
    worker_id: str,
    lease_id: uuid.UUID,
    artifact_id: uuid.UUID,
) -> SignedArtifactURL:
    """Sign a GET request only for an artifact in the leased mission."""
    artifact = await self._runtime_store.get_artifact_for_download(
        job_id,
        worker_id,
        lease_id,
        artifact_id,
    )
    url = await asyncio.to_thread(
        self._client.generate_presigned_url,
        "get_object",
        Params={"Bucket": artifact["bucket"], "Key": artifact["object_key"]},
        ExpiresIn=self._url_ttl_seconds,
        HttpMethod="GET",
    )
    return SignedArtifactURL(
        artifact_id=artifact_id,
        method="GET",
        url=url,
        headers={},
        expires_at=datetime.now(UTC) + timedelta(seconds=self._url_ttl_seconds),
    )

create_migration_upload async

create_migration_upload(request: MigrationCreateRequest) -> MigrationCreateResponse

Create an idempotent, content-addressed legacy upload.

Source code in agent_k/stores.py
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
async def create_migration_upload(
    self,
    request: MigrationCreateRequest,
) -> MigrationCreateResponse:
    """Create an idempotent, content-addressed legacy upload."""
    migration_id = uuid.uuid4()
    suffix = "json" if request.source.kind is MigrationSourceKind.MISSION_STATE else "sqlite3"
    object_key = (
        f"migrations/{request.source.kind.value}/{request.source.sha256}/"
        f"{migration_id}.{suffix}"
    )
    migration = await self._runtime_store.create_migration_record(
        request,
        migration_id=migration_id,
        bucket=self._bucket,
        object_key=object_key,
    )
    checksum = base64.b64encode(bytes.fromhex(request.source.sha256)).decode()
    url = await asyncio.to_thread(
        self._client.generate_presigned_url,
        "put_object",
        Params={
            "Bucket": self._bucket,
            "Key": migration["object_key"],
            "ContentType": request.content_type,
            "ChecksumSHA256": checksum,
        },
        ExpiresIn=self._url_ttl_seconds,
        HttpMethod="PUT",
    )
    upload = SignedArtifactURL(
        artifact_id=migration["migration_id"],
        method="PUT",
        url=url,
        headers={
            "content-type": request.content_type,
            "x-amz-checksum-sha256": checksum,
        },
        expires_at=datetime.now(UTC) + timedelta(seconds=self._url_ttl_seconds),
    )
    return MigrationCreateResponse(migration_id=migration["migration_id"], upload=upload)

complete_migration_upload async

complete_migration_upload(migration_id: UUID, worker_id: str, sha256: str, size_bytes: int) -> MigrationRecord

Verify a legacy source in S3 before queueing its import.

Source code in agent_k/stores.py
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
async def complete_migration_upload(
    self,
    migration_id: uuid.UUID,
    worker_id: str,
    sha256: str,
    size_bytes: int,
) -> MigrationRecord:
    """Verify a legacy source in S3 before queueing its import."""
    migration = await self._runtime_store.get_migration_for_verification(
        migration_id,
        worker_id,
    )
    if migration["source_sha256"] != sha256 or migration["size_bytes"] != size_bytes:
        raise StoreConflictError("migration completion metadata differs from reservation")
    response = await asyncio.to_thread(
        self._client.head_object,
        Bucket=migration["bucket"],
        Key=migration["object_key"],
        ChecksumMode="ENABLED",
    )
    expected_checksum = base64.b64encode(bytes.fromhex(sha256)).decode()
    if (
        int(response["ContentLength"]) != size_bytes
        or response.get("ChecksumSHA256") != expected_checksum
    ):
        raise StoreConflictError("S3 migration object failed size or checksum validation")
    return await self._runtime_store.complete_migration_upload(
        migration_id,
        worker_id,
        sha256,
        size_bytes,
    )

download_claimed_migration async

download_claimed_migration(migration: dict[str, Any], destination: Path) -> None

Download and verify a migration held by a database processing lease.

Source code in agent_k/stores.py
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
async def download_claimed_migration(
    self,
    migration: dict[str, Any],
    destination: Path,
) -> None:
    """Download and verify a migration held by a database processing lease."""
    temporary = destination.with_name(f".{destination.name}.{uuid.uuid4().hex}.tmp")
    try:
        await asyncio.to_thread(
            self._client.download_file,
            migration["bucket"],
            migration["object_key"],
            str(temporary),
        )
        actual_size = temporary.stat().st_size
        actual_sha256 = await asyncio.to_thread(_file_sha256, temporary)
        if (
            actual_size != migration["size_bytes"]
            or actual_sha256 != migration["source_sha256"]
        ):
            raise StoreConflictError("downloaded migration source failed integrity validation")
        temporary.replace(destination)
    finally:
        temporary.unlink(missing_ok=True)

Worker API client and isolated process entrypoints.

(c) Mike Casale 2025. Licensed under the MIT License.

WorkerApiError

Bases: RuntimeError

Structured failure returned by the authenticated worker API.

Source code in agent_k/runner.py
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
class WorkerApiError(RuntimeError):
    """Structured failure returned by the authenticated worker API."""

    def __init__(
        self,
        code: str,
        message: str,
        *,
        retryable: bool,
        status_code: int,
        details: dict[str, Any] | None = None,
    ) -> None:
        super().__init__(message)
        self.code = code
        self.retryable = retryable
        self.status_code = status_code
        self.details = details

WorkerApiClient

Authenticated async client for fenced worker operations.

Source code in agent_k/runner.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
class WorkerApiClient:
    """Authenticated async client for fenced worker operations."""

    def __init__(
        self,
        base_url: str,
        worker_id: str,
        token: str,
        *,
        timeout_seconds: float = 30.0,
    ) -> None:
        if not base_url.startswith(("http://", "https://")):
            raise ValueError("base_url must be HTTP or HTTPS")
        if not worker_id or not token:
            raise ValueError("worker_id and token are required")
        self._worker_id = worker_id
        self._client = httpx.AsyncClient(
            base_url=base_url.rstrip("/"),
            headers={
                "Authorization": f"Bearer {token}",
                "X-Worker-Id": worker_id,
                "User-Agent": "agent-k-worker/1.0",
            },
            timeout=httpx.Timeout(timeout_seconds),
        )
        self._transfer_client = httpx.AsyncClient(
            timeout=httpx.Timeout(connect=30.0, read=3600.0, write=3600.0, pool=30.0)
        )

    @property
    def worker_id(self) -> str:
        """Return the identity bound to this client and its bearer token."""
        return self._worker_id

    async def __aenter__(self) -> WorkerApiClient:
        return self

    async def __aexit__(self, *_args: object) -> None:
        await self.close()

    async def close(self) -> None:
        """Release network connections held by the worker client."""
        await self._client.aclose()
        await self._transfer_client.aclose()

    async def claim_jobs(
        self,
        capabilities: tuple[str, ...],
        *,
        lease_seconds: int = 60,
        max_jobs: int = 1,
    ) -> ClaimJobsResponse:
        """Atomically claim available work from the runtime queue."""
        request = ClaimJobsRequest(
            worker_id=self.worker_id,
            capabilities=capabilities,
            lease_seconds=lease_seconds,
            max_jobs=max_jobs,
        )
        payload = await self._request_json(
            "POST",
            "/api/worker/v1/jobs/claim",
            json=request.model_dump(mode="json", by_alias=True),
        )
        return ClaimJobsResponse.model_validate(payload)

    async def heartbeat(
        self,
        lease: JobLease,
        *,
        progress: float | None = None,
        current_phase: str | None = None,
        current_task_id: str | None = None,
    ) -> HeartbeatResponse:
        """Renew a lease and read its current control directive."""
        request = HeartbeatRequest(
            worker_id=self.worker_id,
            lease_id=lease.lease_id,
            progress=progress,
            current_phase=current_phase,
            current_task_id=current_task_id,
        )
        payload = await self._request_json(
            "POST",
            f"/api/worker/v1/jobs/{lease.job_id}/heartbeat",
            json=request.model_dump(mode="json", by_alias=True, exclude_none=True),
        )
        return HeartbeatResponse.model_validate(payload)

    async def append_events(
        self,
        lease: JobLease,
        events: tuple[WorkerEvent, ...],
    ) -> AppendEventsReceipt:
        """Append a contiguous, idempotent event batch."""
        payload = await self._request_json(
            "POST",
            f"/api/worker/v1/jobs/{lease.job_id}/events",
            json={
                "workerId": self.worker_id,
                "leaseId": str(lease.lease_id),
                "events": [event.model_dump(mode="json", by_alias=True) for event in events],
            },
        )
        return AppendEventsReceipt.model_validate(payload)

    async def save_snapshot(
        self,
        lease: JobLease,
        snapshot: MissionSnapshot,
    ) -> SnapshotReceipt:
        """Save an immutable checkpoint under the current lease."""
        payload = await self._request_json(
            "POST",
            f"/api/worker/v1/jobs/{lease.job_id}/snapshots",
            json={
                "workerId": self.worker_id,
                "leaseId": str(lease.lease_id),
                "snapshot": snapshot.model_dump(mode="json", by_alias=True),
            },
        )
        return SnapshotReceipt.model_validate(payload)

    async def get_snapshot(
        self,
        lease: JobLease,
        snapshot_id: uuid.UUID,
    ) -> MissionSnapshotRecord:
        """Fetch a checkpoint and artifact references through the fenced lease."""
        payload = await self._request_json(
            "GET",
            f"/api/worker/v1/jobs/{lease.job_id}/snapshots/{snapshot_id}",
            params={"leaseId": str(lease.lease_id)},
        )
        return MissionSnapshotRecord.model_validate(payload)

    async def get_control(self, lease: JobLease) -> ControlDirective:
        """Read a pause or cancellation request without renewing the lease."""
        payload = await self._request_json(
            "GET",
            f"/api/worker/v1/jobs/{lease.job_id}/control",
            params={"leaseId": str(lease.lease_id)},
        )
        return ControlDirective.model_validate(payload)

    async def complete_job(
        self,
        lease: JobLease,
        result: MissionRunResult,
        *,
        idempotency_key: str,
    ) -> JobCompletionResponse:
        """Commit a successful mission after its durable terminal event."""
        request = JobCompletionRequest(
            worker_id=self.worker_id,
            lease_id=lease.lease_id,
            idempotency_key=idempotency_key,
            result=result,
            final_event_sequence=result.final_event_sequence,
            artifacts=result.artifacts,
        )
        payload = await self._request_json(
            "POST",
            f"/api/worker/v1/jobs/{lease.job_id}/complete",
            json=request.model_dump(mode="json", by_alias=True),
        )
        return JobCompletionResponse.model_validate(payload)

    async def fail_job(
        self,
        lease: JobLease,
        request: JobFailureRequest,
    ) -> JobFailureResponse:
        """Commit a structured failure or server-authorized retry."""
        payload = await self._request_json(
            "POST",
            f"/api/worker/v1/jobs/{lease.job_id}/fail",
            json=request.model_dump(mode="json", by_alias=True),
        )
        return JobFailureResponse.model_validate(payload)

    async def request_upload(
        self,
        lease: JobLease,
        path: Path,
        *,
        content_type: str,
        role: str,
    ) -> SignedArtifactURL:
        """Reserve an immutable object and obtain a checksum-bound S3 PUT URL."""
        size_bytes, sha256 = await asyncio.to_thread(_file_metadata, path)
        request = ArtifactUploadSpec(
            worker_id=self.worker_id,
            lease_id=lease.lease_id,
            name=path.name,
            content_type=content_type,
            size_bytes=size_bytes,
            sha256=sha256,
            role=role,
        )
        payload = await self._request_json(
            "POST",
            f"/api/worker/v1/jobs/{lease.job_id}/artifacts/upload-url",
            json=request.model_dump(mode="json", by_alias=True),
        )
        return SignedArtifactURL.model_validate(payload)

    async def upload_file(
        self,
        lease: JobLease,
        signed: SignedArtifactURL,
        path: Path,
        *,
        role: str,
    ) -> ArtifactReference:
        """Upload and server-verify a file without exposing S3 credentials."""
        size_bytes, sha256 = await asyncio.to_thread(_file_metadata, path)
        response = await self._transfer_client.put(
            signed.url,
            headers=signed.headers,
            content=_iter_file(path),
        )
        response.raise_for_status()
        payload = await self._request_json(
            "POST",
            (f"/api/worker/v1/jobs/{lease.job_id}/artifacts/{signed.artifact_id}/complete"),
            json={
                "workerId": self.worker_id,
                "leaseId": str(lease.lease_id),
                "sha256": sha256,
                "sizeBytes": size_bytes,
            },
        )
        response_id = ArtifactCompleteResponse.model_validate(payload).artifact_id
        if response_id != signed.artifact_id:
            raise WorkerApiError(
                "artifact_id_mismatch",
                "Artifact completion returned a different identifier",
                retryable=False,
                status_code=502,
            )
        return ArtifactReference(artifact_id=response_id, role=role)

    async def upload_signed_file(self, signed: SignedArtifactURL, path: Path) -> None:
        """Upload a checksum-bound source whose completion uses a separate endpoint."""
        response = await self._transfer_client.put(
            signed.url,
            headers=signed.headers,
            content=_iter_file(path),
        )
        response.raise_for_status()

    async def request_download(
        self,
        lease: JobLease,
        artifact_id: uuid.UUID,
    ) -> SignedArtifactURL:
        """Obtain a short-lived GET URL for an available mission artifact."""
        payload = await self._request_json(
            "POST",
            f"/api/worker/v1/jobs/{lease.job_id}/artifacts/{artifact_id}/download-url",
            json={"workerId": self.worker_id, "leaseId": str(lease.lease_id)},
        )
        return SignedArtifactURL.model_validate(payload)

    async def download_file(
        self,
        signed: SignedArtifactURL,
        destination: Path,
        *,
        expected_sha256: str,
        expected_size: int,
    ) -> None:
        """Download an artifact atomically and verify its immutable metadata."""
        temporary = destination.with_name(f".{destination.name}.{uuid.uuid4().hex}.tmp")
        digest = hashlib.sha256()
        size = 0
        try:
            async with self._transfer_client.stream(
                "GET",
                signed.url,
                headers=signed.headers,
            ) as response:
                response.raise_for_status()
                with temporary.open("xb") as target:
                    os.chmod(temporary, 0o600)
                    async for chunk in response.aiter_bytes(_CHUNK_SIZE):
                        size += len(chunk)
                        if size > expected_size:
                            raise WorkerApiError(
                                "artifact_size_mismatch",
                                "Downloaded artifact exceeded its expected size",
                                retryable=False,
                                status_code=502,
                            )
                        digest.update(chunk)
                        target.write(chunk)
            if size != expected_size or digest.hexdigest() != expected_sha256:
                raise WorkerApiError(
                    "artifact_integrity_mismatch",
                    "Downloaded artifact failed size or checksum validation",
                    retryable=False,
                    status_code=502,
                )
            temporary.replace(destination)
        finally:
            temporary.unlink(missing_ok=True)

    async def create_migration_upload(
        self,
        request: MigrationCreateRequest,
    ) -> MigrationCreateResponse:
        """Create a content-addressed legacy migration upload."""
        payload = await self._request_json(
            "POST",
            "/api/worker/v1/migrations",
            json=request.model_dump(mode="json", by_alias=True),
        )
        return MigrationCreateResponse.model_validate(payload)

    async def complete_migration_upload(
        self,
        migration_id: uuid.UUID,
        *,
        idempotency_key: str,
        sha256: str,
        size_bytes: int,
    ) -> MigrationRecord:
        """Confirm an uploaded migration source for asynchronous import."""
        payload = await self._request_json(
            "POST",
            f"/api/worker/v1/migrations/{migration_id}/complete",
            json={
                "workerId": self.worker_id,
                "idempotencyKey": idempotency_key,
                "sha256": sha256,
                "sizeBytes": size_bytes,
            },
        )
        return MigrationRecord.model_validate(payload)

    async def get_migration(self, migration_id: uuid.UUID) -> MigrationRecord:
        """Read one migration's asynchronous processing status."""
        payload = await self._request_json(
            "GET",
            f"/api/worker/v1/migrations/{migration_id}",
        )
        return MigrationRecord.model_validate(payload)

    async def _request_json(
        self,
        method: str,
        path: str,
        **kwargs: Any,
    ) -> dict[str, Any]:
        response = await self._client.request(method, path, **kwargs)
        try:
            payload = response.json()
        except ValueError as error:
            raise WorkerApiError(
                "invalid_worker_response",
                "Worker API returned a non-JSON response",
                retryable=response.status_code >= 500,
                status_code=response.status_code,
            ) from error
        if response.is_error:
            detail = payload.get("error", {}) if isinstance(payload, dict) else {}
            raise WorkerApiError(
                str(detail.get("code", "worker_api_error")),
                str(detail.get("message", "Worker API request failed")),
                retryable=bool(detail.get("retryable", response.status_code >= 500)),
                status_code=response.status_code,
                details=detail.get("details"),
            )
        if not isinstance(payload, dict):
            raise WorkerApiError(
                "invalid_worker_response",
                "Worker API returned an invalid JSON envelope",
                retryable=False,
                status_code=response.status_code,
            )
        return payload

worker_id property

worker_id: str

Return the identity bound to this client and its bearer token.

close async

close() -> None

Release network connections held by the worker client.

Source code in agent_k/runner.py
133
134
135
136
async def close(self) -> None:
    """Release network connections held by the worker client."""
    await self._client.aclose()
    await self._transfer_client.aclose()

claim_jobs async

claim_jobs(capabilities: tuple[str, ...], *, lease_seconds: int = 60, max_jobs: int = 1) -> ClaimJobsResponse

Atomically claim available work from the runtime queue.

Source code in agent_k/runner.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
async def claim_jobs(
    self,
    capabilities: tuple[str, ...],
    *,
    lease_seconds: int = 60,
    max_jobs: int = 1,
) -> ClaimJobsResponse:
    """Atomically claim available work from the runtime queue."""
    request = ClaimJobsRequest(
        worker_id=self.worker_id,
        capabilities=capabilities,
        lease_seconds=lease_seconds,
        max_jobs=max_jobs,
    )
    payload = await self._request_json(
        "POST",
        "/api/worker/v1/jobs/claim",
        json=request.model_dump(mode="json", by_alias=True),
    )
    return ClaimJobsResponse.model_validate(payload)

heartbeat async

heartbeat(lease: JobLease, *, progress: float | None = None, current_phase: str | None = None, current_task_id: str | None = None) -> HeartbeatResponse

Renew a lease and read its current control directive.

Source code in agent_k/runner.py
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
async def heartbeat(
    self,
    lease: JobLease,
    *,
    progress: float | None = None,
    current_phase: str | None = None,
    current_task_id: str | None = None,
) -> HeartbeatResponse:
    """Renew a lease and read its current control directive."""
    request = HeartbeatRequest(
        worker_id=self.worker_id,
        lease_id=lease.lease_id,
        progress=progress,
        current_phase=current_phase,
        current_task_id=current_task_id,
    )
    payload = await self._request_json(
        "POST",
        f"/api/worker/v1/jobs/{lease.job_id}/heartbeat",
        json=request.model_dump(mode="json", by_alias=True, exclude_none=True),
    )
    return HeartbeatResponse.model_validate(payload)

append_events async

append_events(lease: JobLease, events: tuple[WorkerEvent, ...]) -> AppendEventsReceipt

Append a contiguous, idempotent event batch.

Source code in agent_k/runner.py
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
async def append_events(
    self,
    lease: JobLease,
    events: tuple[WorkerEvent, ...],
) -> AppendEventsReceipt:
    """Append a contiguous, idempotent event batch."""
    payload = await self._request_json(
        "POST",
        f"/api/worker/v1/jobs/{lease.job_id}/events",
        json={
            "workerId": self.worker_id,
            "leaseId": str(lease.lease_id),
            "events": [event.model_dump(mode="json", by_alias=True) for event in events],
        },
    )
    return AppendEventsReceipt.model_validate(payload)

save_snapshot async

save_snapshot(lease: JobLease, snapshot: MissionSnapshot) -> SnapshotReceipt

Save an immutable checkpoint under the current lease.

Source code in agent_k/runner.py
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
async def save_snapshot(
    self,
    lease: JobLease,
    snapshot: MissionSnapshot,
) -> SnapshotReceipt:
    """Save an immutable checkpoint under the current lease."""
    payload = await self._request_json(
        "POST",
        f"/api/worker/v1/jobs/{lease.job_id}/snapshots",
        json={
            "workerId": self.worker_id,
            "leaseId": str(lease.lease_id),
            "snapshot": snapshot.model_dump(mode="json", by_alias=True),
        },
    )
    return SnapshotReceipt.model_validate(payload)

get_snapshot async

get_snapshot(lease: JobLease, snapshot_id: UUID) -> MissionSnapshotRecord

Fetch a checkpoint and artifact references through the fenced lease.

Source code in agent_k/runner.py
216
217
218
219
220
221
222
223
224
225
226
227
async def get_snapshot(
    self,
    lease: JobLease,
    snapshot_id: uuid.UUID,
) -> MissionSnapshotRecord:
    """Fetch a checkpoint and artifact references through the fenced lease."""
    payload = await self._request_json(
        "GET",
        f"/api/worker/v1/jobs/{lease.job_id}/snapshots/{snapshot_id}",
        params={"leaseId": str(lease.lease_id)},
    )
    return MissionSnapshotRecord.model_validate(payload)

get_control async

get_control(lease: JobLease) -> ControlDirective

Read a pause or cancellation request without renewing the lease.

Source code in agent_k/runner.py
229
230
231
232
233
234
235
236
async def get_control(self, lease: JobLease) -> ControlDirective:
    """Read a pause or cancellation request without renewing the lease."""
    payload = await self._request_json(
        "GET",
        f"/api/worker/v1/jobs/{lease.job_id}/control",
        params={"leaseId": str(lease.lease_id)},
    )
    return ControlDirective.model_validate(payload)

complete_job async

complete_job(lease: JobLease, result: MissionRunResult, *, idempotency_key: str) -> JobCompletionResponse

Commit a successful mission after its durable terminal event.

Source code in agent_k/runner.py
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
async def complete_job(
    self,
    lease: JobLease,
    result: MissionRunResult,
    *,
    idempotency_key: str,
) -> JobCompletionResponse:
    """Commit a successful mission after its durable terminal event."""
    request = JobCompletionRequest(
        worker_id=self.worker_id,
        lease_id=lease.lease_id,
        idempotency_key=idempotency_key,
        result=result,
        final_event_sequence=result.final_event_sequence,
        artifacts=result.artifacts,
    )
    payload = await self._request_json(
        "POST",
        f"/api/worker/v1/jobs/{lease.job_id}/complete",
        json=request.model_dump(mode="json", by_alias=True),
    )
    return JobCompletionResponse.model_validate(payload)

fail_job async

fail_job(lease: JobLease, request: JobFailureRequest) -> JobFailureResponse

Commit a structured failure or server-authorized retry.

Source code in agent_k/runner.py
261
262
263
264
265
266
267
268
269
270
271
272
async def fail_job(
    self,
    lease: JobLease,
    request: JobFailureRequest,
) -> JobFailureResponse:
    """Commit a structured failure or server-authorized retry."""
    payload = await self._request_json(
        "POST",
        f"/api/worker/v1/jobs/{lease.job_id}/fail",
        json=request.model_dump(mode="json", by_alias=True),
    )
    return JobFailureResponse.model_validate(payload)

request_upload async

request_upload(lease: JobLease, path: Path, *, content_type: str, role: str) -> SignedArtifactURL

Reserve an immutable object and obtain a checksum-bound S3 PUT URL.

Source code in agent_k/runner.py
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
async def request_upload(
    self,
    lease: JobLease,
    path: Path,
    *,
    content_type: str,
    role: str,
) -> SignedArtifactURL:
    """Reserve an immutable object and obtain a checksum-bound S3 PUT URL."""
    size_bytes, sha256 = await asyncio.to_thread(_file_metadata, path)
    request = ArtifactUploadSpec(
        worker_id=self.worker_id,
        lease_id=lease.lease_id,
        name=path.name,
        content_type=content_type,
        size_bytes=size_bytes,
        sha256=sha256,
        role=role,
    )
    payload = await self._request_json(
        "POST",
        f"/api/worker/v1/jobs/{lease.job_id}/artifacts/upload-url",
        json=request.model_dump(mode="json", by_alias=True),
    )
    return SignedArtifactURL.model_validate(payload)

upload_file async

upload_file(lease: JobLease, signed: SignedArtifactURL, path: Path, *, role: str) -> ArtifactReference

Upload and server-verify a file without exposing S3 credentials.

Source code in agent_k/runner.py
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
async def upload_file(
    self,
    lease: JobLease,
    signed: SignedArtifactURL,
    path: Path,
    *,
    role: str,
) -> ArtifactReference:
    """Upload and server-verify a file without exposing S3 credentials."""
    size_bytes, sha256 = await asyncio.to_thread(_file_metadata, path)
    response = await self._transfer_client.put(
        signed.url,
        headers=signed.headers,
        content=_iter_file(path),
    )
    response.raise_for_status()
    payload = await self._request_json(
        "POST",
        (f"/api/worker/v1/jobs/{lease.job_id}/artifacts/{signed.artifact_id}/complete"),
        json={
            "workerId": self.worker_id,
            "leaseId": str(lease.lease_id),
            "sha256": sha256,
            "sizeBytes": size_bytes,
        },
    )
    response_id = ArtifactCompleteResponse.model_validate(payload).artifact_id
    if response_id != signed.artifact_id:
        raise WorkerApiError(
            "artifact_id_mismatch",
            "Artifact completion returned a different identifier",
            retryable=False,
            status_code=502,
        )
    return ArtifactReference(artifact_id=response_id, role=role)

upload_signed_file async

upload_signed_file(signed: SignedArtifactURL, path: Path) -> None

Upload a checksum-bound source whose completion uses a separate endpoint.

Source code in agent_k/runner.py
336
337
338
339
340
341
342
343
async def upload_signed_file(self, signed: SignedArtifactURL, path: Path) -> None:
    """Upload a checksum-bound source whose completion uses a separate endpoint."""
    response = await self._transfer_client.put(
        signed.url,
        headers=signed.headers,
        content=_iter_file(path),
    )
    response.raise_for_status()

request_download async

request_download(lease: JobLease, artifact_id: UUID) -> SignedArtifactURL

Obtain a short-lived GET URL for an available mission artifact.

Source code in agent_k/runner.py
345
346
347
348
349
350
351
352
353
354
355
356
async def request_download(
    self,
    lease: JobLease,
    artifact_id: uuid.UUID,
) -> SignedArtifactURL:
    """Obtain a short-lived GET URL for an available mission artifact."""
    payload = await self._request_json(
        "POST",
        f"/api/worker/v1/jobs/{lease.job_id}/artifacts/{artifact_id}/download-url",
        json={"workerId": self.worker_id, "leaseId": str(lease.lease_id)},
    )
    return SignedArtifactURL.model_validate(payload)

download_file async

download_file(signed: SignedArtifactURL, destination: Path, *, expected_sha256: str, expected_size: int) -> None

Download an artifact atomically and verify its immutable metadata.

Source code in agent_k/runner.py
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
async def download_file(
    self,
    signed: SignedArtifactURL,
    destination: Path,
    *,
    expected_sha256: str,
    expected_size: int,
) -> None:
    """Download an artifact atomically and verify its immutable metadata."""
    temporary = destination.with_name(f".{destination.name}.{uuid.uuid4().hex}.tmp")
    digest = hashlib.sha256()
    size = 0
    try:
        async with self._transfer_client.stream(
            "GET",
            signed.url,
            headers=signed.headers,
        ) as response:
            response.raise_for_status()
            with temporary.open("xb") as target:
                os.chmod(temporary, 0o600)
                async for chunk in response.aiter_bytes(_CHUNK_SIZE):
                    size += len(chunk)
                    if size > expected_size:
                        raise WorkerApiError(
                            "artifact_size_mismatch",
                            "Downloaded artifact exceeded its expected size",
                            retryable=False,
                            status_code=502,
                        )
                    digest.update(chunk)
                    target.write(chunk)
        if size != expected_size or digest.hexdigest() != expected_sha256:
            raise WorkerApiError(
                "artifact_integrity_mismatch",
                "Downloaded artifact failed size or checksum validation",
                retryable=False,
                status_code=502,
            )
        temporary.replace(destination)
    finally:
        temporary.unlink(missing_ok=True)

create_migration_upload async

create_migration_upload(request: MigrationCreateRequest) -> MigrationCreateResponse

Create a content-addressed legacy migration upload.

Source code in agent_k/runner.py
401
402
403
404
405
406
407
408
409
410
411
async def create_migration_upload(
    self,
    request: MigrationCreateRequest,
) -> MigrationCreateResponse:
    """Create a content-addressed legacy migration upload."""
    payload = await self._request_json(
        "POST",
        "/api/worker/v1/migrations",
        json=request.model_dump(mode="json", by_alias=True),
    )
    return MigrationCreateResponse.model_validate(payload)

complete_migration_upload async

complete_migration_upload(migration_id: UUID, *, idempotency_key: str, sha256: str, size_bytes: int) -> MigrationRecord

Confirm an uploaded migration source for asynchronous import.

Source code in agent_k/runner.py
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
async def complete_migration_upload(
    self,
    migration_id: uuid.UUID,
    *,
    idempotency_key: str,
    sha256: str,
    size_bytes: int,
) -> MigrationRecord:
    """Confirm an uploaded migration source for asynchronous import."""
    payload = await self._request_json(
        "POST",
        f"/api/worker/v1/migrations/{migration_id}/complete",
        json={
            "workerId": self.worker_id,
            "idempotencyKey": idempotency_key,
            "sha256": sha256,
            "sizeBytes": size_bytes,
        },
    )
    return MigrationRecord.model_validate(payload)

get_migration async

get_migration(migration_id: UUID) -> MigrationRecord

Read one migration's asynchronous processing status.

Source code in agent_k/runner.py
434
435
436
437
438
439
440
async def get_migration(self, migration_id: uuid.UUID) -> MigrationRecord:
    """Read one migration's asynchronous processing status."""
    payload = await self._request_json(
        "GET",
        f"/api/worker/v1/migrations/{migration_id}",
    )
    return MigrationRecord.model_validate(payload)

main

main(argv: list[str] | None = None) -> int

Run the candidate or mission child-process entrypoint.

Source code in agent_k/runner.py
574
575
576
577
578
579
def main(argv: list[str] | None = None) -> int:
    """Run the candidate or mission child-process entrypoint."""
    arguments = _parser().parse_args(argv)
    if arguments.command == "candidate":
        return asyncio.run(_run_candidate(arguments.spec, arguments.output))
    return asyncio.run(_run_mission(arguments.job, arguments.output))

Portable worker that executes fenced missions in fresh subprocesses.

(c) Mike Casale 2025. Licensed under the MIT License.

WorkerSettings

Bases: BaseModel

Validated worker process configuration sourced from environment variables.

Source code in agent_k/worker.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
class WorkerSettings(BaseModel):
    """Validated worker process configuration sourced from environment variables."""

    model_config = ConfigDict(extra="forbid", frozen=True)

    api_url: str
    worker_id: str = Field(min_length=1, max_length=200)
    worker_token: str = Field(min_length=16, repr=False)
    capabilities: tuple[str, ...] = ()
    work_root: Path
    sandbox_image: str
    gpu_devices: tuple[str, ...] = ()
    lease_seconds: int = Field(default=60, ge=30, le=3600)
    heartbeat_seconds: float = Field(default=15.0, ge=2.0, le=300.0)
    poll_seconds: float = Field(default=5.0, ge=0.5, le=60.0)
    control_grace_seconds: float = Field(default=300.0, ge=30.0, le=3600.0)
    shutdown_grace_seconds: float = Field(default=60.0, ge=5.0, le=600.0)
    environment: str = "production"

    @field_validator("api_url")
    @classmethod
    def validate_api_url(cls, value: str) -> str:
        """Require an explicit HTTP worker API endpoint."""
        if not value.startswith(("http://", "https://")):
            raise ValueError("api_url must be HTTP or HTTPS")
        return value.rstrip("/")

    @field_validator("work_root")
    @classmethod
    def validate_work_root(cls, value: Path) -> Path:
        """Reject broad or implicit worker workspace roots."""
        resolved = value.expanduser().resolve()
        if resolved in {Path("/"), Path.home().resolve()}:
            raise ValueError("work_root must be a dedicated subdirectory")
        return resolved

    @model_validator(mode="after")
    def validate_heartbeat_interval(self) -> WorkerSettings:
        """Keep two heartbeat opportunities inside every configured lease."""
        if self.heartbeat_seconds * 2 >= self.lease_seconds:
            raise ValueError("heartbeat_seconds must be less than half of lease_seconds")
        return self

    @classmethod
    def from_environment(cls) -> WorkerSettings:
        """Load worker settings without accepting storage or database credentials."""
        capabilities = tuple(
            item.strip()
            for item in os.environ.get("AGENT_K_WORKER_CAPABILITIES", "cpu").split(",")
            if item.strip()
        )
        gpu_value = json.loads(os.environ.get("AGENT_K_GPU_DEVICES", "[]"))
        if not isinstance(gpu_value, list) or any(not isinstance(item, str) for item in gpu_value):
            raise ValueError("AGENT_K_GPU_DEVICES must be a JSON array of device identifiers")
        return cls(
            api_url=os.environ["AGENT_K_API_URL"],
            worker_id=os.environ["AGENT_K_WORKER_ID"],
            worker_token=os.environ["AGENT_K_WORKER_TOKEN"],
            capabilities=capabilities,
            work_root=Path(os.environ["AGENT_K_WORK_ROOT"]),
            sandbox_image=os.environ["AGENT_K_SANDBOX_IMAGE"],
            gpu_devices=tuple(gpu_value),
            lease_seconds=int(os.environ.get("AGENT_K_LEASE_SECONDS", "60")),
            heartbeat_seconds=float(os.environ.get("AGENT_K_HEARTBEAT_SECONDS", "15")),
            poll_seconds=float(os.environ.get("AGENT_K_POLL_SECONDS", "5")),
            control_grace_seconds=float(os.environ.get("AGENT_K_CONTROL_GRACE_SECONDS", "300")),
            shutdown_grace_seconds=float(os.environ.get("AGENT_K_SHUTDOWN_GRACE_SECONDS", "60")),
            environment=os.environ.get("AGENT_K_ENVIRONMENT", "production"),
        )

validate_api_url classmethod

validate_api_url(value: str) -> str

Require an explicit HTTP worker API endpoint.

Source code in agent_k/worker.py
104
105
106
107
108
109
110
@field_validator("api_url")
@classmethod
def validate_api_url(cls, value: str) -> str:
    """Require an explicit HTTP worker API endpoint."""
    if not value.startswith(("http://", "https://")):
        raise ValueError("api_url must be HTTP or HTTPS")
    return value.rstrip("/")

validate_work_root classmethod

validate_work_root(value: Path) -> Path

Reject broad or implicit worker workspace roots.

Source code in agent_k/worker.py
112
113
114
115
116
117
118
119
@field_validator("work_root")
@classmethod
def validate_work_root(cls, value: Path) -> Path:
    """Reject broad or implicit worker workspace roots."""
    resolved = value.expanduser().resolve()
    if resolved in {Path("/"), Path.home().resolve()}:
        raise ValueError("work_root must be a dedicated subdirectory")
    return resolved

validate_heartbeat_interval

validate_heartbeat_interval() -> WorkerSettings

Keep two heartbeat opportunities inside every configured lease.

Source code in agent_k/worker.py
121
122
123
124
125
126
@model_validator(mode="after")
def validate_heartbeat_interval(self) -> WorkerSettings:
    """Keep two heartbeat opportunities inside every configured lease."""
    if self.heartbeat_seconds * 2 >= self.lease_seconds:
        raise ValueError("heartbeat_seconds must be less than half of lease_seconds")
    return self

from_environment classmethod

from_environment() -> WorkerSettings

Load worker settings without accepting storage or database credentials.

Source code in agent_k/worker.py
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
@classmethod
def from_environment(cls) -> WorkerSettings:
    """Load worker settings without accepting storage or database credentials."""
    capabilities = tuple(
        item.strip()
        for item in os.environ.get("AGENT_K_WORKER_CAPABILITIES", "cpu").split(",")
        if item.strip()
    )
    gpu_value = json.loads(os.environ.get("AGENT_K_GPU_DEVICES", "[]"))
    if not isinstance(gpu_value, list) or any(not isinstance(item, str) for item in gpu_value):
        raise ValueError("AGENT_K_GPU_DEVICES must be a JSON array of device identifiers")
    return cls(
        api_url=os.environ["AGENT_K_API_URL"],
        worker_id=os.environ["AGENT_K_WORKER_ID"],
        worker_token=os.environ["AGENT_K_WORKER_TOKEN"],
        capabilities=capabilities,
        work_root=Path(os.environ["AGENT_K_WORK_ROOT"]),
        sandbox_image=os.environ["AGENT_K_SANDBOX_IMAGE"],
        gpu_devices=tuple(gpu_value),
        lease_seconds=int(os.environ.get("AGENT_K_LEASE_SECONDS", "60")),
        heartbeat_seconds=float(os.environ.get("AGENT_K_HEARTBEAT_SECONDS", "15")),
        poll_seconds=float(os.environ.get("AGENT_K_POLL_SECONDS", "5")),
        control_grace_seconds=float(os.environ.get("AGENT_K_CONTROL_GRACE_SECONDS", "300")),
        shutdown_grace_seconds=float(os.environ.get("AGENT_K_SHUTDOWN_GRACE_SECONDS", "60")),
        environment=os.environ.get("AGENT_K_ENVIRONMENT", "production"),
    )

run_worker async

run_worker(settings: WorkerSettings) -> None

Poll the authenticated queue and run one fenced mission at a time.

Source code in agent_k/worker.py
167
168
169
170
171
172
173
174
175
176
async def run_worker(settings: WorkerSettings) -> None:
    """Poll the authenticated queue and run one fenced mission at a time."""
    settings.work_root.mkdir(mode=0o700, parents=True, exist_ok=True)
    os.chmod(settings.work_root, 0o700)
    lock_descriptor = _acquire_worker_lock(settings.work_root)
    try:
        await _run_locked_worker(settings)
    finally:
        fcntl.flock(lock_descriptor, fcntl.LOCK_UN)
        os.close(lock_descriptor)

loop_time

loop_time() -> float

Return the running loop's monotonic clock for control deadlines.

Source code in agent_k/worker.py
509
510
511
def loop_time() -> float:
    """Return the running loop's monotonic clock for control deadlines."""
    return asyncio.get_running_loop().time()

main

main(argv: list[str] | None = None) -> int

Start the portable worker using its validated environment contract.

Source code in agent_k/worker.py
527
528
529
530
531
532
533
def main(argv: list[str] | None = None) -> int:
    """Start the portable worker using its validated environment contract."""
    _parser().parse_args(argv)
    settings = WorkerSettings.from_environment()
    configure_observability(service_name="agent-k-worker", environment=settings.environment)
    asyncio.run(run_worker(settings))
    return 0

Rootless Docker isolation for untrusted candidate programs.

(c) Mike Casale 2025. Licensed under the MIT License.

SandboxError

Bases: RuntimeError

Raised when candidate isolation or execution fails closed.

Source code in agent_k/sandbox.py
82
83
class SandboxError(RuntimeError):
    """Raised when candidate isolation or execution fails closed."""

SandboxLimits

Bases: BaseModel

Hard resource limits applied to one candidate container.

Source code in agent_k/sandbox.py
86
87
88
89
90
91
92
93
94
95
96
class SandboxLimits(BaseModel):
    """Hard resource limits applied to one candidate container."""

    model_config = ConfigDict(extra="forbid", frozen=True)

    cpus: float = Field(default=1.0, gt=0.0, le=64.0)
    memory_bytes: int = Field(default=2 * 1024**3, ge=256 * 1024**2)
    pids: int = Field(default=128, ge=16, le=4096)
    output_bytes: int = Field(default=512 * 1024**2, ge=1024**2)
    temporary_bytes: int = Field(default=512 * 1024**2, ge=16 * 1024**2)
    wall_seconds: float = Field(default=900.0, gt=0.0, le=86_400.0)

SandboxRequest

Bases: BaseModel

Inputs for one secretless candidate execution.

Source code in agent_k/sandbox.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
class SandboxRequest(BaseModel):
    """Inputs for one secretless candidate execution."""

    model_config = ConfigDict(
        extra="forbid",
        frozen=True,
        arbitrary_types_allowed=True,
        validate_default=True,
    )

    image: str
    input_root: Path
    output_root: Path
    candidate_program: Path | None = None
    offline_assets: dict[str, Path] = Field(default_factory=dict)
    gpu_devices: tuple[str, ...] = ()
    environment: dict[str, str] = Field(default_factory=dict)
    limits: SandboxLimits = Field(default_factory=SandboxLimits)
    lease_owner: uuid.UUID = Field(default_factory=_lease_owner_from_environment)
    worker_owner: str = Field(default_factory=_worker_owner_from_environment)

    @field_validator("image")
    @classmethod
    def validate_image(cls, value: str) -> str:
        """Require an immutable OCI digest rather than a mutable tag."""
        if not _DIGESTED_IMAGE.fullmatch(value):
            raise ValueError("image must be pinned with an immutable sha256 digest")
        return value

    @field_validator("offline_assets")
    @classmethod
    def validate_assets(cls, value: dict[str, Path]) -> dict[str, Path]:
        """Restrict asset names to safe single path components."""
        if any(not _SAFE_ASSET_NAME.fullmatch(name) for name in value):
            raise ValueError("offline asset names must be safe lowercase path components")
        return value

    @field_validator("environment")
    @classmethod
    def validate_environment(cls, value: dict[str, str]) -> dict[str, str]:
        """Permit only non-secret runtime tuning variables."""
        for name, setting in value.items():
            if name not in _SAFE_ENVIRONMENT or _SECRET_NAME.search(name):
                raise ValueError(f"environment variable is not candidate-safe: {name}")
            if "\x00" in setting or "\n" in setting:
                raise ValueError(f"environment variable contains unsafe bytes: {name}")
        return value

    @field_validator("gpu_devices")
    @classmethod
    def validate_gpu_devices(cls, value: tuple[str, ...]) -> tuple[str, ...]:
        """Allow only explicit NVIDIA indices, GPU UUIDs, or MIG device UUIDs."""
        if len(value) != len(set(value)) or any(not _GPU_DEVICE.fullmatch(item) for item in value):
            raise ValueError("gpu_devices must contain unique explicit NVIDIA device identifiers")
        return value

    @field_validator("worker_owner")
    @classmethod
    def validate_worker_owner(cls, value: str) -> str:
        """Require the trusted worker's stable, non-secret ownership token."""
        if not _OWNER_TOKEN.fullmatch(value):
            raise ValueError("worker_owner must be a 64-character lowercase hexadecimal token")
        return value

    @model_validator(mode="after")
    def validate_paths(self) -> SandboxRequest:
        """Require distinct, existing host paths for all mounts."""
        input_root = self.input_root.resolve(strict=True)
        output_root = self.output_root.resolve(strict=True)
        if not input_root.is_dir() or not output_root.is_dir():
            raise ValueError("input_root and output_root must be directories")
        if input_root == output_root or input_root in output_root.parents:
            raise ValueError("output_root must not be inside input_root")
        if output_root in input_root.parents:
            raise ValueError("input_root must not be inside output_root")
        if self.candidate_program is not None:
            program = self.candidate_program.resolve(strict=True)
            if not program.is_file() or program.suffix != ".py":
                raise ValueError("candidate_program must be an existing Python file")
        for asset in self.offline_assets.values():
            if not asset.resolve(strict=True).exists():
                raise ValueError(f"offline asset does not exist: {asset}")
        return self

validate_image classmethod

validate_image(value: str) -> str

Require an immutable OCI digest rather than a mutable tag.

Source code in agent_k/sandbox.py
120
121
122
123
124
125
126
@field_validator("image")
@classmethod
def validate_image(cls, value: str) -> str:
    """Require an immutable OCI digest rather than a mutable tag."""
    if not _DIGESTED_IMAGE.fullmatch(value):
        raise ValueError("image must be pinned with an immutable sha256 digest")
    return value

validate_assets classmethod

validate_assets(value: dict[str, Path]) -> dict[str, Path]

Restrict asset names to safe single path components.

Source code in agent_k/sandbox.py
128
129
130
131
132
133
134
@field_validator("offline_assets")
@classmethod
def validate_assets(cls, value: dict[str, Path]) -> dict[str, Path]:
    """Restrict asset names to safe single path components."""
    if any(not _SAFE_ASSET_NAME.fullmatch(name) for name in value):
        raise ValueError("offline asset names must be safe lowercase path components")
    return value

validate_environment classmethod

validate_environment(value: dict[str, str]) -> dict[str, str]

Permit only non-secret runtime tuning variables.

Source code in agent_k/sandbox.py
136
137
138
139
140
141
142
143
144
145
@field_validator("environment")
@classmethod
def validate_environment(cls, value: dict[str, str]) -> dict[str, str]:
    """Permit only non-secret runtime tuning variables."""
    for name, setting in value.items():
        if name not in _SAFE_ENVIRONMENT or _SECRET_NAME.search(name):
            raise ValueError(f"environment variable is not candidate-safe: {name}")
        if "\x00" in setting or "\n" in setting:
            raise ValueError(f"environment variable contains unsafe bytes: {name}")
    return value

validate_gpu_devices classmethod

validate_gpu_devices(value: tuple[str, ...]) -> tuple[str, ...]

Allow only explicit NVIDIA indices, GPU UUIDs, or MIG device UUIDs.

Source code in agent_k/sandbox.py
147
148
149
150
151
152
153
@field_validator("gpu_devices")
@classmethod
def validate_gpu_devices(cls, value: tuple[str, ...]) -> tuple[str, ...]:
    """Allow only explicit NVIDIA indices, GPU UUIDs, or MIG device UUIDs."""
    if len(value) != len(set(value)) or any(not _GPU_DEVICE.fullmatch(item) for item in value):
        raise ValueError("gpu_devices must contain unique explicit NVIDIA device identifiers")
    return value

validate_worker_owner classmethod

validate_worker_owner(value: str) -> str

Require the trusted worker's stable, non-secret ownership token.

Source code in agent_k/sandbox.py
155
156
157
158
159
160
161
@field_validator("worker_owner")
@classmethod
def validate_worker_owner(cls, value: str) -> str:
    """Require the trusted worker's stable, non-secret ownership token."""
    if not _OWNER_TOKEN.fullmatch(value):
        raise ValueError("worker_owner must be a 64-character lowercase hexadecimal token")
    return value

validate_paths

validate_paths() -> SandboxRequest

Require distinct, existing host paths for all mounts.

Source code in agent_k/sandbox.py
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
@model_validator(mode="after")
def validate_paths(self) -> SandboxRequest:
    """Require distinct, existing host paths for all mounts."""
    input_root = self.input_root.resolve(strict=True)
    output_root = self.output_root.resolve(strict=True)
    if not input_root.is_dir() or not output_root.is_dir():
        raise ValueError("input_root and output_root must be directories")
    if input_root == output_root or input_root in output_root.parents:
        raise ValueError("output_root must not be inside input_root")
    if output_root in input_root.parents:
        raise ValueError("input_root must not be inside output_root")
    if self.candidate_program is not None:
        program = self.candidate_program.resolve(strict=True)
        if not program.is_file() or program.suffix != ".py":
            raise ValueError("candidate_program must be an existing Python file")
    for asset in self.offline_assets.values():
        if not asset.resolve(strict=True).exists():
            raise ValueError(f"offline asset does not exist: {asset}")
    return self

SandboxResult

Bases: BaseModel

Auditable process outcome from an isolated candidate container.

Source code in agent_k/sandbox.py
184
185
186
187
188
189
190
191
192
193
194
195
class SandboxResult(BaseModel):
    """Auditable process outcome from an isolated candidate container."""

    model_config = ConfigDict(extra="forbid", frozen=True)

    container_name: str
    exit_code: int
    timed_out: bool = False
    output_limit_exceeded: bool = False
    oom_killed: bool = False
    stdout: str = ""
    stderr: str = ""

run_candidate_sandbox async

run_candidate_sandbox(request: SandboxRequest) -> SandboxResult

Run one baseline or evolved candidate in a fresh rootless Docker container.

Source code in agent_k/sandbox.py
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
async def run_candidate_sandbox(request: SandboxRequest) -> SandboxResult:
    """Run one baseline or evolved candidate in a fresh rootless Docker container."""
    docker = shutil.which("docker")
    if docker is None:
        raise SandboxError("docker CLI is required for candidate execution")
    await _require_rootless_docker(docker)
    _clear_output_root(request.output_root)
    container_name = f"agent-k-candidate-{uuid.uuid4().hex}"
    command = _docker_create_command(docker, container_name, request)
    created = await _run_control_command(command)
    if created[0] != 0:
        raise SandboxError(_control_error("docker create", created[2]))

    process: asyncio.subprocess.Process | None = None
    timed_out = False
    output_limit_exceeded = False
    try:
        process = await asyncio.create_subprocess_exec(
            docker,
            "start",
            "--attach",
            container_name,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE,
            start_new_session=True,
        )
        stdout_task = asyncio.create_task(_read_bounded(process.stdout))
        stderr_task = asyncio.create_task(_read_bounded(process.stderr))
        monitor_task = asyncio.create_task(_monitor_output(request.output_root, request.limits))
        wait_task = asyncio.create_task(process.wait())
        done, _pending = await asyncio.wait(
            {wait_task, monitor_task},
            timeout=request.limits.wall_seconds,
            return_when=asyncio.FIRST_COMPLETED,
        )
        if not done:
            timed_out = True
            await _kill_container(docker, container_name)
            await process.wait()
        elif monitor_task in done and monitor_task.result():
            output_limit_exceeded = True
            await _kill_container(docker, container_name)
            if process.returncode is None:
                await process.wait()
        if not wait_task.done():
            wait_task.cancel()
            with contextlib.suppress(asyncio.CancelledError):
                await wait_task
        monitor_task.cancel()
        with contextlib.suppress(asyncio.CancelledError):
            await monitor_task
        if (
            await asyncio.to_thread(_directory_size, request.output_root)
            > request.limits.output_bytes
        ):
            output_limit_exceeded = True
        stdout = await stdout_task
        stderr = await stderr_task
        inspection = await _inspect_container(docker, container_name)
        return SandboxResult(
            container_name=container_name,
            exit_code=process.returncode if process.returncode is not None else 125,
            timed_out=timed_out,
            output_limit_exceeded=output_limit_exceeded,
            oom_killed=inspection,
            stdout=stdout,
            stderr=stderr,
        )
    except asyncio.CancelledError:
        if process is not None and process.returncode is None:
            os.killpg(process.pid, signal.SIGKILL)
        await _kill_container(docker, container_name)
        raise
    finally:
        await _remove_container(docker, container_name)

run_candidate_sandbox_sync

run_candidate_sandbox_sync(request: SandboxRequest) -> SandboxResult

Run an isolated candidate from a synchronous evaluator process.

Source code in agent_k/sandbox.py
275
276
277
278
279
280
281
def run_candidate_sandbox_sync(request: SandboxRequest) -> SandboxResult:
    """Run an isolated candidate from a synchronous evaluator process."""
    try:
        asyncio.get_running_loop()
    except RuntimeError:
        return asyncio.run(run_candidate_sandbox(request))
    raise SandboxError("sync sandbox helper cannot run inside an active event loop")

validate_sandbox_runtime async

validate_sandbox_runtime(image: str, *, gpu_devices: tuple[str, ...] = ()) -> None

Fail worker startup unless its rootless daemon and pinned image are ready.

Source code in agent_k/sandbox.py
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
async def validate_sandbox_runtime(
    image: str,
    *,
    gpu_devices: tuple[str, ...] = (),
) -> None:
    """Fail worker startup unless its rootless daemon and pinned image are ready."""
    if not _DIGESTED_IMAGE.fullmatch(image):
        raise SandboxError("sandbox image must be pinned with an immutable sha256 digest")
    docker = shutil.which("docker")
    if docker is None:
        raise SandboxError("docker CLI is required for candidate execution")
    await _require_rootless_docker(docker)
    code, _stdout, stderr = await _run_control_command([docker, "image", "inspect", image])
    if code != 0:
        raise SandboxError(_control_error("docker image inspect", stderr))
    if gpu_devices:
        if len(gpu_devices) != len(set(gpu_devices)) or any(
            not _GPU_DEVICE.fullmatch(item) for item in gpu_devices
        ):
            raise SandboxError("GPU devices must be unique explicit NVIDIA identifiers")
        code, runtimes, stderr = await _run_control_command(
            [docker, "info", "--format", "{{json .Runtimes}}"]
        )
        if code != 0:
            raise SandboxError(_control_error("docker runtime inspection", stderr))
        if "nvidia" not in runtimes.lower():
            raise SandboxError("configured GPU devices require the NVIDIA container runtime")

remove_owned_sandbox_containers async

remove_owned_sandbox_containers(worker_owner: str, *, lease_owner: UUID | None = None) -> None

Force-remove only AGENT-K containers owned by one locked worker workspace.

Source code in agent_k/sandbox.py
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
async def remove_owned_sandbox_containers(
    worker_owner: str,
    *,
    lease_owner: uuid.UUID | None = None,
) -> None:
    """Force-remove only AGENT-K containers owned by one locked worker workspace."""
    if not _OWNER_TOKEN.fullmatch(worker_owner):
        raise SandboxError("worker sandbox ownership token is invalid")
    docker = shutil.which("docker")
    if docker is None:
        raise SandboxError("docker CLI is required for candidate cleanup")
    command = _owned_container_query(docker, worker_owner, lease_owner)
    code, stdout, stderr = await _run_control_command(command)
    if code != 0:
        raise SandboxError(_control_error("docker owned-container listing", stderr))
    for container_id in stdout.splitlines():
        code, _stdout, stderr = await _run_control_command([docker, "rm", "--force", container_id])
        if code != 0:
            raise SandboxError(_control_error("docker owned-container removal", stderr))

Read-only legacy inventory, upload, and idempotent import commands.

(c) Mike Casale 2025. Licensed under the MIT License.

LegacyInspection

Bases: BaseModel

Content-safe dry-run report for a legacy AGENT-K root.

Source code in agent_k/migration.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
class LegacyInspection(BaseModel):
    """Content-safe dry-run report for a legacy AGENT-K root."""

    model_config = ConfigDict(extra="forbid", frozen=True)

    schema_version: str = "1.0"
    mission_state_files: int = Field(ge=0)
    mission_ids: int = Field(ge=0)
    bare_node_ids: tuple[str, ...]
    completed_phase_claims: dict[str, int]
    experiment_rows: int = Field(ge=0)
    hint_attempt_rows: int = Field(ge=0)
    submission_history_rows: int = Field(ge=0)
    experiment_database_sha256: str | None = None
    warnings: tuple[str, ...] = ()

inspect_legacy_root

inspect_legacy_root(legacy_root: Path) -> LegacyInspection

Inspect legacy files without modifying or exposing their payloads.

Source code in agent_k/migration.py
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
def inspect_legacy_root(legacy_root: Path) -> LegacyInspection:
    """Inspect legacy files without modifying or exposing their payloads."""
    root = _validate_legacy_root(legacy_root)
    states = _read_legacy_states(root)
    node_ids = sorted(
        {
            str(item["id"])
            for entry in states
            for item in entry["graphSnapshot"]
            if isinstance(item, dict) and isinstance(item.get("id"), str)
        }
    )
    phase_counts: dict[str, int] = {}
    for entry in states:
        for phase in entry["legacyState"].get("phases_completed", []):
            name = str(phase)
            phase_counts[name] = phase_counts.get(name, 0) + 1
    database = root / "experiments" / "experiments.sqlite"
    counts = {table: 0 for table in _EXPERIMENT_TABLES}
    digest = None
    warnings: list[str] = []
    if database.is_file():
        counts = _sqlite_counts(database)
        digest = _sha256(database)
    else:
        warnings.append("experiment database not found")
    return LegacyInspection(
        mission_state_files=len(states),
        mission_ids=len({entry["legacyMissionId"] for entry in states}),
        bare_node_ids=tuple(node_ids),
        completed_phase_claims=dict(sorted(phase_counts.items())),
        experiment_rows=counts["experiments"],
        hint_attempt_rows=counts["hint_attempts"],
        submission_history_rows=counts["kaggle_submissions"],
        experiment_database_sha256=digest,
        warnings=tuple(warnings),
    )

upload_legacy_sources async

upload_legacy_sources(legacy_root: Path, *, owner_id: str, client: WorkerApiClient) -> tuple[UUID, ...]

Upload immutable legacy sources through scoped S3 URLs for later import.

Source code in agent_k/migration.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
async def upload_legacy_sources(
    legacy_root: Path,
    *,
    owner_id: str,
    client: WorkerApiClient,
) -> tuple[uuid.UUID, ...]:
    """Upload immutable legacy sources through scoped S3 URLs for later import."""
    if not owner_id.strip():
        raise ValueError("owner_id is required to attach imported missions safely")
    root = _validate_legacy_root(legacy_root)
    migration_ids: list[uuid.UUID] = []
    with tempfile.TemporaryDirectory(prefix="agent-k-migration-") as temporary_name:
        temporary = Path(temporary_name)
        state_bundle = temporary / "mission-states.json"
        _write_state_bundle(root, owner_id, state_bundle)
        migration_ids.append(
            await _upload_source(
                client,
                state_bundle,
                kind=MigrationSourceKind.MISSION_STATE,
                schema_version=_MISSION_STATE_SCHEMA,
                content_type="application/json",
            )
        )
        database = root / "experiments" / "experiments.sqlite"
        if database.is_file():
            database_backup = temporary / "experiments.sqlite"
            _backup_sqlite(database, database_backup)
            _validate_sqlite(database_backup)
            migration_ids.append(
                await _upload_source(
                    client,
                    database_backup,
                    kind=MigrationSourceKind.EXPERIMENT_DB,
                    schema_version="legacy-sqlite-v1",
                    content_type="application/x-sqlite3",
                )
            )
    return tuple(migration_ids)

process_migration async

process_migration(migration_id: UUID, *, store: PostgresRuntimeStore, artifacts: S3ArtifactStore, work_root: Path) -> dict[str, int]

Claim and transactionally import one S3-verified queued migration.

Source code in agent_k/migration.py
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
async def process_migration(
    migration_id: uuid.UUID,
    *,
    store: PostgresRuntimeStore,
    artifacts: S3ArtifactStore,
    work_root: Path,
) -> dict[str, int]:
    """Claim and transactionally import one S3-verified queued migration."""
    work_root.mkdir(mode=0o700, parents=True, exist_ok=True)
    claimed = await store.claim_migration(migration_id)
    token = claimed["processing_token"]
    suffix = ".json" if claimed["source_kind"] == "mission-state" else ".sqlite3"
    source = work_root / f"{migration_id}{suffix}"
    try:
        await artifacts.download_claimed_migration(claimed, source)
        if claimed["source_kind"] == "mission-state":
            mission_states = _migration_mission_records(source, claimed["source_sha256"])
            return await store.complete_legacy_import(
                migration_id,
                token,
                mission_states=mission_states,
            )
        experiments, hints, submissions = _migration_database_records(source)
        return await store.complete_legacy_import(
            migration_id,
            token,
            experiments=experiments,
            hints=hints,
            submissions=submissions,
        )
    except Exception:
        failure = JobFailure(
            code="legacy_import_failed",
            message="Legacy source failed structural validation or transactional import",
            retryable=False,
            category="migration",
        )
        await store.fail_migration_import(migration_id, token, failure)
        raise
    finally:
        source.unlink(missing_ok=True)

main

main(argv: list[str] | None = None) -> int

Inspect, upload, or explicitly process legacy sources.

Source code in agent_k/migration.py
484
485
486
487
488
489
490
491
492
493
def main(argv: list[str] | None = None) -> int:
    """Inspect, upload, or explicitly process legacy sources."""
    arguments = _parser().parse_args(argv)
    if arguments.command == "inspect":
        report = inspect_legacy_root(arguments.legacy_root)
        print(report.model_dump_json(by_alias=True))
        return 0
    if arguments.command == "upload":
        return asyncio.run(_upload_command(arguments))
    return asyncio.run(_process_command(arguments))