# Attest that an operator cleared a printer

This is the partner flow behind `printers.attestOperatorReady`. Most
integrations do not need it. It serves production partners, such as Printie,
whose floor staff confirm that a printer's bed is clear before Print Hive sends
it more work. For install, API keys, and your first print, read the
[quickstart](https://www.npmjs.com/package/@printhive/api). This file ships in
the package as `node_modules/@printhive/api/docs/partner-operator-ready.md`.

`POST /v1/printers/operator-ready` accepts a human JWT or an unbound API key
with a literal `control` or legacy `*` grant. Unbound `["*"]` and
`["control", "*"]` keys are accepted. `host`, `production:*`, Host-bound keys,
and mixtures containing Host or production grants receive 403, including
Host-bound wildcard keys. `dangerous` alone does not imply `control`. A partner
using a production key needs a separate `control` key for this endpoint.

```ts
await client.printers.attestOperatorReady({
  printer_ids: [printerId],
  attestation: {
    external_operator_id: "printie:operator-42",
    operator_display_name: "Tyler",
    method: "qr_scan",
    attested_at: scanTime.toISOString(),
    label_id: "printie:label-123",
    idempotency_key: scanId,
  },
  outcomes: [
    {
      printer_id: printerId,
      job_id: completedJobId,
      event_type: "operator:manual_verification:failed",
      requeue_failed: true,
    },
  ],
});
```

The body requires 1 to 50 printer UUIDs and every attestation field except
`label_id`. Exact duplicate printer ID strings receive 400. Case-variant duplicates are
lowercased and merged, and the resulting UUIDs are sorted. The OpenAPI schema
requires unique items. `method` is `qr_scan` or `manual`. Identity, label, and
idempotency strings have a 200-character limit. `attested_at` is an RFC 3339
timestamp with a timezone. Hive accepts a five-minute age and at most 30 seconds
of future clock skew. A scan predating the lock holder's completion, update, or
the latest printer lock mutation is superseded and cannot release newer work.

Unknown fields and values of the wrong JSON type receive 400 with
`INVALID_OPERATOR_ATTESTATION`. Hive does not strip unknown fields or coerce
types. A misspelled `requeue_failed` field therefore fails before release.

`outcomes` is optional, with at most one entry per requested printer. Each entry
must name the job holding that printer's lock. It uses the human dialog's
`operator:manual_verification:success`, `operator:manual_verification:failed`, or
`operator:manual_verification:cancelled` event. `requeue_failed` defaults to false
and is accepted only for the failed verdict. Existing verified outcomes are
preserved, as on the human path.

For an unverified lock holder, a supplied verdict calls the existing adjudication
function in the readiness transaction. Without a verdict, Hive releases the
printer and marks an unverified COMPLETED or FAILED job `ERROR`, `PRINT_OUTCOME_UNRESOLVED`, and
`outcome_resolution_required: true`. The existing Unresolved Print Outcome feed
and job details retain the job for a later verdict and requeue decision.
CANCELLED and ERROR lock holders release without this unresolved flag.

When the held job is already an Unresolved Print Outcome, its verdict uses the
existing attestation function. The attested farm event and history metadata retain
`source: "operator"`. The farm event uses a system actor. The corresponding
`app_private.partner_ready_audits` row records the partner credential and external
operator identity for attribution in this path.

The response contains `replayed` and `results`. Each result contains `printer_id`,
`audit_id`, `job_id`, `result`, `previous_readiness`, `new_readiness`, and its own
`replayed` flag. `ready` means the readiness transaction committed. Its `outcome`
is `recorded`, `flagged_unresolved`, or `not_applicable`.

`requeue` reports the human path's separate post-commit step:

| Requeue result              | Meaning                                                                                                                                                                                                                                                                                                                  |
| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `not_requested`             | No failed-job replacement was requested.                                                                                                                                                                                                                                                                                 |
| `not_applicable_standalone` | The outcome was recorded for a standalone job. Hive creates no replacement. Printie tracks its orders and must resubmit if needed.                                                                                                                                                                                       |
| `batch_replacement_created` | The shared human-release workflow created a replacement with its existing source and material checks.                                                                                                                                                                                                                    |
| `pending` or `in_progress`  | The durable replacement step is pending, running, or its acknowledgement is unavailable. Retry the original attestation to read its state. After five minutes, the next replay marks an unfinished claim failed and emits an operator log alert. Inspect the batch before resubmitting; a replacement may already exist. |
| `skipped`                   | The shared workflow skipped replacement because its model or material preparation is blocked.                                                                                                                                                                                                                            |
| `failed`                    | The replacement step failed, a database read failed, or the batch context disappeared. Readiness and adjudication remain committed. No automatic second replacement is attempted.                                                                                                                                        |

Other `result` values are per-printer refusals, even with HTTP 200:

| Result                     | Meaning                                                                                                                                                               |
| -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `printer_not_in_org`       | The printer is missing or belongs to another organization. Readiness fields are null.                                                                                 |
| `printer_offline`          | The printer is disconnected.                                                                                                                                          |
| `printer_maintenance`      | The printer is in maintenance mode.                                                                                                                                   |
| `printer_busy`             | Status or active motion/command work prevents release.                                                                                                                |
| `active_job`               | A nonterminal job owns the printer or remains active on it.                                                                                                           |
| `state_unavailable`        | Status is missing, stale, unknown, or more than 30 seconds ahead of Hive.                                                                                             |
| `state_not_fresh`          | Activity is stale despite a recent observation. The printer reported no recognizable state recently, or the Host clock is behind.                                     |
| `stop_unsettled`           | A non-terminal lock holder has a pending/unconfirmed current-generation Stop. Use returned `job_id` and `stop_receipt_id` with `printJobs.getStop(jobId, receiptId)`. |
| `verification_in_progress` | A post-completion motion task has a status outside its release allowlist.                                                                                             |
| `ownership_conflict`       | Ownership changed during release or a database fence refused it.                                                                                                      |
| `outcome_job_mismatch`     | The supplied verdict names a job that does not hold the lock.                                                                                                         |
| `outcome_target_changed`   | The held job can no longer accept that verdict. This printer's transaction rolls back; later printers still run. Refresh the job before retrying.                     |
| `attestation_expired`      | The attestation is older than five minutes.                                                                                                                           |
| `attestation_in_future`    | The attestation is more than 30 seconds ahead of Hive.                                                                                                                |
| `attestation_superseded`   | Newer job or lock evidence makes the scan obsolete.                                                                                                                   |
| `idempotency_conflict`     | This credential already used the key with a different body.                                                                                                           |

Status freshness comes from `printer_states.activity_asserted_at`. A recognizable
current `status` or `gcode_state`, or an `mc_print_stage` observation, asserts
activity. A partial Bambu MQTT push (`msg: 1`) also asserts activity after the
same live MQTT session has received a full report (`msg: 0`) with a recognizable
`gcode_state`. Disconnect or reconnect clears that baseline. Heartbeats and
snapshots without current MQTT evidence do not assert activity. The API lane
forwards idle telemetry at least every 30 seconds while reports keep arriving.
Mailbox merges retain the latest push's activity evidence separately from cached
fields. Idle telemetry uses the normal state upsert and needs no journal row.
The assertion must be no older than 60 seconds or more than 30 seconds ahead.

Unobserved activity still permits job progress, missed-finish recovery and task
supersession. Its lifecycle receipts carry `activity_observed: false`; they do
not refresh activity for readiness or MQTT displays, and cannot repair Host
clock skew. A Bambu `job:update` asserts activity only when its push carries a
recognizable `gcode_state`; progress or stage alone record `false`.

A busy state in either `gcode_state` or `current_status` refuses release.
When present, `current_status` must be `IDLE`, `FINISH`, `FINISHED`, `FAILED`,
`READY`, or `STANDBY`.

`FAILED` remains eligible because the operator's bed-clear attestation confirms
the failed print has been cleared. When `raw_state` contains `mc_print_stage`,
only `1` permits release; other values, including null, return `printer_busy`.
A missing stage follows the status rules. Stage observations still refresh
activity evidence for MQTT displays.

Other jobs on the printer must be `QUEUED`, `COMPLETED`, `CANCELLED`, `CANCELED`,
`FAILED`, `ERROR`, or legacy `FINISHED`. Unknown or null statuses refuse release.
Any live subtask dispatch lease blocks release, regardless of type or job status.
On non-terminal jobs, subtask status must be `QUEUED`, `FINISHED`, `FAILED`, or `SKIPPED`.
An `IN_PROGRESS` post-completion motion task also blocks.
Non-motion subtasks without a live lease on ended jobs do not block.
These checks include jobs, subtasks and command attempts with missing or
incorrect organization metadata because printer ownership is already verified.
Durable Printer Command Attempts in `prepared` or `dispatched` block release.
Readiness recovers stale API-key attempts in the attesting organization.
A `prepared` attempt expires to `refused` after 45 seconds. A `dispatched`
attempt without a recorded outcome becomes `indeterminate` after 5 minutes
without a resend. The 15-minute readiness fence starts at that deadline, 20
minutes from dispatch when it expires. If the API records `indeterminate`
earlier after losing the acknowledgement, the fence starts at that write.
Other readiness checks still apply.

Only a non-terminal lock holder's current-generation `pending` or `unconfirmed`
Stop blocks with temporary `stop_unsettled`. The result includes `job_id` and
`stop_receipt_id`, so the caller can call `printJobs.getStop(jobId, receiptId)`.
COMPLETED, FAILED, ERROR and CANCELLED jobs release normally even if their Stop
receipt is unsettled, subject to every other readiness check.
Legacy CANCELED also bypasses the Stop fence, but the shared lock-release function
can still refuse that spelling with `ownership_conflict`.
Rejected and unsupported Stop receipts also do not block release.
Operator attestation never changes a Stop receipt. If newer job evidence
supersedes the scan, submit a fresh attestation.

A recent applied status receipt with explicit `activity_observed: true`, bound to the observation's Host, assignment,
sequence and timestamp can repair a lagging Host clock with database receipt time,
provided the activity assertion is no more than five minutes old.
Upload, filament and metadata observations cannot refresh stale activity evidence.
`UNKNOWN` and `OFFLINE` observations also preserve the previous activity assertion.
Stale activity with a recent generic observation produces temporary `state_not_fresh`.
Its message names both possible causes, an unrecognizable state or a Host clock
that is behind. Other missing or stale evidence produces `state_unavailable`.
Both refuse readiness and allow retries. Retry after a fresh recognizable status.
Idle telemetry has no receipt-based clock repair. Keep NTP enabled on the Host.
Clock skew beyond about 30 to 60 seconds can cause refusals.

Hive retains the request and audit without automatic expiry. Idempotency is
scoped to the organization and authenticated key or JWT user. Reuse the body and
key after a timeout. Final per-printer outcomes (`ready`, `printer_not_in_org`,
`attestation_expired`, `attestation_superseded`, and `outcome_job_mismatch`) replay
without changing readiness, adjudicating again, or creating another replacement.
Temporary refusals are audited but reevaluated with the same key. In a mixed
batch, only temporary results retry; prior successes remain cached even after a
competing claim consumes readiness. The top-level `replayed` is true when every
printer's readiness result was cached. A new physical check needs a new key.

The audit distinguishes the partner operator, credential, scan, previous and new
readiness, outcome path, and replacement status. Conflicting attempts retain their
own `conflicting_request` and never overwrite the accepted request. Successful
releases preserve `ready_source: "operator_override"` for material evidence,
claim admission, and Bed-Clear Watch. The partner ledger and lock-release reason
`partner_operator_attestation` distinguish their origin.

Malformed input receives 400 with `code: "INVALID_OPERATOR_ATTESTATION"`.
A non-fence database error rolls back the entire batch, including audits and
adjudications, and returns 503. A post-commit batch replacement failure instead
returns the committed readiness result and its replacement status. A known outcome also emits the human training notification and partner-attributed
verification activity. Print loops are deprecated. Partner release does not advance, restart, or otherwise mutate a loop run. Rejected lock attempts do not supersede scans.
This endpoint sends no printer commands. Filament corrections never certify an empty bed and
must not create a new scan key or restore readiness after a claim.

## Pause pickup for a filament correction

Call `client.printers.pausePickup(printerId)` with a partner API key that has
the `control` scope. The pause succeeds when no job holds the printer lock,
no tracked job is printing or paused, and no device-file start is in progress.
A successful call blocks new claims, queued dispatch, and web device-file
starts. It returns `pickup_paused: true` and `paused_at`. A repeat returns the
original timestamp while the pause is active.

A retained job lock or active tracked print returns 409 `printer_busy`.
The `PrinterPickupBusy` response includes the blocking job's ID and stored
status in `holdingJob`. A job can still hold the lock with `ERROR` after a
start confirmation timeout. Retry when the lock is clear and no tracked
print is active. If a device-file start holds the printer, the 409 instead
reports `holding.kind` as `device_file` and gives its deadline in
`holding.expires_at`. Retry after the reservation settles or expires.

After the correction, submit a new `attestOperatorReady` request when the
operator confirms the bed is clear. Pickup resumes when that attestation
succeeds. `GET /v1/printers/{id}/status` reports `pickup_paused: true` during
a pause. Its `ready` and `ready_source` fields still report bed readiness.
