# Gmail API with Repo

This workflow uses the Cortex handoff copied into `CORTEX-HANDOFF-2026-10-17.md`. Runtime connections use HTTPS and HMAC only. The server does not read SSH credentials. The existing Gmail API workflow and Cortex's existing Repo pages remain separate.

## Settings

Sign in to the domain's administrator account and open **Worker settings** (`/inbox-tasks/admin`). Settings are separate for newtopc.com and runwaydo.com.

1. **Cortex integration settings** opens a script-free form containing only the Cortex URL and private connection key. Use `https://app.moreisheats.com`. The 64-character ASCII key is encrypted with Laravel's application key, hidden from serialization, never returned to the browser, and preserved when submitted blank. Back up the database and application encryption key together.
2. **Worker mode** selects the existing Gmail API workflow or Gmail API with Repo.
3. **Platform** selects SproutGigs or Microworkers for the Repo workflow.
4. **Campaign message subject** is the final fixed subject of the saved Cortex campaign. This is checked in Gmail metadata alongside the RFC Message-ID. The current Cortex contract does not export or override campaign subjects; configure the same fixed subject in Cortex. Normal campaign placeholder replacement still runs there.
5. **Task deadline** is in minutes from verified Google authorization. Worker task access, status and reconnection end at that deadline, including for completed tasks. The original deadline never extends. After successful completion, reopening the platform link can start a separate worker attempt as described below.
6. **Wait before work** is entered in seconds from verified Google authorization (for example, `90` gives a 90-second countdown). It must be shorter than the deadline, which is still entered in minutes. Saved policies already store seconds, so existing durations and active task cutoffs are preserved.
7. **Margin of error (messages)** is an absolute number of received task messages allowed to remain unfinished. Default `0` requires all received messages. With 20 received and margin 2, 18 must qualify. At least one message must qualify; zero received messages still go to manual review without completion. The margin is frozen in each task policy at creation, so changing settings does not relax an existing task. Gmail/API failures remain checking-unavailable states and cannot establish completion.

**Require a 👍 reaction** defaults on for new Repo tasks. Inbox/read checks remain in place, with dynamic read/reaction progress and saved evidence for manual review. Existing tasks retain their original rules. See [Gmail reaction tracking](GMAIL-REACTIONS.md) for matching, campaign compatibility, bounded polling and the October 19 `000004` migration.

**Faster progress** uses Gmail history, small parallel request groups and shared rolling quota budgets. Confirmed read/reaction updates appear during checks, with current-step feedback and safe retries. See [Faster progress](FAST-PROGRESS.md) for the `2026_10_19_000005` migration, settings and verification.

**Worker help links** is a separate administrator menu page at `/worker-help`, with its own controller and save form for the Telegram group, mobile task tutorial and computer task tutorial. It is separate from `/inbox-tasks/admin`. Links are optional, must use HTTPS without embedded username/password, and are saved per domain in `inbox_domain_settings.help_links`. Blank removes that link. Configured links appear in a shared **Need help?** panel on every Repo worker page, including connection, waiting, reading, completion and expired sessions. The header Help button jumps to this panel. Links open a new tab with no referrer, task identifiers or Gmail address appended. Existing tasks use the current domain links on the next page load; editing help does not alter frozen policies, payment records or sending settings. Saving help requires no Cortex connection and never sends messages.

The same `/worker-help` page has a separate **Worker CAPTCHA** form: Enable/Disable, hCaptcha Site Key, and hCaptcha Secret Key. Settings apply per domain to the first Repo Google connection step and reconnects. The secret is encrypted in `inbox_captcha_settings`, never returned in HTML/JSON, and preserved when left blank. The HTTPS-only key-entry page runs no scripts; validation and error responses do not echo or flash the secret. Enabling requires both keys. Until a domain saves its override, its existing environment-based CAPTCHA configuration is preserved. Legacy worker and administrator-login CAPTCHA settings continue to use their original configuration.

Enabled Repo connections must pass backend verification before starting basic Google sign-in. The server sends a form-encoded POST to the fixed `https://api.hcaptcha.com/siteverify` endpoint with the response token, expected sitekey, secret and client IP, and accepts only a successful response whose `success` is the boolean `true`. Missing/invalid/reused tokens, provider errors and credential-decryption failures cannot bypass CAPTCHA. hCaptcha enforces token expiry and single use; no successful CAPTCHA is cached in the worker session. The site key is public; the secret and verification token are excluded from settings/audit output. Integration follows the [official hCaptcha verification reference](https://docs.hcaptcha.com/#verify-the-user-response-server-side).

The worker help panel sits above the page heading, with compact links labelled **Telegram group**, **Phone tutorial**, and **Computer tutorial**. It stays in this position throughout the workflow.

Save these settings and copy the displayed platform link. No individual invitation or external job policy is required for the public link workflow:

```
https://DOMAIN/modify/auth?platform=sproutgigs&job={{JOB_ID}}&worker={{PW_ID}}
https://DOMAIN/modify/auth?platform=microworkers&campaign={{CAMP_ID}}&worker={{MW_ID}}
```

The platform replaces the placeholders. `platform=platform=sproutgigs` is invalid. Only the domain's selected platform is accepted. The campaign parameter is a Microworkers job identifier, never a Cortex campaign selector. An assignment is bound to domain, platform, job, worker, worker attempt number and the Google-authenticated Gmail address. Repeated entry reuses the current unfinished attempt, task and idempotency key.

Returning workers can open the exact same public platform link after the latest task has both a completion timestamp and nonempty completion evidence. A pending or approved manual-review status is eligible; rejected, revoked, private-invitation and unfinished tasks do not automatically restart. The platform entry creates the next numbered assignment with a new UUID, without copying its predecessor's email, account binding, authorization metadata, completion, approval or payment. The old task, proof, deadline and payment history remain unchanged, including if the old deadline has passed. Refreshing the old progress/completion URL or reconnecting an old task does not create a new attempt.

Entry is serialized using the domain settings, job and latest assignment/task locks, with a unique database identity including `attempt_number`. Repeated clicks/tabs use the same pending attempt rather than creating multiple sends. Entry alone never dispatches mail or starts the task timer. The new attempt repeats CAPTCHA and the two-stage Google flow; only successful authorization creates its task, fresh countdown/deadline and durable outbox. Its new assignment/task UUIDs produce distinct Cortex assignment and idempotency keys, while retries retain the same key within that attempt. No automatic SMTP resend is introduced.

The existing Gmail duplicate check stays in force: returning workers must use a Gmail address not already registered, including Gmail dot/plus/googlemail aliases and accounts on the other domain. Cortex's campaign mailbox rules are also unchanged. Worker review identifies each numbered attempt and links to the previous saved worker task. A `worker_repeat_attempt_created` event links the new assignment to its predecessor. All attempts still require separate manual review/payment; a rejected prior task cannot gain a fresh attempt automatically.

Public URL identifiers are claims, not proof of platform eligibility. Check platform records before approving payment. Someone opening another worker's URL cannot view their Gmail address or task progress without authorizing the already bound mailbox through Google. Existing private invitations are retained for compatibility. A disabled job or revoked assignment stays blocked.

There is no separate sending authorization or test-mailbox restriction. With the Cortex connection saved and Repo mode selected, a worker's verified Google login creates the durable campaign request. Saving settings or opening a link alone does not send email. The connection-check button performs an authenticated GET only. Cortex still enforces its campaign configuration and duplicate-mailbox rules. Legacy authorization columns are retained for schema compatibility and have no effect.

## Worker flow and counts

Google authorization uses the existing domain projects and HTTPS callback. Random OAuth state is session-bound, domain-bound, expiring and single-use. Tokens are encrypted in `inbox_connections`, excluded from legacy exports, and never shared with Cortex. Google profile supplies the proof address. Canonical Gmail aliases are normalized to match Cortex's duplicate rules; the Google-reported address is displayed as proof. There is no OTP, VCODE or PCODE in this workflow.

Repo connection now has two Google steps. First it requests only `openid email profile`, with online access and account selection. The server exchanges the code and reads Google's verified email through the OpenID Connect UserInfo endpoint. It checks `accounts` globally across projects/domains, including revoked rows and Gmail dot/plus/googlemail aliases. An existing email receives **This email already exists in our system. Please use a different Google account to register.** No Gmail authorization or Cortex request starts for that new signup. Basic-step tokens are discarded rather than persisted.

For a new email, the server redirects immediately to Gmail consent using the same project/callback and the verified address as `login_hint`. This second step requests the original workflow's Gmail permissions (full Gmail access and basic Gmail settings). It rejects a switched Gmail address or missing permissions. Each step uses fresh random state, bound to session, assignment, domain and stage, with a ten-minute expiry and single-use validation. Duplicate detection runs again inside the registration transaction; PostgreSQL advisory locking serializes Repo registrations for a canonical mailbox. No account, connection, task or outbox is committed on failure. The deadline and waiting period start only after successful Gmail authorization.

Reconnecting the bound mailbox of an existing task repeats both Google steps and updates that task's credentials without creating another signup or send. It is permitted for the same task despite its own account row. Previously connected read-only mailboxes remain valid for observation and read-only reports; they must authorize the broader permissions before tools can change messages. Google authorization still does not establish job eligibility.

After the same-address and permission checks, Repo authorization waits three seconds for Google notices, then polls within a total five-second budget before creating the task and starting its countdown. This separate helper uses metadata only, matching the exact display name `Google`, a sender address at `google.com` or its subdomains, the current sign-in time window, and a Gmail authentication result showing a passing Google DKIM signature. It does not filter by subject, so different notification subjects and languages can match. It adds only `STARRED` and `IMPORTANT` to at most two matching notices. It never fetches bodies, changes read/unread state, moves messages, or touches Trash. Google may send fewer than two or send them late. Sender and timing checks cannot establish which authorization phase generated a notice or distinguish another genuine Google notice arriving in the same window.

At the countdown cutoff, a deferred worker-page check retries for missing notices once; the scheduled worker provides recovery even for zero-delivery tasks. The helper shares the exclusive task lease with message observation and records `google_notice_initial_check` / `google_notice_countdown_check` events, including matched Gmail IDs and sanitized results. Adding labels is idempotent if a process stops before recording the result. These notices never count toward campaign messages, worker actions, completion, review, or payment. Missing notices and optional highlighting/API failures do not block the countdown or change the task's checking status. No existing tasks are retroactively opted in without a new successful authorization.

Each verified login creates or updates a row in `accounts`, linked by `inbox_connection_id` to the encrypted credentials. It records project, email, platform, worker/job IDs and browser/network metadata. The corresponding assignment stores `account_id` and its own metadata; authorization events retain historical metadata. The standard `accounts.access_token`, `refresh_token`, `expires_in` and `token_created` columns are populated using the existing account format. The encrypted connection remains synchronized on authorization and refresh, including refresh during long mailbox operations. Existing registration time and payment history are preserved; token fields update to the currently authorized credentials. Reconnects reuse the account and task without increasing project account counts repeatedly. Accounts from another domain are not overwritten.

Legacy Gmail clients and token checks resolve the encrypted connection on the server. API/service failure is distinct from revoked access. Repo-linked accounts are excluded from external Master API credential exports. Browser token-status responses omit access tokens, refresh tokens and project credentials. Credential persistence failures use a sanitized error without SQL bindings. Mailbox tools do not approve Repo tasks or pay workers. IP and browser fields are observations provided by the request, not verified personal identity. OAuth codes, state, invite secrets, cookies and authorization headers are not recorded in worker metadata; URL query strings and fragments are stripped.

Previously connected Repo assignments can be linked using `php artisan inbox-tasks:sync-accounts`. This command makes no Gmail/Cortex requests, does not create campaign tasks, preserves grant scopes and is safe to repeat. It cannot reconstruct IP/device details that were never recorded.

Mailbox check requests return stored progress before starting a due Gmail scan in a termination callback, after PHP-FPM sends the response. This prevents the browser's 20-second request timeout from treating a long multi-message scan as a failed progress update. Active task leases and retry due times prevent overlapping scans; the scheduled worker recovers if a web process stops. Actual Google connection/rate/permission failures remain recorded separately and have simple worker-facing explanations. A browser update failure is described as a page update problem, rather than a Gmail failure.

After login the server commits a task and durable outbox before requesting the campaign. The initial request starts after the redirect response; the scheduled outbox provides recovery. The worker sees a loading indicator, countdown and actual received message count. Planned counts stay in admin records and the session deadline is enforced without displaying its timestamp on the worker page. The browser requests a mailbox check every two seconds after the previous request completes, using a session-authorized, CSRF-protected POST `/inbox-tasks/tasks/{task}/check`. This observes the assigned task, schedules the separate notice retry at the cutoff, and never dispatches campaigns. The processor's due time and task lease prevent overlapping scans across browser tabs and the background worker. API failures back off for at least 30 seconds (or longer if required by Cortex Retry-After); the browser can still retrieve stored progress. Completed tasks use the read-only GET status endpoint. When the countdown ends, the spinner disappears immediately and the page shows the last received count and Inbox/Spam breakdown. It does not wait for another delivery scan or for Cortex to report finished sending.

For public tasks using the received-message policy, the server freezes the distinct logical messages observed by the countdown cutoff. Freezing uses persisted Gmail observations under a task lock and makes no external requests; an ongoing slow scan or a late page visit cannot add messages first observed after the cutoff. The existing `work_list_frozen` audit event records the cutoff and original Inbox/Spam counts, so those counts remain fixed as messages are read or moved. Duplicate deliveries count once; Inbox takes precedence when a logical message has copies in both Inbox and Spam. Archived/Trash messages are shown as Other with instructions to restore them. Zero observed messages end waiting with an administrator-review notice, a zero count, and no completion/payment credit. Existing API/access failures stay recorded separately. The required count uses the frozen received list and the task's saved margin. Missing/failed sends are not presented as emails the worker must find. Already frozen lists and older planned-count policies are preserved.

After freezing, the processor stops Message-ID searches and Cortex manifest polling for that task. It checks the known Gmail message IDs of the selected logical messages for read/Inbox/Spam/Trash changes. Later arrivals cannot enlarge or substitute for the fixed work list. The last observed Cortex send plan and attempt states remain in admin records; Cortex owns subsequent dispatch history. The instructions ask the worker to open/read each Inbox message and open/read then click **Not spam** for each Spam message, one email at a time. API state observations cannot establish whether the worker used individual or bulk actions.

For a nonempty received work list, required qualifying messages are `max(1, received count - saved margin)`. The margin is applied once; missing/failed sends are already excluded from the received count and are not subtracted again. The margin and reduced threshold are private server/admin settings: neither is included in worker HTML or progress JSON. The worker's heading, denominator and percentage always use the full received total (for example, 10 / 24), alongside the original Inbox/Spam split. Only the server decides when to show completion using the saved threshold. Frozen lists and completion thresholds saved before the margin setting was introduced keep their original values.

The worker's **Task instructions** panel uses simple English and changes with the current step: waiting, reading Inbox messages, reading/moving Spam messages one at a time, reconnecting Gmail, temporary checking failures, administrator review, or submitting the Gmail proof on the correct platform. Instructions for Inbox/Spam use current unfinished logical messages, not the frozen arrival breakdown. They change after a message moves or qualifies; duplicate copies do not create extra steps. The panel updates only when its instructions change, so polling does not repeatedly announce the same text.

The worker reads those task messages and moves Spam to Inbox. Qualifying messages must exist in Inbox, be outside Spam/Trash and have no UNREAD label. Already-read messages can qualify at the first scan; this checks state, not human reading. Duplicate deliveries count one logical message. Matching the subject alone never earns credit: the server verifies Cortex's unique RFC Message-ID and Gmail's resource ID. A subject mismatch is a configuration/checking issue, not a worker violation.

The completion screen says **Submit this Gmail address as your proof.** Completion is ready for manual review. Approval and recording an external payment are separate administrator actions; the application does not transfer money. New tasks continue observation until their original deadline, preserving later changes separately from immutable completion evidence. At the deadline, the worker task's session capabilities are removed and the page closes access. This does not revoke Google's OAuth grant or erase audit records.

## Worker review

**Worker review** is a separate administrator menu page at `/worker-review`; `/inbox-tasks/admin` contains settings only. Enter the Gmail address submitted as proof to find matching tasks and saved account registrations on the current domain. Gmail dot/plus aliases and googlemail.com addresses use the same normalization as registration. The search is stored in the domain's administrator session rather than URL parameters, remains active across pagination, and can be cleared. The initial page shows recent tasks; summary counts cover the full matching result set, not just the current 20-row page. A legacy account without a Repo task is identified as registration only, not task completion.

Each task opens its saved activity review. It shows platform/job/worker IDs, account and connection details, original Inbox/Spam arrival counts when recorded, frozen work count, private saved margin/threshold, last qualifying state, and the last recorded message-check time. Duplicate deliveries/resends count once per logical message, and later arrivals outside the frozen list are excluded. Dates are displayed in Africa/Casablanca. Credentials are not queried for account/connection summaries or exposed in the review pages.

Readable message history distinguishes first-seen already-read mail from an observed unread-to-read change. Observed changes after completion are marked separately. A warning identifies later nonqualifying observations of the actual Gmail message copies used in completion evidence; unrelated delivery copies are not treated as that evidence. Earlier completion records remain intact. Checking/access failures have their own history and never become inferred deletions, worker actions, or automatic cheating decisions. Detailed message IDs, attempts and audit history remain available in expandable sections.

Opening/searching these reports makes no Gmail/Cortex requests, does not freeze or complete tasks, and never approves or records payment. Manual decisions still require administrator notes and confirmation; approval requires recorded completion evidence, and recording an external payment requires prior approval. Paid tasks cannot be reviewed/paid again. Public platform IDs still require checking against the platform's records. These reports describe saved observations, not live mailbox state or proof of human reading.

The **Estimated activity** column and task details use saved message-change times directly, including older task history. Five or more distinct messages with the same recorded change within five seconds means **Bulk activity**; other recorded read/Inbox changes mean **One by one**. **—** means no relevant changes were recorded. This is a rough estimate only; scan duration, gaps and the old hidden `bulk_review` metadata do not gate classification. Existing scan metadata is preserved for compatibility, but the processor no longer updates it. No signup changes, additional Gmail requests, automatic rejection or payment changes are introduced. See [the estimator rules and limitations](BULK-ACTION-ESTIMATES.md).

## Contract and recovery

Documented endpoints are GET `/api/repo-api/settings`, POST `/api/repo-api/tasks`, and GET `/api/repo-api/tasks/{task_id}`. The only POST business fields are assignment_id, canonical email and settings_revision. The exact JSON bytes/hash, assignment and idempotency key are persisted before dispatch. Each HTTP retry retains them and signs fresh timestamp/nonce headers with the ASCII key, never hex-decoded. TLS verification is required; redirects and query strings are disabled.

Network failures, 503, 429 and nonce replay errors use bounded exponential backoff with jitter and Retry-After. Partial-queue 503 recovery retries the original POST. An uncertain SMTP attempt is never automatically resent. Identity conflicts and changed manifests require investigation, not a new task identity. Eligible service failures can be retried from admin review using the original request. Changing Cortex settings does not rewrite an attempted request. Failed access/API checks remain separate from observed message changes and cannot establish completion or a cheating decision.

Cortex owns its configured saved campaign, rendering/placeholders, selected IPs, sending settings and canonical mailbox deduplication/test whitelist. No local duplicate bypass or Repo tracking div is injected. SMTP acceptance, internal sender IDs and finished sending are not Gmail receipt evidence. The manifest's slot/attempt/RFC IDs remain immutable after acceptance.

## Database and background processing

Only the feature migrations `2026_10_17_000001` through `000005`, `2026_10_18_000001_add_worker_help_links_to_inbox_domain_settings`, `2026_10_18_000002_create_inbox_captcha_settings_table` and the October 19 feature migrations `000001_add_worker_attempt_numbers`, `000002_add_provider_to_inbox_captcha_settings`, `000003_add_bulk_review_evidence_to_inbox_tasks` , `000004_add_gmail_reaction_tracking` and `000005_add_gmail_sync_state_to_inbox_tasks` belong here. Legacy migrations do not completely describe the deployed schema: do not use indiscriminate migration or migrate:fresh in production. Migration 000004 adds domain worker settings, assignment entry mode and the frozen work list/timestamps without changing existing task policies. Migration 000005 links accounts to encrypted connections and saves assignment metadata. The October 18 migrations add nullable help-links JSON and a separate domain CAPTCHA-settings table; neither migration populates credentials or changes existing worker modes/policies. The October 19 migration adds `inbox_assignments.attempt_number` with default 1 and extends its unique identity to include that number. It does not create new attempts or rewrite task history. Rolling it back refuses to delete or merge existing repeat-attempt history. During deployment, public entry keeps its original behavior until the new column exists.

The durable worker is `php artisan inbox-tasks:process --limit=10`, run by the dedicated cron template every minute with flock. Per-request/task leases protect concurrent processing. Worker-page mailbox checks supplement this worker; the cron still provides outbox recovery and monitoring when the browser is closed. Neither the HTTP status nor check endpoint sends campaign messages.

Tests run with:

```
runuser -u www-data -- php vendor/bin/phpunit --do-not-cache-result
```

Feature tests use in-memory SQLite and synthetic keys/tokens with real HTTP requests prohibited. Actual PowerMTA-to-Gmail Message-ID preservation can be verified through the normal worker flow. Mocked tests and Cortex's loopback captures do not establish real delivery.

## Delete an account for another test

The authenticated domain administrator can open **Delete account** in the sidebar (`/inbox-tasks/admin/delete-account`). Enter an email to preview matching account IDs and related record counts, then type the same email again and confirm deletion. Gmail dot/plus/googlemail aliases are included on the current domain. Matching accounts on another domain are listed as a count and kept; the global signup duplicate check can still find them until they are separately removed by that domain's administrator.

Deletion removes matching `accounts` rows and their encrypted connections, assignments, tasks, durable dispatches, message manifests/attempts, deliveries, observations, related activity and `smtx_jobs_queue` entries for those accounts. It resolves the `inbox_assignments.account_id` foreign key by deleting children first. Shared job policies, projects, domain settings, integration credentials and unrelated accounts/tasks stay intact. Project account counters decrease by the number of deleted rows. A separate deletion audit records the administrator and counts, without preserving the deleted email or task identifiers.

Preview and confirmation require the same administrator, domain and session, a short-lived single-use token, CSRF validation and HTTPS. Deletion runs in one database transaction, rechecks the preview graph, refuses inconsistent cross-mailbox/domain links and active task/dispatch leases, and rolls everything back on error. Brief PostgreSQL table locks prevent new worker claims/registrations from changing the graph during deletion. Changed records require a fresh preview. Passwords, tokens, campaign bodies and project credentials never appear in the preview.

This removes local records only. It does not revoke Google's OAuth grant, delete Gmail messages, erase Cortex records, recall submitted messages or bypass Cortex campaign deduplication. Work already handed to a sender may still finish. The feature does not call Gmail, Cortex or SSH.
