an encouraging twitch bot overwatch coach
README.md

Roverwatch #

Roverwatch watches an Overwatch stream through Twitch’s official embedded player. It periodically captures what is visible on screen, asks a vision model what the screen shows, turns those observations into match and death events, and saves a reviewable record.

The project is built for evidence and debugging. Every important step keeps its timestamps, source frame, model response, deterministic interpretation, and failure information so a review can answer “what did Roverwatch see, and why did it decide that?”

Current implementation state #

The active product path is the Overwatch realtime evidence pipeline:

  • Captures the Twitch player on a configurable interval; the deployed CDK default is 2 seconds.
  • Sends the newest waiting frame to Amazon Bedrock Nova Lite, with enlarged upper-right, top-center, and kill-feed details.
  • Validates literal screen evidence before deterministic lifecycle code interprets it.
  • Tracks match boundaries, phases, numeric respawn-confirmed deaths, scoreboard OCR, map evidence, and hero timelines.
  • Stores each frame’s screenshot, raw model response, validated evidence, derived observation, timing, and tracking state under the session prefix.
  • Persists per-game mapName, mapEvidence, player name, hero timeline, scoreboard totals, and deduplicated eliminationEvents in games.json and manifest.json.
  • Publishes optional Twitch chat updates for lifecycle changes, accepted scoreboard snapshots, confirmed deaths, and local-player kill-feed matches.

Kill tracking is deliberately fail-closed: a kill is announced only when a readable kill-feed attacker matches a scoreboard-established local player name. A kill streak banner or an unreadable name is not enough. The raw frame JSON and screenshot remain the source of truth for auditing any announcement.

The short version #

Twitch stream
    ↓
Chrome + official Twitch embed
    ↓
JPEG screenshot
    ↓
latest-frame queue
    ↓
Bedrock vision model
    ↓
validated visual evidence
    ↓
match lifecycle + death episode tracking
    ↓
S3 session files + review.html

There is one active inference at a time. If screenshots arrive faster than the model can process them, Roverwatch keeps the newest waiting frame and marks older waiting frames as stale. This keeps the decision current instead of building an ever-growing queue.

What the system does #

  1. Starts Chrome and opens the Twitch embed for the configured channel.
  2. Waits for Twitch to report that playback is ready and actually playing.
  3. Captures screenshots at the configured interval.
  4. Sends the newest screenshot to the Overwatch vision processor.
  5. Validates the model response as literal visual evidence: for example, “a respawn countdown says 4” or “the post-match scoreboard is visible.”
  6. Uses deterministic code to decide match phases, start/end boundaries, deaths, map/player evidence, kill-feed attribution, and scoreboard updates.
  7. Writes session evidence and a self-contained HTML review page to S3.
  8. Stops cleanly when Twitch goes offline or the task receives SIGTERM, draining pending work and finalizing the review.

How a frame moves through the code #

The main orchestration lives in src/index.ts.

  • main() loads configuration, starts Chrome, creates the S3 store, and initializes the match session and vision processor.
  • The Twitch lifecycle loop waits for PLAYING, OFFLINE, and related player events.
  • The capture branch calls page.screenshot(). In realtime mode it submits an in-memory frame to LatestFrameProcessor; in capture-only mode it writes the JPEG directly to S3.
  • LatestFrameProcessor admits at most one frame for processing and replaces an older pending frame with a newer one.
  • OverwatchRealtimeProcessor sends the admitted frame to Bedrock, validates the response, records evidence, updates the match session, and optionally sends Twitch chat messages.
  • MatchSessionRecorder stores the durable timeline and eventually produces manifest.json, games.json, history.json, frame evidence JSON, and review.html.

How games are separated #

src/overwatch/match-tracker.ts and src/overwatch/game-summary.ts interpret the ordered frame timeline. A game gets a matchId, start/end times, phases, death events, scoreboard values, and the list of timeline sequence numbers that belong to it.

The review page uses those sequence numbers to group frames under Game 1, Game 2, and so on in a frame inspector. Choose a game, then use the frame list or Previous/Next buttons to see each screenshot and its interpretation. Frames that cannot be assigned safely remain under “Unassigned frames”; they are never silently discarded.

The review page is generated by reviewHtml() in src/overwatch/match-session.ts. Its tabs provide:

  • Games: summaries and per-game metrics.
  • Deaths: replay frames around each confirmed death and record review notes.
  • Scoreboards: accepted scoreboard observations.
  • Post-match: post-match screenshots.
  • Problems: invalid or conflicting evidence.
  • Raw frames: a selected screenshot, evidence, and annotation controls, with a frame list grouped by game. Use the invalid or unreviewed filter to narrow the list.

The renderers build page sections directly from the session manifest. src/overwatch/ui.ts supplies the shared page shell and styles; src/overwatch/review-ui.ts builds game and frame navigation; src/overwatch/review-annotations.ts supplies the browser controls. No step rewrites an already generated HTML document.

The session index shows games, maps, heroes, outcomes, and review warnings. Filter it by date, map, hero, result, or review status. Player history shows averages across identity-confirmed games, hero usage, map results, death counts, and data quality. Scoreboard totals are per game and are not assigned to each hero after a swap. The usage budget has the same navigation and visual layout.

Annotations are saved in the browser’s local storage and can be exported as JSON. They do not rewrite the original model evidence. After changing the renderer, rebuild an existing session review with npm run review:rebuild -- SESSION_ID BUCKET and rebuild the session index and player history with npm run review:index -- BUCKET to see the new pages for older data.

Important design choices #

  • Twitch is accessed through the documented JavaScript embed. Roverwatch does not inspect the iframe, extract media URLs, or use undocumented playback APIs.
  • A death is only confirmed from a numeric RESPAWN IN countdown. A player kill is attributed only when the left-side kill-feed name matches the known local scoreboard identity.
  • The model describes visible evidence; deterministic code makes lifecycle decisions from that evidence.
  • .capture.jpg objects are the only S3 objects that trigger inference in the asynchronous path. latest.jpg, results, and failure artifacts cannot create an inference loop.
  • Evidence is append-oriented and kept until explicitly removed. A review can be rebuilt from stored frames and JSON.
  • Secrets are read at runtime from AWS Secrets Manager and are never placed in source code or logs.

Run locally #

Prerequisites:

  • Node.js 22+
  • Google Chrome or Chromium
  • AWS credentials that can read/write the configured S3 bucket and call Bedrock
  • A Twitch channel login

Install and type-check:

npm install
npm run build

Run the browser worker:

TWITCH_CHANNEL=CHANNEL_LOGIN \
SCREENSHOT_BUCKET=BUCKET_NAME \
EMBED_URL=https://YOUR_CLOUDFRONT_HOST/ \
AWS_REGION=us-east-1 \
CHROME_PATH=/usr/bin/google-chrome \
npm run dev

Use npm run check:chrome to verify that Chrome can launch and load the embed without running the full capture loop.

Tests and useful commands #

npm test                 # automated tests
npm run build            # TypeScript check
npm run overwatch:test   # fixture-based Overwatch checks
npm run overwatch:evaluate
npm run overwatch:workbench
npm run review:recover   # rebuild a review from stored evidence
npm run dataset:export   # export reviewed evidence as JSONL + images

The test fixtures under test-fixtures/ are intentionally offline. They let lifecycle, OCR, review, and export behavior be tested without Twitch, Chrome, Bedrock, or S3.

AWS shape #

In production, CDK deploys:

  • a Fargate browser worker;
  • an S3 artifact bucket for screenshots and session evidence;
  • CloudWatch logs;
  • an API Gateway/Lambda EventSub endpoint;
  • EventSub-driven ECS scaling: one task while the channel is live, zero tasks while it is offline;
  • the IAM permissions and Secrets Manager references needed at runtime.

The worker uses a public Fargate IP so Chrome can reach Twitch without a NAT Gateway. The task role is restricted to the session artifact prefix.

Deployment requires an AWS account bootstrapped for CDK and Twitch credentials stored in Secrets Manager. See docs/ for the deeper deployment, latency, prompt-evaluation, and dataset notes. Historical experiments and retired prototypes are in archive/.

Where to start reading the code #

  1. src/index.ts — application lifecycle and capture loop.
  2. src/realtime/latest-frame.ts — newest-frame queue behavior.
  3. src/overwatch/processor.ts — vision processing and evidence recording.
  4. src/overwatch/match-session.ts — durable session files and HTML review generation.
  5. src/overwatch/match-tracker.ts — game boundaries and lifecycle events.
  6. src/overwatch/death-episodes.ts — death replay windows.
  7. src/overwatch/types.ts — evidence and manifest shapes.
  8. src/overwatch/chat.ts — structured Twitch announcements and deduplication.
  9. src/overwatch/maps.ts — canonical map names and OCR aliases.

Current development focuses on Overwatch screenshot evidence, match/session review, and repeatable prompt evaluation. The completed player-only latency reports and the retired generic shape-recognition spike are preserved under archive/.

Roverwatch captures Twitch's official embedded player and records Overwatch visual evidence for review. An optional realtime Bedrock path extracts literal screenshot cues; deterministic code builds match lifecycles and summaries. Debuggability is a product requirement: processing stages, source evidence, and timing are recorded in structured logs and per-frame S3 records.

The central architecture is now proven: on 2026-08-28, the paulchinjr channel transitioned from offline to live, the official player emitted PLAYING, Fargate captured JPEGs approximately every 10 seconds, S3 accepted both timestamped objects and latest.jpg, and a downloaded JPEG visibly contained the live broadcast.

Current status #

The current development phase is Overwatch screenshot evidence, match/session review, and repeatable prompt evaluation. Completed latency reports are in archive/early-latency/; the retired shape-recognition implementation is in archive/shape/.

  • Proven: local Chrome launch, production Docker image, CDK deployment, CloudFront embed delivery, offline detection, live playback, periodic screenshots, task-role S3 uploads, and visual verification of a live frame.
  • Observed session: 89c97e36-85c8-49e7-be62-6d0d7e42b053 reached PLAYING and uploaded captures successfully. Memory stayed roughly within 145–157 MB RSS during the observed period.
  • Current operating posture: CDK now declares zero browser tasks at rest. Twitch EventSub can scale the service to one on stream.online and back to zero on stream.offline.
  • EventSub proven end to end: stream.online started the Fargate viewer and stream.offline stopped it, returning the service to zero tasks at rest.
  • Current measured behavior: with a two-second setting and Vision Lab's dedicated /test screen, captures averaged 2.16 seconds apart, all 19 observable source transitions were classified correctly, and changed captures reached chat in 2.08 seconds on average. End-to-end source-to-chat latency averaged 16.20 seconds because 11–19 seconds accumulated before the changed frame reached Roverwatch's Twitch player.
  • CPU-scaling finding (2026-09-17): controlled player-only experiments showed severe Twitch-player buffering at 1 vCPU/2 GiB (mean broadcaster latency 53.32 seconds, maximum 79.98 seconds) but stable playback at 2 vCPU/4 GiB (mean 3.26 seconds) and 4 vCPU/8 GiB (mean 1.77 seconds). A follow-up 4-vCPU production-path run with 2,804 captures at 250 ms kept latency stable at 1.36 seconds mean; screenshot duration averaged 31.6 ms. See live-edge validation.
  • Historical acquisition finding: controlled runs showed stable player latency at 2 vCPU/4 GiB and 4 vCPU/8 GiB, while a 1-vCPU run fell behind. See live-edge validation and the archived run outputs.
  • Real Overwatch extraction remains experimental: the focused lifecycle contract classifies game phase, confirms local death only from a numeric RESPAWN IN countdown, reads the persistent blue/red alive counts, captures the highlighted local scoreboard row, and now reads upper-right kill-feed rows for conservative local-player elimination announcements. The latest production run accumulated more than 100 seconds of player latency, so no production-accuracy or useful-live-latency claim is made. See docs/overwatch-evaluation.md and docs/live-edge-validation.md.
  • Current dataset workflow: the offline dataset:export command exports durable frame evidence and copied images to JSONL, preserves sessionId/gameId split groups, supports --reviewed-only, and writes label-count/imbalance reports. It is read-only with respect to production evidence and does not add inference calls. See docs/dataset-export.md.
  • Prompt update deployed (2026-09-20): v7 explicitly recognizes ASSEMBLE YOUR TEAM together with hero choices as hero selection, while role queue remains excluded. Historical session evidence was not rewritten.
  • Current review/evaluation workflow: finalized sessions expose screenshot classifications, raw evidence, timing, invalid/unreviewed filters, quick correction controls, and annotation export. The localhost prompt workbench supports same-frame iterations and paired baseline/candidate scoring on complete, pre-scored fixture sets. Reviewed-session dataset authoring and immutable revisions remain future work. See prompt workbench and evaluation workspace.

Architecture #

viewer request -> CloudFront HTTPS -> CloudFront Function embed page -> official Twitch player
                                      (private empty S3 origin is a required placeholder)
Twitch EventSub -> API Gateway -> signature-verifying Lambda -> ECS desired count 0 or 1
public-subnet Fargate -> Google Chrome -> Playwright
         |                   |
         +-> CloudWatch      +-> screenshots / failure evidence -> private S3 bucket
                                    |
                                    +-> latest-frame queue -> Bedrock -> session evidence/review
                                                           \-> optional diagnostic Twitch chat

The worker uses a single realtime Overwatch inference path with one request in flight. If B, C, and D arrive while A is being inferred, only D remains pending; B and C increment framesDroppedAsStale. Fresh observations take priority over complete processing history.

CDK creates a VPC with public subnets and no NAT Gateway. When desired count is one, the Fargate service receives a public IP and only needs outbound traffic. Its task role can put objects only under sessions/* in the artifact bucket. A CloudFront Function returns the small embed HTML directly; an otherwise-empty private S3 origin satisfies CloudFront's origin requirement without CDK deployment-helper Lambdas. CloudFront does not proxy Twitch video: Chrome loads Twitch directly. Session artifacts have no automatic expiration and remain until explicitly deleted.

The EventSub HTTP API is always available but has no continuously running server. Its Lambda verifies Twitch's HMAC signature and rejects messages older than 10 minutes before changing ECS. Duplicate online/offline notifications are safe because the handler sets an absolute desired count. A separate on-demand setup Lambda reads Twitch credentials and the webhook secret from Secrets Manager at runtime and creates the subscriptions; secret values are never stack parameters, source code, or command output.

Periodic captures use sessions/<session-id>/screenshots/<timestamp>.capture.jpg. Only .capture.jpg keys trigger vision processing, so latest.jpg, failure evidence, and result JSON cannot trigger inference or create a loop. Receipts use the matching sessions/<session-id>/results/<timestamp>.json key. The processor runs outside the VPC, so normal Lambda networking reaches Twitch without a NAT Gateway.

The page intentionally uses Twitch's documented JavaScript embed. parent is derived from its CloudFront hostname. It never inspects the iframe, discovers media URLs, suppresses Twitch UI/ads, or calls undocumented playback APIs.

Prerequisites #

  • Node.js 22 or newer
  • Docker
  • AWS CLI v2 with working credentials
  • An AWS account bootstrapped for CDK
  • A Twitch developer application for EventSub

Install and verify #

npm install
npm run build
npm test

Experiments #

The latency spike records Twitch playback statistics and HTML video telemetry once per second, Twitch lifecycle events, screenshot timing, and inference admission. Each run is written immutably under experiments/<run-id>/ in the screenshot bucket as metadata.json, telemetry.jsonl, summary.json, and report.html. The report includes latency/buffer/capture/inference statistics and a deterministic diagnostic hypothesis; it is not a root-cause assertion.

Start a named run with npm run experiment -- start baseline-1vcpu-player-only, then deploy/start the worker with SCREENSHOTS_ENABLED=false INFERENCE_ENABLED=false (or set those values in the ECS deployment configuration). When Twitch goes offline, open the generated report.html. List historical runs with SCREENSHOT_BUCKET=... npm run experiment -- list; compare two runs with SCREENSHOT_BUCKET=... npm run experiment -- compare RUN_A RUN_B.

The first matrix is: 1 vCPU/2 GiB player-only (false/false), 1 vCPU/2 GiB screenshots every 5 seconds/no inference (true/false), and 1 vCPU/2 GiB normal inference (true/true), followed by the same three configurations at 2 vCPU/4 GiB. CPU and memory are recorded from ECS metadata environment values. Change one configuration variable per deployment; do not change playback behavior during this spike.

Deploy #

Create a Twitch application in the Twitch developer console. Store its credentials in AWS Secrets Manager under roverwatch/twitch-app as JSON with exactly these field names:

{
  "clientId": "from Twitch",
  "clientSecret": "from Twitch"
}

Use the AWS console to enter those values so they do not pass through shell history or agent logs. The generated EventSub HMAC secret is a separate CDK-managed secret.

For chat, create a second Secrets Manager JSON secret named roverwatch/twitch-chat in the AWS console:

{
  "clientId": "Twitch application client ID",
  "accessToken": "user access token without an oauth: prefix",
  "refreshToken": "refresh token",
  "botUserId": "numeric ID of the Twitch user sending messages",
  "broadcasterId": "40366699"
}

The access token must represent botUserId and include user:write:chat. Register http://localhost:3000 as an OAuth redirect URL on the same Twitch application, then let Roverwatch perform the authorization-code exchange and update the chat secret without printing either token:

AWS_REGION=us-east-1 \
TWITCH_CHANNEL=CHANNEL_LOGIN \
npm run twitch:authorize

Open the URL printed by the command and sign in as the Twitch account that will send chat messages. The callback verifies OAuth state, checks the client, user, and user:write:chat scope, resolves the configured broadcaster, and writes the user and rotated token pair directly to roverwatch/twitch-chat. Optional TWITCH_APP_SECRET_NAME, TWITCH_CHAT_SECRET_NAME, and TWITCH_OAUTH_REDIRECT_URI settings override the defaults.

At runtime the Vision Processor validates the token before a chat send. An expired access token is exchanged using the confidential application's refresh token, and both tokens returned by Twitch are persisted because Twitch may rotate the refresh token. A revoked or rejected refresh grant produces a completed REAUTH_REQUIRED receipt and updates detection state instead of failing the Lambda invocation. This prevents permanent authorization failures from sending the same S3 event through asynchronous retries and repeating Bedrock inference. Run npm run twitch:authorize again only when this condition appears.

Deploy with the channel login, not its display name. The deployment wrapper gives CDK an isolated temporary Docker configuration so ECR login does not invoke Docker Desktop's desktop.exe credential helper, serializes asset publication to avoid concurrent config writes, and removes the temporary ECR authorization on both success and failure:

aws sts get-caller-identity
npx cdk bootstrap
npm run synth
npx cdk diff
npm run deploy -- \
  --parameters TwitchChannel=CHANNEL_LOGIN \
  --parameters BedrockModelId=amazon.nova-lite-v1:0 \
  --parameters CaptureIntervalMs=2000

For a player-only capture run, disable screenshots/inference in the deployment configuration. For normal Overwatch processing, the worker uses the realtime path.

The service deploys with desired count zero. After deployment, invoke the output named ConfigureEventSubFunctionName once:

EVENTSUB_SETUP_FUNCTION="$(aws cloudformation describe-stacks \
  --stack-name RoverwatchStack \
  --region us-east-1 \
  --query "Stacks[0].Outputs[?OutputKey=='ConfigureEventSubFunctionName'].OutputValue | [0]" \
  --output text)"

aws lambda invoke \
  --function-name "$EVENTSUB_SETUP_FUNCTION" \
  --region us-east-1 \
  /tmp/roverwatch-eventsub-setup.json

cat /tmp/roverwatch-eventsub-setup.json

The CloudFormation output key is ConfigureEventSubFunctionName, matching the CDK construct and the name shown by cdk deploy. An earlier walkthrough incorrectly called it EventSubSetupFunctionName. Querying that nonexistent key does not produce an AWS error; it produces an empty string, which then causes aws lambda invoke to fail with Invalid length for parameter FunctionName. If the printed function name is empty, compare the query with the exact output names printed at the end of deployment.

Both subscriptions should report enabled, webhook_callback_verification_pending, or already_enabled. Twitch verifies the HTTPS callback immediately. If the channel is already live when subscriptions are created, no historical online event is sent; stop/start the stream or scale the service to one manually for that test.

amazon.nova-lite-v1:0 is the default because the live us-east-1 Bedrock catalog reports that original Nova Lite accepts image input, returns text, and supports on-demand inference. BEDROCK_MODEL_ID remains configurable in the Lambda and local test; the CDK BedrockModelId parameter injects it at deployment. Do not substitute a model until its current catalog entry confirms image input and Converse support. Inference-profile overrides may require both the profile ARN and routed foundation-model ARNs in IAM.

The outputs give the embed URL, screenshot bucket, and log group. A continuously running service has idle cost; destroy it when the experiment ends. For an initial diagnostic deployment, add --no-rollback so CloudFormation preserves failed ECS resources long enough to inspect them:

npx cdk deploy --parameters TwitchChannel=CHANNEL_LOGIN --no-rollback

At the current task size (1 vCPU, 2 GB Linux/x86 in us-east-1), continuous Fargate compute plus its public IPv4 address costs approximately $39.70 per 730-hour month before S3, CloudWatch, and CloudFront usage. Desired count zero eliminates that idle compute/IP charge. The original 10-second cadence produced roughly 518,000 S3 PUTs per continuously live month because each interval writes a timestamped object and latest.jpg; a two-second cadence would produce roughly 2.63 million PUTs and 1.31 million Bedrock inferences per continuously live month. Actual usage is limited to time the channel is live.

Stop compute without destroying evidence #

Stopping an individual task is not sufficient because the ECS service replaces it. Scale the service to zero:

ROVERWATCH_CLUSTER="$(aws cloudformation describe-stack-resources --stack-name RoverwatchStack --region us-east-1 --query "StackResources[?ResourceType=='AWS::ECS::Cluster'].PhysicalResourceId | [0]" --output text)"
ROVERWATCH_SERVICE="$(aws cloudformation describe-stack-resources --stack-name RoverwatchStack --region us-east-1 --query "StackResources[?ResourceType=='AWS::ECS::Service'].PhysicalResourceId | [0]" --output text)"

aws ecs update-service \
  --cluster "$ROVERWATCH_CLUSTER" \
  --service "$ROVERWATCH_SERVICE" \
  --desired-count 0 \
  --region us-east-1

aws ecs wait services-stable \
  --cluster "$ROVERWATCH_CLUSTER" \
  --services "$ROVERWATCH_SERVICE" \
  --region us-east-1

Confirm desired, running, and pending are all zero:

aws ecs describe-services \
  --cluster "$ROVERWATCH_CLUSTER" \
  --services "$ROVERWATCH_SERVICE" \
  --region us-east-1 \
  --query 'services[0].{desired:desiredCount,running:runningCount,pending:pendingCount}'

Local run #

Use the deployed EmbedUrl and an artifact bucket your active AWS identity may write to:

TWITCH_CHANNEL=CHANNEL_LOGIN \
SCREENSHOT_BUCKET=BUCKET_NAME \
EMBED_URL=https://CLOUDFRONT_HOST/ \
AWS_REGION=us-east-1 \
CHROME_PATH=/usr/bin/google-chrome \
npm run dev

No static credentials are supported or needed. Locally, the normal AWS SDK credential chain is used; in ECS, it resolves the task role.

Twitch diagnostics #

Test Twitch independently of Bedrock. This command intentionally sends Roverwatch integration test using the runtime secret:

AWS_REGION=us-east-1 \
TWITCH_CHAT_SECRET_NAME=roverwatch/twitch-chat \
npm run twitch:test

The local test and deployed processor both validate and refresh authorization before sending. Look for tokenRefreshed locally or twitch.auth_validated, twitch.auth_refreshed, and twitch.reauthorization_required in processor logs. Token values are never logged.

Inspect processor activity and receipts after deployment:

aws logs tail /roverwatch/browser-worker --follow --region us-east-1
aws s3 ls s3://BUCKET_NAME/sessions/ --recursive | grep '/results/'

Match-session records include the source frame, literal visual evidence, deterministic interpretation, and processing timings. Failed realtime inferences are logged with their processing stage and validation evidence.

Latency evaluation #

Use these layers consistently; combining them hides which system owns the delay:

  • Source-to-render latency: Vision Lab publishedAt to its renderedAt.
  • Render-to-player latency: Vision Lab renderedAt to the matching revision visible in Fargate. This currently combines OBS, Twitch ingest, transcoding, distribution, and player buffering.
  • Roverwatch reaction latency: Fargate capturedAt to the Twitch chat response. This is Roverwatch's optimization target.
  • Full response latency: Vision Lab renderedAt to the Twitch chat response.

The initial realtime target is Roverwatch reaction p50 below 1000 ms; p95 below 1000 ms is the stretch target. The first live realtime latency run on 2026-08-29 met the capture-to-decision form of both targets: across the 40 completions in the Vision Lab window, p50 was 846 ms, p95 was 976 ms, and max was 1.28 seconds. This fixture intentionally presented transport beacons as blank, so it produced no chat sends and does not yet establish capture-to-chat percentiles.

That run captured 106 frames, completed 57 inferences, deliberately replaced 49 stale frames, and had zero processing failures over the full worker session. Bedrock averaged 649 ms and inference queue wait averaged 162 ms. The 250 ms setting produced an actual 345 ms average cadence because the loop currently sleeps after screenshot work; screenshot capture itself averaged 86 ms. Scheduling against monotonic 250 ms deadlines would make the setting accurate, but would likely save only about 50 ms of average observation delay. It cannot provide a seconds-scale improvement while inference remains serialized.

The seconds-scale opportunity is upstream of Roverwatch. Twitch reported roughly 10–12 seconds of broadcaster latency during the run, and that value increased toward the end. This dominates the sub-second capture-to-decision path. The next architecture decision is therefore whether the official player can be kept closer to its live edge. If not, meaningful multi-second improvement requires a lower-latency input such as a streamer-side OBS/local capture integration or another permitted direct-media source before Twitch distribution. Any direct Twitch media approach must be verified against current Twitch-supported integration and access rules before implementation.

The official player is polled through Twitch's documented getPlaybackStats() API approximately once per second. twitch.playback_stats safely records available hlsLatencyBroadcaster, bufferSize, fps, resolution, bitrate, and skipped-frame fields. Fields are optional and telemetry failures are isolated from capture and inference.

Summarize a deployed session without manually reading CloudWatch lines:

AWS_REGION=us-east-1 npm run latency:report -- SESSION_ID

The report includes frames captured/inferred/dropped, capture cadence and duration, Bedrock/decision/chat/reaction percentiles, player latency and buffer beginning/middle/end trends, processing failures, and memory. It can also consume a saved aws logs filter-log-events response:

npm run latency:report -- --file /path/to/log-export.json

When Vision Lab exposes /api/time, estimate evaluation clock offset with multiple midpoint samples:

npm run latency:clock -- https://VISION_LAB/api/time

The command averages the three lowest-RTT samples and reports RTT and half-RTT uncertainty. It reduces clock-skew error but does not claim global clock synchronization.

For exact Vision Lab transport latency, deploy with decoding explicitly enabled:

npm run deploy -- --require-approval never \
  --parameters TwitchChannel=paulchinjr \
  --parameters CaptureIntervalMs=250 \
  --parameters DecodeVisionLabBeacon=true

The deterministic decoder samples the finalized vision-lab-latency-v1 6-row × 8-column beacon directly from each complete 16:9 JPEG; it does not use Bedrock. Two header rows identify the contract and four rows encode the uint32 revision MSB-first. Each cell is classified as black, white, or ambiguous from its center-pixel luminance. Unsupported transforms and invalid headers are unreadable; threshold-gap samples are ambiguous. These results are logged before latest-frame inference replacement, so transport analysis includes frames that are intentionally dropped from vision processing.

After the stream, join the worker session to a finalized Vision Lab export containing beaconSchemaVersion: "vision-lab-latency-v1":

AWS_REGION=us-east-1 npm run latency:beacon -- WORKER_SESSION_ID ./vision-lab-latency-export.json

For an offline CloudWatch export:

npm run latency:beacon -- --file ./worker-log-events.json ./vision-lab-latency-export.json

The report lists every exported revision with renderedAt, earliest capturedAt, exact renderedToCapturedMs, and capture count, followed by p50/p95 across matched revisions. Missing revisions, ambiguous/unreadable captures, and decoded revisions outside the export remain explicit and are excluded—not silently converted or folded into the percentile. The older checked-in latency export predates beaconSchemaVersion; it remains historical evidence but is intentionally rejected by this finalized-schema report.

First finalized-beacon result #

The 2026-08-30 run joined Vision Lab session b1df4ed7-307e-451b-bad4-220c22724e9f to worker session 679a40ba-5b46-4c10-a787-39e828f7562f. The export was valid: 60 unique revisions (466–525) each had an authoritative renderedAt. Roverwatch captured 235 frames and completed 166 inferences without a processing failure, but decoded no beacon revisions. The exact report therefore retained all 60 revisions as missing and correctly produced no render-to-capture p50/p95.

Of the 235 beacon attempts, 157 had an invalid header and 78 contained an ambiguous cell. Header failures were stable rather than random, and later frames repeatedly measured payload cell (3,5) at luminance 97, one point inside the ambiguous range. Twitch reported 1920×1080 video displayed at 1280×720, so the broad aspect ratio was correct; a smaller video-surface offset/scale difference or cumulative OBS/Twitch compression remains unproven. No session JPEG was persisted because the vision state stayed none, leaving insufficient evidence to distinguish those causes. The next decoder diagnostic must save a bounded sample—one first invalid-header JPEG and one first ambiguous JPEG—with expected sample coordinates overlaid or recorded.

Beacon decoding also affected the experiment loop: average capture cadence increased from the prior 345 ms to 467 ms, capture duration averaged 118 ms, and capture-to-inference start averaged 325 ms. This overhead matters for freshness but is still small beside video delivery. Twitch broadcaster latency averaged 14.5 seconds and grew from 8.1 seconds in the first third to 20.5 seconds in the last third; buffer size also trended upward. A practical OBS-to-chat response remained an estimate of video/player delay plus roughly one second of Roverwatch processing because neither a revision nor a chat send could be correlated in this blank-beacon run.

Player-buffer experiments #

The buffer-growth problem is now a named follow-up, not an incidental observation. Test these in order with the same finalized latency sequence:

Experiment Expected benefit Main tradeoff
Increase Fargate from 1 vCPU/2 GB to 2 vCPU/4 GB determine whether Chrome is losing the live edge under CPU contention roughly doubles running compute cost
Request 720p instead of 1080p reduce network, video decode, screenshot, and beacon work less detail for production vision
Capture every 500 ms instead of 250 ms leave more CPU for playback and reduce stale work adds roughly 125 ms of average observation wait versus a true 250 ms cadence
Decode a cropped region or use a worker thread/latest-frame decoder remove Sharp work from the synchronous capture path additional concurrency and lifecycle complexity
Reload/recreate the player after sustained excessive latency recover toward the live edge and bound accumulated delay several-second blind spot; needs hysteresis, cooldown, and a retry cap
Pause/play or supported seek experiments potentially cheaper recovery than full reload may resume the same stale buffer or be unreliable for live playback
Streamer-side OBS/local frame delivery remove Twitch distribution and player buffering from the vision path requires installation/configuration on the broadcaster's machine

The latest real-game run showed that a resource matrix beginning with full Overwatch inference changes too many variables at once. The replacement plan begins with a player-only run, then adds screenshot cadence, fast perception, and semantic phase understanding one layer at a time. The live-edge acceptance gate, exact run order, bounded evidence policy, and fallback decision are in docs/live-edge-validation.md. Do not adopt private Twitch HLS playlist discovery as the default: it is an unsupported, expiring-token integration and cannot remove delay already present before segments are published.

Death-centered Overwatch evidence #

The session index links to the generated Fargate + Bedrock usage budget at /sessions/budget.html. It reports monthly cumulative and per-session estimates; see usage budget details, including rates, assumptions, and the manual npm run budget:rebuild refresh command.

The production Overwatch path keeps one Nova Lite request containing the legacy full frame plus one upper-right detail from that same frame. Its narrow prompt asks only for literal visible cues: normal first-person HUD, hero-select interface, scoreboard table, exact preparation text, KILL CAM, numeric RESPAWN IN, explicit match result, Play of the Game, searching/loading/map interfaces, round-transition text, post-match stats, game-mode selection, menu, and the OBS SRC UTC clock. Prompt version overwatch-visible-evidence-v2-death-detail and schema overwatch-visible-evidence-v1 do not request heroes, health, ultimate charge, team counts, objectives, scoreboard rows, strategy, or kill-feed entries. TypeScript converts those cues into the compatibility FrameObservation and owns all temporal interpretation.

A readable numeric RESPAWN IN <number> is the only authoritative local-death signal. KILL CAM, red damage effects, low health, or an inferred dead-looking scene cannot emit PLAYER_DIED. A continuous countdown produces one event; an unreadable intermediate frame does not create another; a later normal first-person HUD confirms respawn. Search/game-found and two-frame-confirmed screen-phase transitions are deterministic and never cloned from an earlier observation.

Diagnostic chat remains off by default. When TWITCH_GAME_STATE_CHAT=true, Roverwatch sends concise messages only when the recognized game phase changes, when OCR reads a changed scoreboard, for confirmed per-game death counts, and for final game tallies. Scoreboard messages include the player name, hero, map/mode, and readable E/A/D and damage/healing/mitigation values; identical snapshots are suppressed and changed snapshots are rate-limited. Detailed timing and publication timestamps remain in structured logs, not chat. No per-frame HUD/timing summaries or periodic state heartbeat are sent.

Every attempted Overwatch inference is part of a first-class match session under sessions/<session-id>/match/. Its JPEG and evidence record are paired as frames/<frame-id>.jpg and .json. Each record includes capturedAt, model/prompt/schema versions, the raw Bedrock response, validation errors, literal visualEvidence, deterministic derived state/events, and timing. sourceVideoAge is recorded independently from inferenceQueueWaitMs, modelLatencyMs, and captureToObservationMs, using the OBS source clock when readable and Twitch playback statistics as a named fallback.

The recorder retains a bounded rolling window of frame references covering the prior 20 seconds (at most 16 frames). Every confirmed death creates deaths/death-NNN.json with the pre-death frames, death frame, respawn value, source-video age at death, and any scoreboard frame in the window or within 10 seconds afterward. manifest.json, history.json, and review.html all expose these DeathEpisode records; the review begins with horizontal death timelines whose thumbnails link to the full chronological frame cards.

Normal stream.offline and SIGTERM shutdown stop new capture admission immediately, discard a queued stale frame, finish the one active inference, flush evidence, announce completion when chat is enabled, and write manifest.json plus review.html. Finalization has a 110-second application deadline inside Fargate's maximum 120-second stop timeout. The manifest is the chronological session timeline and review.html places each screenshot beside the validated interpretation and links its raw evidence.

The artifact bucket remains private, but a dedicated read-only CloudFront distribution makes sessions/* publicly viewable over HTTPS. This includes screenshots, raw Bedrock output, observations, and manifests, so do not record a stream containing information you do not intend to publish. Each review card embeds the complete frame JSON beside its screenshot and also links the standalone .json object. The finalized match_session.finalized log contains the exact publicReviewUrl; the stack also outputs PublicReviewBaseUrl.

aws s3 cp s3://BUCKET/sessions/SESSION_ID/match ./match-review --recursive
open ./match-review/review.html

The public URL has this shape:

https://PUBLIC_REVIEW_DOMAIN/sessions/SESSION_ID/match/review.html

The browseable session list is always available at:

https://PUBLIC_REVIEW_DOMAIN/sessions/index.html

Export corrections from a review with Export annotations JSON, then persist them beside the session:

npm run review:ingest -- SESSION_ID ./roverwatch-SESSION_ID-annotations.json

The annotation file is stored as sessions/SESSION_ID/match/annotations.json. Each correction is keyed by frameId, joining the exact screenshot, original model output, and reviewer feedback.

Build a local regression dataset automatically from those annotations:

npm run feedback:build -- SESSION_ID ./roverwatch-SESSION_ID-annotations.json ./datasets/session-SESSION_ID
npm run overwatch:evaluate -- ./datasets/session-SESSION_ID/cases

The builder uploads the annotations, downloads only annotated screenshots and evidence, writes one frameId.jpg plus frameId.expected.json per case, and creates feedback-manifest.json. The generated expected files are the bridge from review to measurable prompt/decision-logic changes. Keep datasets split by session; do not mix adjacent frames randomly between development and test sets.

Each session review presents the model's classification prominently beside every screenshot, with source-video age, queue/model timing, validation errors, raw literal evidence, and deterministic derived state. Use the invalid/unreviewed filter to work through a game efficiently, then use the quick literal-correction buttons or JSON/text correction field, mark reviewed fields, and export one annotation file. Compact history.json removes null compatibility fields and confidence metadata; raw per-frame evidence remains linked. The primary historical unit is the evidence-backed DeathEpisode, not an attempted reconstruction of every HUD value.

Corrections are deliberately a later labeling operation: the immutable frame JSON and JPEG form a stable source pair from which a corrected label can be created without overwriting what the model originally said.

Prompt-candidate loop #

Reviewed annotations do not silently change production. To test a prompt candidate, copy the current prompt text into a candidate file, edit only the candidate, and evaluate both versions against the same reviewed dataset:

node --import tsx scripts/print-prompt.ts > ./candidate-v4.txt
# edit ./candidate-v4.txt

OVERWATCH_EVALUATION_DETAILS=true \
OVERWATCH_EVALUATION_REPORT=./reports/baseline.json \
npm run overwatch:evaluate -- ./datasets/session-SESSION_ID/cases

OVERWATCH_PROMPT_CANDIDATE=./candidate-v4.txt \
OVERWATCH_PROMPT_CANDIDATE_VERSION=overwatch-visible-evidence-v4-candidate \
OVERWATCH_EVALUATION_DETAILS=true \
OVERWATCH_EVALUATION_REPORT=./reports/candidate.json \
npm run overwatch:evaluate -- ./datasets/session-SESSION_ID/cases

npm run prompt:compare -- \
  ./reports/baseline.json \
  ./reports/candidate.json \
  ./reports/comparison.json

The comparison reports field-level improvements and regressions plus lifecycle-score changes. A candidate is promoted only after it improves the intended fields without unacceptable regressions: update src/overwatch/prompt.ts, bump OVERWATCH_PROMPT_VERSION, run the fixture/evaluation tests, and deploy. The candidate-file override is evaluation-only and cannot change a live worker.

For fast, isolated inspection of one already-captured screen, start the local workbench:

SCREENSHOT_BUCKET=YOUR_SCREENSHOT_BUCKET AWS_REGION=us-east-1 npm run overwatch:workbench

Open http://127.0.0.1:4173, enter a session ID to browse its match/frames/ screenshots, or paste a screenshot S3 key directly. The page shows the stored full frame and the exact upper-right detail crop sent to Bedrock. Edit the production prompt in place (or reset it), then rerun the same frame as often as needed. Each result separates raw Bedrock text, parsed literal evidence, normalized observation, and the independent scoreboard-layout override. No lifecycle or neighboring-frame context is supplied. The local server uses your AWS credentials for read-only S3 access and Bedrock invocation; it binds only to localhost. Set PORT or BEDROCK_MODEL_ID to override defaults. These single-frame experiments do not alter production prompts or stored session data.

Local fixture workflow #

Only use Overwatch screenshots captured from gameplay you own and are permitted to retain. Fixture and optional expected-file guidance is in test-fixtures/overwatch/README.md.

AWS_REGION=us-east-1 npm run overwatch:test -- test-fixtures/overwatch/frame.jpg
AWS_REGION=us-east-1 npm run bedrock:screenshot-evaluate -- test-fixtures/overwatch

The one-frame command prints raw and validated literal evidence, its deterministic interpretation, tokens, and latency without sending chat. The directory evaluator requires one adjacent *.expected.json for every JPEG/PNG before making any billable Bedrock calls. Expected files are partial flat overwatch-visible-evidence-v1 values, so only literal cues named in the fixture are scored. The evaluator also replays chronological sequence files through the deterministic lifecycle tracker and exits nonzero for invalid responses, sequence mismatches, or fields below OVERWATCH_EVALUATION_MIN_ACCURACY (default 1). Set OVERWATCH_EVALUATION_RUNS=3 to measure repeatability, OVERWATCH_EVALUATION_DETAILS=true to include literal evidence, derived observations, and raw responses, or OVERWATCH_EVALUATION_REPORT=./report.json to save the report.

Exact manual live workflow #

First deploy observation-only mode. This keeps chat safely disabled while validating real screenshots:

npm run deploy -- --require-approval never \
  --parameters TwitchChannel=CHANNEL_LOGIN \
  --parameters CaptureIntervalMs=250 \
  --parameters TwitchGameStateChat=false

Then:

  1. Start your Twitch stream with your own Overwatch gameplay. EventSub should raise ECS desired count from zero to one.
  2. Follow aws logs tail /roverwatch/browser-worker --region us-east-1 --follow and confirm overwatch.processing_completed records validated observations. Unknown or obscured fields should be null, not confident guesses. When diagnostic chat is enabled, Roverwatch posts concise confirmed phase transitions, changed OCR scoreboard snapshots (including hero and map), confirmed death counts, and final game tallies. It does not send per-frame timing/HUD summaries or periodic heartbeats; detailed diagnostics remain in the logs.
  3. Exercise normal gameplay, death/respawn, scoreboard/menu, and an ambiguous HUD. Confirm framesDroppedAsStale may rise while the latest frame is still favored and inference concurrency remains one.
  4. Download several matching overwatch/screenshots and overwatch/results objects. Record incorrect observations as first-party fixtures with optional expected JSON.
  5. Only after observation quality is acceptable, redeploy with --parameters TwitchGameStateChat=true. Confirm compact messages are responsive, throttled, deduplicated, and do not replay old observations.
  6. Stop the stream. EventSub should return desired count to zero. Run AWS_REGION=us-east-1 npm run latency:report -- SESSION_ID to report Bedrock and capture-to-observation p50/p95, diagnostic capture-to-chat timing, counters, failures, player latency, and buffer trend.

Acceptance still requires the live work above: local tests and synthesis prove contract/integration behavior, but do not establish real-game extraction accuracy or useful end-to-end latency.

Docker debugging #

docker build -t roverwatch .
docker run --rm roverwatch --check-chrome

The check writes /tmp/roverwatch-chrome-check.jpg inside the disposable container. For a full run, pass TWITCH_CHANNEL, SCREENSHOT_BUCKET, EMBED_URL, and AWS_REGION with -e. Set DEBUG_BROWSER=true for Chrome stderr and verbose browser logs.

Configuration #

Variable Required/default Meaning
TWITCH_CHANNEL required Twitch channel login
SCREENSHOT_BUCKET required private artifact bucket
EMBED_URL required HTTPS CloudFront page URL
CAPTURE_INTERVAL_MS 2000 capture delay; tested configuration values are 1000, 500, 250, and 200 ms
MAX_IN_FLIGHT_INFERENCES 1 hard realtime invariant; other values are rejected
SAVE_CAPTURE_EVIDENCE true asynchronously persist realtime transition evidence
DECODE_VISION_LAB_BEACON false opt-in deterministic vision-lab-latency-v1 capture decoding
TWITCH_GAME_STATE_CHAT false enable concise game-state transitions, changed scoreboard snapshots, confirmed death counts, and final tallies in Twitch chat
GAME_STATE_CHAT_INTERVAL_MS 3000 minimum spacing between state messages and confirmed local-death batching window; scoreboard snapshots use at least 5 seconds
PLAYER_STATS_INTERVAL_MS 1000 documented Twitch playback-stat polling interval
SHUTDOWN_TIMEOUT_SECONDS 110 bounded finalization deadline; must remain below the 120-second Fargate stop timeout
PUBLIC_REVIEW_BASE_URL infrastructure-derived public CloudFront origin used to report the completed review URL
BEDROCK_MODEL_ID required when inference is enabled image-capable Converse model; currently Nova Lite
TWITCH_CHAT_SECRET_ARN / TWITCH_APP_SECRET_ARN required when diagnostic chat is enabled Secrets Manager identifiers injected by CDK; never token values
SCREENSHOT_INTERVAL_SECONDS 5 capture interval fallback when CAPTURE_INTERVAL_MS is absent; tuned to the single-inference throughput
BROWSER_WIDTH / BROWSER_HEIGHT 1280 / 720 viewport
PLAYER_STARTUP_TIMEOUT_SECONDS 60 Twitch initialization deadline
PAGE_NAVIGATION_TIMEOUT_SECONDS 45 embed navigation deadline
S3_UPLOAD_TIMEOUT_SECONDS 20 deadline for each S3 attempt
CHROME_PATH /usr/bin/google-chrome real Chrome executable
LOG_LEVEL info debug, info, warn, or error
DEBUG_BROWSER false enable verbose Chrome logging
APP_VERSION / GIT_SHA development deploy correlation label

Infrastructure-derived values are injected by CDK. Do not place secrets in these variables.

Inspect evidence #

List captures:

aws s3 ls s3://BUCKET_NAME/sessions/ --recursive
aws s3 cp s3://BUCKET_NAME/sessions/SESSION_ID/latest.jpg ./latest.jpg
aws logs tail /roverwatch/browser-worker --follow
aws logs tail /roverwatch/eventsub-webhook --follow

Overwatch screenshots and inference records are paired under sessions/<session-id>/match/. Player-only diagnostic captures use sessions/<session-id>/screenshots/; latest.jpg is overwritten after each capture. Failures are under sessions/<session-id>/failures/<timestamp>/ as screenshot.jpg, page.html, and diagnostics.json.

Targeted debugging #

  • Chrome won't launch: find browser.launch.failed; it includes the Playwright process error and stderr. Run npm run check:chrome or the Docker diagnostic command. No page artifact can exist if Chrome never started.
  • CloudFront/embed page fails: inspect browser.response, browser.request_failed, and fatal navigation status. The failure HTML and screenshot show the page Chrome received; confirm the EmbedUrl stack output returns 200.
  • Twitch never becomes READY: filter for twitch.player.console, browser.console, and failed Twitch requests. diagnostics.json records the final URL and last player event.
  • Twitch reports OFFLINE: state.transition must enter TWITCH_OFFLINE and application.health must show a healthy process with an offline channel. This is not a browser failure.
  • Autoplay is blocked: look for PLAYBACK_BLOCKED; the worker treats it distinctly and saves a failure screenshot. The container explicitly uses a no-gesture autoplay policy and muted audio.
  • PLAYING never fires: compare the last event in diagnostics with console/network failures. READY proves initialization, not decoded playback. The screenshot distinguishes player UI, an error overlay, and a black frame.
  • Screenshots are black: download both latest.jpg and a new manual failure screenshot, then correlate its time with PLAYING, response errors, and Chrome GPU/media errors enabled by DEBUG_BROWSER=true.
  • Twitch UI but no video: inspect whether the last official event was OFFLINE, PLAYBACK_BLOCKED, PAUSE, or merely READY; then inspect Twitch request failures. Do not infer playback from visible UI.
  • S3 upload fails: use s3.upload.failed attempt numbers and AWS error name. Confirm the task role has s3:PutObject for this exact bucket/prefix and that region/bucket match. After three bounded attempts, failure evidence is attempted and the process exits.
  • Fargate exits: correlate ECS stopped reason/exit code with the session's fatal event. Then inspect aws ecs describe-services, stopped tasks, and the log stream; the service restart is expected after non-zero exit.

Historical acquisition and prototype results #

This section records early infrastructure and generic shape-recognition experiments. The shape implementation, fixture runner, tests, and PNGs are archived under archive/shape/; completed player-only outputs are under archive/early-latency/. These are historical findings, not current runtime instructions.

Completed:

  1. Offline channel: Chrome launched, the embed initialized, OFFLINE was observed, and the process remained healthy.
  2. Live channel: Twitch reached PLAYING, JPEGs were captured and uploaded, and a downloaded JPEG visibly showed the live broadcast.
  3. Offline transition: after the stream ended, Twitch emitted OFFLINE and PAUSE without crashing the process.
  4. Event-driven lifecycle: Twitch stream.online started the zero-idle Fargate service and stream.offline returned it to zero tasks.
  5. Vision-to-Chat: a live Vision Lab session produced correct green-circle, red-square, and blue-triangle detections, successful official Twitch chat sends, none resets, duplicate suppression, and per-frame receipts.
  6. Local vision fixtures: all three target PNGs and the no-target PNG produced structurally valid results after tightening the none-case prompt.
  7. Timestamped ground truth: early Vision Lab exports recorded scheduled and published transitions for source-to-player correlation. Those generated exports are not checked into this repository.
  8. Clean-screen two-second run: an early shape-recognition session processed 100 frames and correctly classified all 19 observable transitions. This path has since been retired; the source and samples are documented in the archive.

Vision-to-Chat latency observed on 2026-08-28 #

Across 21 processed live frames, screenshot/S3 event to Lambda invocation averaged 1.04 seconds (0.52–1.34), Bedrock inference averaged 0.70 seconds (0.59–0.93), and seven Twitch sends averaged 0.14 seconds (0.13–0.15). Captured-frame-to-chat latency averaged 2.13 seconds and ranged from 1.66 to 2.46 seconds. Lambda processing itself averaged 0.87 seconds and peaked at 1.24 seconds.

The viewer captured every 10.32 seconds on average. This introduces an additional 0–10.3 seconds of sampling delay, approximately 5.2 seconds on average, before the measured processing path. Once a changed frame is visible in the Fargate Twitch player, expected response is therefore approximately 1.7–12.8 seconds, averaging about 7.3 seconds. Twitch ingest/transcoding/player delay could not be measured in that original run because its history export contained no source events. The replacement ground-truth export now records scheduled and published ISO timestamps plus monotonic revisions.

The first two-second session captured 53 unique frames at a 2.24-second average cadence and Bedrock averaged 608 ms, but it was not a valid end-to-end chat benchmark. An expired access token returned 401, and throwing that permanent failure allowed S3/Lambda asynchronous retries to turn 53 frames into 129 inference attempts. Reserved concurrency one then mixed old retries with new frames. The same run also captured Vision Lab Control Mode rather than the clean /test page, so controls polluted blank-frame classifications. Automatic token refresh, non-retryable REAUTH_REQUIRED receipts, and the clean test source are prerequisites for the repeat.

Clean two-second evaluation observed on 2026-08-29 #

The dedicated Vision Lab /test screen removed Control Mode labels and buttons from the video. The run produced 100 screenshots, 100 processor completions, 33 none classifications, 67 shape classifications, nine successful chat sends, and no failed or duplicate invocations. The first three of 22 ground-truth transitions occurred before the EventSub-started worker began capturing; the remaining 19 matched the model state changes in order for 19/19 observable transition accuracy.

Stage Average p95 Range
Capture interval 2.16 s 2.23 s 2.10–2.74 s
Capture to Lambda receipt 1.07 s 1.45 s 0.49–2.19 s
Bedrock inference 0.62 s 0.79 s 0.52–0.87 s
Lambda processing 0.70 s 0.97 s 0.57–1.12 s
Twitch chat API 0.14 s 0.15 s 0.13–0.15 s
Changed capture to chat 2.08 s 2.55 s 1.70–2.55 s

Ground-truth publication to the first matching capture averaged 14.62 seconds, with a 14.31-second median and 10.83–19.36-second range. For the nine message-producing shapes, publication to chat averaged 16.20 seconds and ranged from 13.39 to 19.14 seconds. The post-capture Roverwatch path remained stable while source-to-capture delay grew from roughly 11–14 seconds early in the run to 16–19 seconds near the end. The remaining bottleneck is therefore upstream of screenshot processing: Vision Lab test-screen synchronization, OBS, Twitch ingest/transcoding, or the embedded-player buffer. These components need separate instrumentation before assigning all of that delay to Twitch.

Remaining:

  1. Leave playback live for at least 30 minutes; check recurring captures and rssBytes/heapUsedBytes health logs.
  2. Break CHROME_PATH in a task revision; verify launch failure and non-zero exit. To test post-launch evidence, terminate Chrome from a diagnostic image.
  3. Run without TWITCH_CHANNEL; verify immediate configuration failure and non-zero exit.
  4. Point EMBED_URL at a page with an incorrect Twitch parent; verify console evidence and failure artifacts.
  5. Run a longer timestamped clean-screen sequence while recording OBS and player timing; determine whether the observed source-to-capture growth is continuing buffer accumulation or bounded startup adaptation.

The decisive success artifact is a current JPEG visibly containing the live Twitch broadcast rendered by official player Chrome on Fargate. Stop the spike after that is reliably demonstrated.

Lessons learned #

  • CDK ContainerImage.fromAsset requires a working local Docker daemon because CDK builds and publishes the image before CloudFormation deploys it.
  • Docker Desktop's desktop.exe credential helper repeatedly failed under WSL while saving temporary ECR logins even though WSL had ample free memory. npm run deploy now uses an isolated temporary DOCKER_CONFIG, disables parallel asset publication, forwards CDK arguments, and deletes the ECR authorization afterward without changing normal Docker configuration.
  • Running TypeScript through tsx in Fargate failed because an ECS-mounted /tmp was root-owned while the container ran as user 1000. The production image now compiles TypeScript during its build and runs node dist/index.js; Chrome and the production entrypoint pass the container diagnostic.
  • A deployment circuit breaker reports only that tasks repeatedly failed. The useful cause is in container stderr. Use --no-rollback during diagnostic deployments so CloudFormation does not delete the evidence before it can be inspected.
  • OFFLINE is a valid channel condition, not an unhealthy application condition. The process remained stable while waiting and later detected PLAYING without a restart.
  • Some Twitch media requests report net::ERR_ABORTED during normal player adaptation and shutdown. They are not automatically fatal; successful PLAYING events and visible JPEGs are stronger evidence.
  • Browser network logs now discard all query values and redact signed Twitch media paths while retaining origin, safe path, and query-parameter names for diagnosis.
  • Expected adaptive-media ERR_ABORTED requests remain observable at info level instead of appearing as fatal-looking errors.
  • The worker processes the player event sequence rather than only the latest event, suppresses duplicate transitions, and exits normally when started offline or after a playing channel goes offline.
  • Permanent OAuth failures must not be thrown back to an asynchronous S3 trigger: one invalid token expanded 53 frames into 129 inference attempts and delayed new work behind retries. Validate before sending, refresh and persist both rotated tokens, and complete revoked grants as REAUTH_REQUIRED.
  • Vision Lab Control Mode is not a valid visual fixture because its labels and colored controls pollute blank frames. Stream the clean /test route and use the separate ground-truth export for correlation.
  • The clean /test route fixed the false positives: 33 blank frames became none, and all 19 observable transitions matched ground truth. Visual-source isolation is part of test correctness, not merely presentation.
  • Two-second sampling is not the current bottleneck. Capture-to-chat averaged 2.08 seconds, while publication-to-capture averaged 14.62 seconds and increased during the run. Optimize and instrument the upstream video path before spending effort on Lambda or Bedrock latency.
  • Realtime evidence keys must not end in .capture.jpg; that suffix belongs exclusively to the S3/Lambda trigger. Separating *.transition.jpg prevents the fallback processor from duplicating direct-path inference and chat.
  • Secrets imported by name expose a partial ARN, while the physical Secrets Manager ARN ends with a generated six-character suffix. Read grants account for it automatically; custom PutSecretValue policies must target the suffixed ARN pattern or refresh can read tokens but fail when persisting rotation. CDK diff caught this before the realtime deployment.
  • Adding the direct Fargate path changes the task role: it needs narrowly scoped bedrock:InvokeModel plus read access to the Twitch application/chat secrets and PutSecretValue for persisted token rotation. A non-interactive CDK deployment must include --require-approval never after that IAM diff has been reviewed; otherwise CDK stops before deployment because it cannot display the security-change prompt without a TTY.
  • A failed aws sts get-caller-identity is not automatically an expired SSO session. Distinguish an endpoint/network failure from an authentication error before reauthorizing. The 2026-08-29 deployment initially failed inside a restricted network, while the same read-only identity call with normal AWS access confirmed the existing SSO session was still valid.
  • A configured 250 ms post-capture sleep is not a 250 ms start-to-start cadence. With screenshot work averaging 86 ms, the live loop averaged 345 ms between captures. A monotonic deadline scheduler would remove this drift and make experiments more reproducible, but the expected latency gain is only tens of milliseconds rather than seconds.
  • The latest-frame policy bounded latency under load: 49 of 106 frames were replaced as stale instead of creating an inference backlog, with no processing failures. Increasing capture frequency improves freshness but cannot increase throughput while Nova Lite inference averages 649 ms and concurrency is intentionally one.
  • The realtime spike moved Roverwatch's own capture-to-decision latency below one second at p50 and p95, but Twitch player latency remained roughly 10–12 seconds. Further Lambda, S3, or capture-loop tuning cannot recover those seconds; the next high-leverage work is live-edge control or moving observation ahead of Twitch playback.
  • Deterministic evaluation identity must not come from the probabilistic vision model. Decode the transport beacon before latest-frame replacement, join its uint32 revision to the export's authoritative renderedAt, and keep invalid headers, threshold ambiguity, missing revisions, and out-of-export revisions visible in the report.
  • A schema name alone is insufficient for historical joins. The finalized report requires both export schemaVersion and beaconSchemaVersion to be vision-lab-latency-v1; the pre-finalization export is preserved but rejected rather than assumed compatible.
  • The first finalized-beacon stream proved failure accounting, not transport latency: zero of 235 captured beacons decoded, so all 60 export revisions remained missing and no p50/p95 was claimed. Always persist a bounded diagnostic frame for a new deterministic decoder; numeric samples alone could not distinguish a small geometry mismatch from video-pipeline degradation.
  • Capture-time beacon decoding increased average cadence from 345 ms to 467 ms, but the dominant regression remained the player: broadcaster latency grew from an 8.1-second beginning-third average to 20.5 seconds in the final third. Optimize decoder placement for correctness and freshness, then return to the explicit player-buffer experiment matrix for seconds-scale gains.
  • Real gameplay must start as an observation problem. A strict single-frame contract prevents the model from quietly turning visible HUD extraction into temporal coaching or strategy; durable game-state logic, if ever justified, belongs in a separately measured layer.
  • Raw model text and validation failures are evidence, not disposable exceptions. Retaining both is necessary to distinguish model uncertainty from JSON parsing and schema failures without logging image bytes.
  • Chat is a diagnostic sink, not the state pipeline. It is disabled by default, uses a replaceable latest value, throttles routine sends, and deduplicates identical states so slow publication cannot create stale commentary.
  • The first live v6 Overwatch run was neither timely nor semantically reliable: Twitch latency reached 110 seconds, inference p50 reached 5.71 seconds, 678 of 736 captures were replaced as stale, and retained frames exposed confident phase and hero errors. The acquisition layer must pass the documented live-edge gate before more model context is added.
  • Realtime Overwatch evidence is stored under sessions/<session-id>/overwatch/, not the legacy latest.jpg path. Evidence existence and evidence discoverability are separate requirements; add a bounded manifest/latest pointer before the next evaluation.
  • A task being terminated cannot reliably announce its own termination. The EventSub control plane should send the final watching message before scaling Fargate to zero, while the worker still handles graceful local cleanup when it receives a signal.

Next steps #

  1. Implement the player-only diagnostic mode and bounded 10-second evidence sampling described in docs/live-edge-validation.md.
  2. Run the 30-minute player-only baseline and apply the live-edge gate before enabling screenshots at production cadence or Bedrock.
  3. If player-only passes, add 1,000 ms capture, then 500 ms capture, measuring one variable per run. Test 2 vCPU/4 GB only if screenshot work is proven to destabilize playback.
  4. If the official player fails under minimal load, compare a permitted OBS/local-frame input before investing in downstream inference optimization.
  5. Move the finished-watching message to the EventSub scale-down path and verify a successful task exit.
  6. Add a bounded realtime evidence manifest or latest-overwatch.jpg pointer so each session can be audited without discovering UUID keys manually.
  7. After acquisition passes, introduce the fast respawn/team-count/scoreboard HUD path, followed by the slower phase/map/mode classifier. Reapply the live-edge gate after every layer.
  8. Expand first-party evaluation data by complete independent match sessions and require both field accuracy and lifecycle precision/recall before claiming generalization.

Destroy #

npx cdk destroy

The empty embed-origin bucket and development CloudWatch log group are deleted. Use --no-rollback on diagnostic deployments so their logs remain available until you inspect and delete the failed stack. The screenshot bucket is deliberately retained because the project forbids the Lambda-backed CDK bucket auto-delete helper. Download what you need, empty it explicitly with aws s3 rm s3://BUCKET_NAME --recursive, and delete the retained bucket when ready.

Known limitations #

  • The proven run covers one AWS region, one Twitch channel, and a short live session; it does not establish long-duration reliability.
  • Muted autoplay is used for reliability, so the JPEG-only experiment says nothing about audio.
  • The public-IP/no-NAT design minimizes spike cost, not production attack surface or high availability.
  • Local Chrome may have different codecs, fonts, shared memory, and network reputation than the Debian/Fargate image; record any observed difference in the experiment report.
  • EventSub delivery depends on the Twitch application, valid subscriptions, API Gateway, and Lambda. Monitor revocation events and /roverwatch/eventsub-webhook logs.

License #

Roverwatch is licensed under the PolyForm Shield License 1.0.0. It permits use, modification, and distribution for purposes other than providing a product that competes with the licensor or its affiliates.

Review summary and scoreboard corrections (2026-09-04) #

Game summaries report detected death episodes separately from the latest readable scoreboard death and elimination counts. Detected deaths are observed events, not a claim of complete match coverage. A visible scoreboard with unreadable cells does not replace a readable snapshot. The snapshot is timestamped and is not described as a final match total. A visible match result or Play of the Game closes the observed game; if neither was seen, a finalized review says “match end not observed.” The observed-screen list preserves successive changes rather than implying a confirmed lifecycle sequence.

The evidence parser now supports optional local-player name, E/A/D/DMG/H/MIT, map, and mode transcription, with visibility and row-identity checks. Automated transcription is NOT enabled: the combined v3 candidate, full-frame variant, and dedicated Nova Lite/Nova Pro scoreboard probes failed the recorded-image gate. The live prompt remains overwatch-visible-evidence-v2-death-detail. Older evidence remains supported; rebuilding its review restores episode counts but cannot invent scoreboard cells that were never extracted. See the evaluation report for the measured failures and remaining work.

Shared match lifecycle and scoreboard OCR #

The current implementation supersedes the older death-detail and scoreboard-status notes above. Match tracking, death events, and summary assignment now share one durable stream. Scoreboard extraction uses spatial checks and local OCR outside model inference. See implementation, validation, and recovery instructions.

Offline visual dataset export #

Use npm run dataset:export -- --session-dir ./evidence/SESSION_ID/match --output ./dataset --reviewed-only to export reviewed frames as copied images plus a JSONL manifest using the current visual-evidence schema. Multiple local sessions or read-only S3 sources are supported. Rows retain session/game IDs, safe split groups, and field-level review provenance; report.json reports class counts, imbalance, and skipped frames. See dataset export documentation for annotation semantics and S3 examples. This tool does not change production inference.

The exporter is covered by focused tests for reviewed-field provenance, literal corrections, match-level grouping, missing/corrupt evidence, path safety, duplicate assignments, rollback, and CLI execution. The repository's current full test suite passes with the local Tesseract runtime available for scoreboard OCR tests.