TruehandsDocs
engine 0.4.0 API Back to site

DocsIntegrate

CI, webhooks and exports

Four ways verdicts reach your systems: a CI job that audits each batch and fails when footage is bad, webhooks that push events as they happen, exports and the verdict stream that hand over the audited clips, and backups that copy every finished run to your own bucket.

Audit a batch in CI#

Every CI template does the same three things:

  1. download the CLI from your Truehands server (/v1/ci/cli.pyz, standard library only, no install);
  2. python3 truehands.pyz run --wait --junit truehands-junit.xml, which uploads the files named in the manifest, starts a run and follows it;
  3. let the exit code fail the job: 0 passed, 1 a clip reached fail_on or the policy's gate failed, anything else an error.

The settings live in a committed truehands.yml, which holds no secret:

truehands.yml
# truehands.yml: settings for `truehands run`. Commit this file; it holds no secret.
# The CI job reads TRUEHANDS_KEY and TRUEHANDS_SECRET_KEY (a key pair) from its secret store.
api_url: https://app.truehands.io
program: home-tasks
manifest: batches/manifest.csv
tag: ci
fail_on: reject          # none | partial | review | reject: the job fails if any clip gets this verdict or worse
parallel_uploads: 4

The key pair comes from the CI system's secret store as TRUEHANDS_KEY and TRUEHANDS_SECRET_KEY. Use a dedicated service account (role ci), not a person's key: it can upload, start runs and read results, and it can never activate a policy, decide a review or approve a payout. An owner or admin creates one under Team & keys in the console, and can limit its key to just what the pipeline does, for example uploads.create and runs.start.

Get the files for your server. The templates below are rendered by the server with its own address and your program, and never contain a key:

Shell
truehands ci init github --program home-tasks     # writes truehands.yml and .github/workflows/truehands.yml
truehands ci init gitlab                          # truehands.yml and .gitlab-ci.yml
truehands ci init jenkins                         # truehands.yml and Jenkinsfile
truehands ci init script                          # truehands.yml and run-truehands.sh (cron, Airflow, anything)
truehands ci check                                # what a job here would send: provider, run name, retry key, user

The same files come from GET /v1/ci/templates?provider=github&program=home-tasks. The versions on this page are rendered for https://app.truehands.io and the program home-tasks, and are the files committed under integrations/examples/. The CLI refuses to send a key over plain http:// to a remote host, so serve Truehands over HTTPS and set the server's --public-url.

Retries are safe. In every supported CI system the CLI derives an Idempotency-Key from the pipeline and job (not the attempt), so re-running a failed job returns the run its first attempt started instead of auditing and billing the footage twice. See the CLI in CI.

GitHub Actions#

.github/workflows/truehands.yml
# Truehands audit for GitHub Actions. Audits batches/manifest.csv every night, on demand, and on pull requests that
# change a batch. The job fails when a clip reaches fail_on (truehands.yml); the job summary shows the verdicts.
#
# Add two repository secrets (Settings > Secrets and variables > Actions):
#   TRUEHANDS_KEY         the TH-Key (thk_...) of a Truehands service account (ci role)
#   TRUEHANDS_SECRET_KEY  its TH-Secret-Key (ths_...)
# Anyone who can edit workflows in this repository can read these secrets. Use a service account, and consider a
# GitHub Environment with required reviewers.
name: Truehands audit

on:
  schedule:
    - cron: "17 2 * * *"
  workflow_dispatch:
  pull_request:
    paths:
      - "batches/**"
      - "truehands.yml"

permissions:
  contents: read

concurrency:
  group: truehands-home-tasks
  cancel-in-progress: false

jobs:
  audit:
    # Pull requests from forks get no secrets: skip them.
    if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
    runs-on: ubuntu-24.04
    timeout-minutes: 180
    env:
      TRUEHANDS_API_URL: https://app.truehands.io
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          persist-credentials: false

      # If the footage is not in the repository, fetch it here so the files in batches/manifest.csv exist.

      - name: Download the Truehands CLI
        run: |
          python3 -c 'import os, urllib.request; urllib.request.urlretrieve(os.environ["TRUEHANDS_API_URL"] + "/v1/ci/cli.pyz", "truehands.pyz")'
          # To pin this exact CLI, paste the SHA-256 shown on Integrations in the Truehands console:
          # echo "PASTE_SHA256  truehands.pyz" | sha256sum --check
          python3 truehands.pyz --version

      - name: Audit the batch
        id: audit
        env:
          TRUEHANDS_KEY: ${{ secrets.TRUEHANDS_KEY }}
          TRUEHANDS_SECRET_KEY: ${{ secrets.TRUEHANDS_SECRET_KEY }}
        run: python3 truehands.pyz run --wait --junit truehands-junit.xml

      # Runs only when the audit passed, for example to release the batch for training or payout:
      # - name: Release the batch
      #   if: steps.audit.outputs.result == 'passed'
      #   env:
      #     RUN_URL: ${{ steps.audit.outputs.run-url }}
      #   run: echo "Audit passed: $RUN_URL"

After the audit step, steps.audit.outputs holds run-id, run-url, status, result, accept, partial, review, reject and billable-hours, and the job summary shows the verdicts (only a link in public repositories, unless TRUEHANDS_SUMMARY=full).

As a composite action. integrations/github-action/ wraps the same steps with inputs instead of a truehands.yml, and no third-party actions:

YAML
- uses: ./integrations/github-action        # or a copy of this folder in your repository
  id: audit
  with:
    api-url: https://app.truehands.io
    key: ${{ secrets.TRUEHANDS_KEY }}
    secret-key: ${{ secrets.TRUEHANDS_SECRET_KEY }}
    program: home-tasks
    manifest: batches/manifest.csv
    fail-on: reject
- if: steps.audit.outputs.result == 'passed'
  run: echo "released"

Its inputs are api-url, key, secret-key (required), program, manifest, config, name, tag, fail-on and junit (default truehands-junit.xml); its outputs are the step outputs above.

Policy changes in pull requests: see Policies.

GitLab CI#

.gitlab-ci.yml
# Truehands audit for GitLab CI. Audits batches/manifest.csv on a schedule, from Run pipeline, and on merge requests
# that change a batch. The job fails when a clip reaches fail_on (truehands.yml).
#
# Add two CI/CD variables (Settings > CI/CD > Variables), masked; mark them protected too if only protected
# branches should run audits:
#   TRUEHANDS_KEY         the TH-Key (thk_...) of a Truehands service account (ci role)
#   TRUEHANDS_SECRET_KEY  its TH-Secret-Key (ths_...)
# Then add a pipeline schedule (Build > Pipeline schedules), for example every night.
truehands-audit:
  image: python:3.13-slim
  variables:
    TRUEHANDS_API_URL: https://app.truehands.io
    TRUEHANDS_DOTENV: truehands.env
  rules:
    - if: $CI_PIPELINE_SOURCE == "schedule"
    - if: $CI_PIPELINE_SOURCE == "web"
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
      changes:
        - batches/**/*
        - truehands.yml
  resource_group: truehands-home-tasks
  timeout: 3h
  script:
    - python3 -c 'import os, urllib.request; urllib.request.urlretrieve(os.environ["TRUEHANDS_API_URL"] + "/v1/ci/cli.pyz", "truehands.pyz")'
    - python3 truehands.pyz run --wait --junit truehands-junit.xml
  artifacts:
    when: always
    reports:
      junit: truehands-junit.xml
      dotenv: truehands.env

The JUnit report shows each clip in the merge request's test tab; the dotenv report passes TRUEHANDS_RUN_ID, TRUEHANDS_RUN_URL and TRUEHANDS_RESULT to later jobs. To share one definition across projects, include integrations/gitlab/truehands.gitlab-ci.yml, which defines a hidden .truehands-audit job to extend:

YAML
include:
  - local: integrations/gitlab/truehands.gitlab-ci.yml
truehands-audit:
  extends: .truehands-audit
  variables:
    TRUEHANDS_API_URL: https://app.truehands.io

Jenkins#

Jenkinsfile
// Truehands audit for Jenkins. Audits batches/manifest.csv every night; the build fails when a clip reaches
// fail_on (truehands.yml).
//
// Add two credentials of kind "Secret text" (Manage Jenkins > Credentials):
//   truehands-key         the TH-Key (thk_...) of a Truehands service account (ci role)
//   truehands-secret-key  its TH-Secret-Key (ths_...)
pipeline {
  agent any
  triggers { cron('H 2 * * *') }
  options {
    disableConcurrentBuilds()
    timeout(time: 3, unit: 'HOURS')
  }
  environment {
    TRUEHANDS_API_URL = 'https://app.truehands.io'
    TRUEHANDS_KEY = credentials('truehands-key')
    TRUEHANDS_SECRET_KEY = credentials('truehands-secret-key')
  }
  stages {
    stage('Truehands audit') {
      steps {
        sh '''
          python3 -c 'import os, urllib.request; urllib.request.urlretrieve(os.environ["TRUEHANDS_API_URL"] + "/v1/ci/cli.pyz", "truehands.pyz")'
          python3 truehands.pyz run --wait --junit truehands-junit.xml
        '''
      }
    }
  }
  post {
    always {
      junit allowEmptyResults: true, testResults: 'truehands-junit.xml'
    }
  }
}

CircleCI and Buildkite#

The server has no generated template for these two, but the CLI recognises both: it reads their run metadata (repository, branch, commit, build URL, pull request) and derives the same retry-safe idempotency key. The job is the same two commands. These examples are written for these docs; adapt the image and triggers to your setup.

.circleci/config.yml
version: 2.1
jobs:
  truehands-audit:
    docker:
      - image: cimg/python:3.13
    steps:
      - checkout
      - run:
          name: Audit the batch
          command: |
            python3 -c 'import os, urllib.request; urllib.request.urlretrieve(os.environ["TRUEHANDS_API_URL"] + "/v1/ci/cli.pyz", "truehands.pyz")'
            mkdir -p test-results/truehands
            python3 truehands.pyz run --wait --junit test-results/truehands/junit.xml
      - store_test_results:
          path: test-results
workflows:
  audit:
    jobs:
      - truehands-audit

Set TRUEHANDS_API_URL, TRUEHANDS_KEY and TRUEHANDS_SECRET_KEY as project environment variables or in a context.

.buildkite/pipeline.yml
steps:
  - label: "Truehands audit"
    command: |
      python3 -c 'import os, urllib.request; urllib.request.urlretrieve(os.environ["TRUEHANDS_API_URL"] + "/v1/ci/cli.pyz", "truehands.pyz")'
      python3 truehands.pyz run --wait --junit truehands-junit.xml
    artifact_paths: "truehands-junit.xml"

Provide the three variables to the agent from your secrets store, not in the pipeline file.

cron, Airflow and other schedulers#

run-truehands.sh
#!/bin/sh
# Truehands audit from cron, Airflow or any scheduler. Audits the manifest named in truehands.yml next to this script.
#   cron:     17 2 * * *  /srv/batches/run-truehands.sh >> /var/log/truehands.log 2>&1
#   Airflow:  BashOperator(task_id="truehands_audit", bash_command="/srv/batches/run-truehands.sh ",
#                          env={"TRUEHANDS_RUN_DATE": "{{ ds }}", ...}, append_env=True)
# Read TRUEHANDS_KEY and TRUEHANDS_SECRET_KEY (a key pair) from your secret store; never write them in this file.
# A retry on the same day returns the run that day already started instead of auditing and billing twice.
# Exit codes: 0 passed, 1 a clip reached fail_on, anything else is an error.
set -eu
: "${TRUEHANDS_KEY:?set TRUEHANDS_KEY}"
: "${TRUEHANDS_SECRET_KEY:?set TRUEHANDS_SECRET_KEY}"
TRUEHANDS_API_URL="${TRUEHANDS_API_URL:-https://app.truehands.io}"
export TRUEHANDS_API_URL
RUN_DATE="${TRUEHANDS_RUN_DATE:-$(date -u +%Y-%m-%d)}"
cd "$(dirname "$0")"
python3 -c 'import os, urllib.request; urllib.request.urlretrieve(os.environ["TRUEHANDS_API_URL"] + "/v1/ci/cli.pyz", "truehands.pyz")'
# To pin this exact CLI, paste the SHA-256 shown on Integrations in the Truehands console:
# echo "PASTE_SHA256  truehands.pyz" | sha256sum --check
exec python3 truehands.pyz run --wait --name "home-tasks $RUN_DATE" --idempotency-key "script-home-tasks-$RUN_DATE" "$@"

The idempotency key includes the run date, so a scheduler that retries the same day gets the run that day already started. For Airflow, pass the logical date as TRUEHANDS_RUN_DATE ({{ ds }}) so a backfill audits each day once.

Truehands can also run batches without any CI: watchers turn footage that arrives in an inbox folder or through POST /v1/watchers/{ref}/clips into runs, and schedules fire a watcher or re-audit a program's recent clips on a cron expression in a time zone. Both are set up in the console under Automation and listed with truehands watchers and truehands schedules.

More gates for CI#

  • Wait for people. truehands review wait RUN --timeout 6h blocks until the review desk has finished a run (exit 0), or times out (exit 6). Use it before releasing a batch for payout or training.
  • Guard an engine or reference-library upgrade. truehands rerun RUN --reason "new reference library" --compare --fail-on-worse reject audits the same clips again and exits 1 if any clip got worse to reject. truehands compare --baseline auto RUN --fail-on-worse review compares a run with its parent or the previous run of the program.
  • Pin the policy. truehands gates RUN --expect-policy .truehands/policy.yml exits 2 unless the run was decided with that exact file.

Status badges and pipeline health#

POST /v1/ci/badges creates a README badge for a program: GET /v1/badges/{token}.svg shows one word for the newest run (passing, failing, warning, audited, running, error, cancelled, no runs) without credentials; the token is an HMAC bound to the badge, and a revoked badge says "revoked". GET /v1/ci/pipelines groups the runs that report in by program, CI provider and repository, with their failure rate and a stale flag when a pipeline has gone quiet for more than twice its usual interval.

Webhooks#

Add an endpoint, then verify every delivery. The endpoint options, event types, retry schedule and signature scheme are on REST API: webhooks.

Shell
truehands webhooks add https://hooks.example.com/truehands --events run.completed,verdict.updated,payout_batch.approved
truehands webhooks test whe_...        # send a webhook.test event now; exit 1 unless your endpoint answers 2xx
truehands webhooks deliveries whe_...  # recent deliveries and their last status

add prints the signing secret (whsec_…) once. For a Slack channel, pass --slack with an incoming-webhook URL; Slack gets short messages for runs, gates, exports and payout batches, and no signature.

Verify signatures#

examples/webhooks/receive.py is a complete receiver in Python's standard library. Its verify function is all a receiver needs:

examples/webhooks/receive.py: verify
def verify(secret, headers, body, now=None, tolerance=TOLERANCE_S):
    """Check one delivery. `headers` is any mapping (looked up case-insensitively), `body` the raw bytes.
    Returns the parsed event, or raises InvalidSignature."""
    h = {k.lower(): v for k, v in dict(headers).items()}
    msg_id, ts, sigs = h.get("webhook-id"), h.get("webhook-timestamp"), h.get("webhook-signature")
    if not msg_id or not ts or not sigs:
        raise InvalidSignature("missing webhook-id, webhook-timestamp or webhook-signature")
    try:
        sent = int(ts)
    except ValueError:
        raise InvalidSignature("bad timestamp") from None
    if abs((time.time() if now is None else now) - sent) > tolerance:
        raise InvalidSignature("timestamp too far from now")
    key = base64.b64decode(secret.removeprefix("whsec_"))
    expected = base64.b64encode(hmac.new(key, f"{msg_id}.{ts}.".encode() + body, hashlib.sha256).digest()).decode()
    for sig in sigs.split(" "):
        version, _, value = sig.partition(",")
        if version == "v1" and hmac.compare_digest(value, expected):
            return json.loads(body)
    raise InvalidSignature("no matching signature")

Run it with the secret in the environment:

Shell
TRUEHANDS_WEBHOOK_SECRET=whsec_... python3 examples/webhooks/receive.py --port 8000
  • It accepts any matching v1 signature in the header, so a secret rotation (24 hours of dual signatures) never drops events.
  • It refuses timestamps more than 5 minutes from now, which stops replays of old deliveries.
  • It remembers the last 5000 webhook-ids and ignores repeats: Truehands retries and resends with the same id.
  • Answer quickly with a 2xx and do the work in the background; Truehands waits at most 10 seconds.
  • Act on payout_batch.approved only after fetching the batch from the API and checking its SHA-256.

Exports#

An export is a manifest of a program's audited clips, for a training pipeline or a buyer, with a sidecar that lists every file's SHA-256.

Shell
truehands export --run run_9b1f04c2e7aa --format parquet -o week41.parquet
# week41.parquet  96 rows  sha256 …   (and week41.parquet.manifest.json)
  • Scope: one or more runs (--run, repeatable), or every run of a program (--program, with --from and --to on submission time). Statuses: --status, default accept,partial. Formats: jsonl, csv, parquet.
  • Verified: the CLI downloads the data file and the sidecar through one-hour signed links, checks both SHA-256s, and exits 1 on a mismatch. Exports expire after 30 days.
  • Rows follow the schema truehands.manifest.v1, one row per clip with these fields: uid, run_id, clip_id, program, contributor_id, device_id, claimed_task, submitted_at, status, reasons, duration_s, payable_s, keep_ranges_s, source_sha256, canonical_sha256, bytes, custom_id, upload, provisional, verdict_version, seq, decided_at.
  • keep_ranges_s lists the seconds a buyer may keep: the whole clip for accept, the clip minus its idle runs for partial, nothing for review and reject. It is null when the ranges cannot be stated exactly, for example for cuts of replayed or repeated frames.
  • Rows carry hashes and ids, never file names or media links. In CSV, a cell that starts with =, +, -, @, a tab or a carriage return is prefixed with ', so a spreadsheet does not run it as a formula.

The verdict stream. truehands verdicts --program home-tasks --status accept,partial --format csv (or GET /v1/verdicts) streams the latest verdict of every clip of finished runs, in the order of the organisation's verdict ledger, and prints a watermark. Pass it back as --after to receive only what changed since, including verdicts a reviewer or a policy changed later.

Payout batches. POST /v1/programs/{slug}/payout-batches freezes the rate and the verdicts of a submission window into a batch in integer cents, bound to a SHA-256. Two different owners or admins, signed in to the console, approve the exact hash they reviewed; only then do the payout files exist, and each clip can be paid once.

Backups to your storage#

Truehands Cloud deletes footage 30 days after it was last used (retention). To keep your own copy, add your bucket as a backup destination, under Delivery › Backups in the console or with the API: every run that finishes is copied there, and its results are refreshed when a reviewer changes a verdict later. Truehands only writes to your storage. It never deletes from it, and it never connects to your database: you load the files yourself, as below.

Where. AWS S3; Cloudflare R2 (region auto); Google Cloud Storage, through its S3-compatible XML API at https://storage.googleapis.com with an HMAC key; MinIO; or any other S3-compatible service. An organisation can have up to 3 destinations. Give each an access key that may write to the bucket and prefix (s3:PutObject; with s3:GetObject as well, a retry skips the files that are already there). The secret access key is write-only: it is stored encrypted and the API shows only its last four characters. A custom endpoint must be https:// and resolve only to public addresses.

What. Each run goes under <prefix>/runs/<run_id>/:

ObjectIncluded
verdicts.jsonl, verdicts.parquetAlways. The run's latest verdict of every clip, in the export row schema.
audit.json, usage.jsonAlways.
report.htmlWhile the run's footage exists: the report embeds frames.
evidence/<clip_id>_t0.jpg …Evidence frames. On by default.
footage/<clip_id>.mp4 (or .mov), imu/<clip_id>.csvThe uploaded videos and sensor logs. Off by default.
manifest.jsonAlways, written last.

manifest.json (schema truehands.backup.v1) lists every other object's key, bytes and sha256, the run's summary and counts, the engine and policy versions, and, under missing, footage that was already deleted when the backup ran. Each object also carries its SHA-256 in its metadata (x-amz-meta-sha256), so a backup that runs again uploads only what changed. Files of 64 MiB or more are uploaded in 16 MiB parts.

Footage is your contributors' personal data. Once it is in your bucket, who can see it and how long it stays there is up to you. It is also most of a backup's size, and of the bucket's cost.

When. A backup is queued for every destination that is on when a run finishes; truehands backups run RUN_ID (or POST /v1/runs/{id}/backup) backs a run up again, and Back up earlier runs (POST /v1/backups/destinations/{id}/backfill) copies the runs that finished before the destination existed. A failed attempt is retried after 1 min, 5 min, 15 min, 1 h, 3 h, 6 h, 12 h, up to 8 attempts; then the backup fails and a backup.failed event goes to your webhooks and Slack. When a verdict changes after the run, only verdicts.jsonl, verdicts.parquet and manifest.json are written again.

While a backup that copies evidence or footage is waiting or running, the footage it needs is not deleted, for at most 3 days past its date, so a broken destination cannot keep footage forever. Each run also sends one run.media_expiring event 7 days before its footage is deleted, with backed_up: true when every destination that copies footage has a finished backup of it.

A run as a zip#

Without a bucket, download a finished run as a zip with the same layout and manifest.json: Download archive on the run page, or

Shell
truehands archive run_9b1f04c2e7aa                    # results and evidence frames: run_9b1f04c2e7aa-results.zip
truehands archive run_9b1f04c2e7aa --footage -o week41.zip

The CLI checks every file against the manifest and exits 1 on a mismatch. Anyone who can see runs can download results; footage needs footage.download (owners and admins) and every footage download is in the audit log. Once a run's footage is deleted, the results archive still works and a footage archive answers 410 media_deleted.

Load verdicts into your database#

examples/sync/verdicts_to_postgres.py (Python's standard library plus psycopg) copies new and changed verdicts from GET /v1/verdicts into a truehands_verdicts table, upserting on uid, and keeps its watermark in truehands_sync_state, so each run picks up where the last one stopped. Run it from cron, or when a run.completed or verdict.updated webhook arrives; a key pair limited to verdicts.view is enough.

Shell
export TRUEHANDS_API_URL=https://app.truehands.io TRUEHANDS_KEY=thk_... TRUEHANDS_SECRET_KEY=ths_...
DATABASE_URL=postgresql://sync@db.internal/analytics python3 examples/sync/verdicts_to_postgres.py

From the bucket into a warehouse. Each run's verdicts.parquet holds its latest verdicts, so reloading all of them gives the current state. With BUCKET and PREFIX as on the destination:

  • BigQuery (a Google Cloud Storage destination): bq load --replace --source_format=PARQUET analytics.truehands_verdicts "gs://BUCKET/PREFIX/runs/*/verdicts.parquet"
  • Snowflake (an external stage truehands on s3://BUCKET/PREFIX/, and a table with the same column names): COPY INTO truehands_verdicts FROM @truehands/runs/ PATTERN = '.*/verdicts[.]parquet' FILE_FORMAT = (TYPE = PARQUET) MATCH_BY_COLUMN_NAME = CASE_INSENSITIVE; Snowflake skips files it already loaded; to pick up refreshed verdicts, truncate the table and add FORCE = TRUE.
  • Redshift (one run, for example on backup.completed; a table with the columns in the row schema's order, reasons and keep_ranges_s as SUPER): COPY truehands_verdicts FROM 's3://BUCKET/PREFIX/runs/RUN_ID/verdicts.parquet' IAM_ROLE 'arn:aws:iam::123456789012:role/redshift-copy' FORMAT AS PARQUET SERIALIZETOJSON;
  • ClickHouse (a ReplacingMergeTree(seq) table ordered by uid, so a newer verdict replaces the older one): INSERT INTO truehands_verdicts SELECT * FROM s3('https://BUCKET.s3.amazonaws.com/PREFIX/runs/*/verdicts.parquet', 'ACCESS_KEY_ID', 'SECRET_ACCESS_KEY', 'Parquet');