Get unstuck without skipping straight to the answer.
Progressive hints, clean editorials, and full C++ solutions for Codeforces problems. Generated through OpenCode, served at your own pace.
Install dependencies and start the app with Bun 1.4.5:
bun install
bun run devCopy the variables documented in .env.example into your local environment. The app requires a PostgreSQL database whose schema matches prisma/schema.prisma.
Initialize a fresh development database with bun run db:deploy. For a schema change, point DATABASE_URL (and DIRECT_URL, if set) at a local/disposable development database, then:
bun run db:migrate --name describe_the_change --create-only
# Review the generated prisma/migrations/<timestamp>_describe_the_change/migration.sql.
bun run db:migrate
bunx --bun prisma generateCommit the SQL migration together with prisma/schema.prisma. Deployments apply pending migrations automatically. Prisma commands prefer a nonempty DIRECT_URL and otherwise use DATABASE_URL; never run development migration commands or db push against production, including through the SSH tunnel.
The navbar displays the model and reasoning effort from the latest successfully saved generation. Its display string is stored in the singleton SiteState row and updated in the same transaction as the generated content. The browser fetches it from /api/current-model, with a 60-second HTTP cache, so the badge does not force otherwise static pages to render at request time. The indicator stays hidden until the first successful save; it does not query generation history or control model selection.
Successful generations prepare sanitized Markdown, KaTeX math, and highlighted code before acquiring the database transaction lock. The prepared documents and their source text commit together in Problem.preparedContent. A source-content hash and PREPARED_CONTENT_VERSION prevent reuse after a content or renderer change. Bump that version when changing parser, sanitization, math, or highlighting behavior, including dependency upgrades that affect output.
Readers reuse the saved documents across server restarts. Older rows are prepared and saved once when first read; no AI regeneration is needed. Only prepared documents and copyable solution code reach the browser, which handles reveals without downloading the parser, KaTeX renderer, or Shiki. Public problem component output is also cached in Next's process-local cache and invalidated by the existing problem tags when content or review state changes.
Production intentionally prepares older problems when visitors read them; deployment does not run a bulk backfill. If an explicit administrative backfill is needed later, these commands require DATABASE_URL access (and CACHE_REVALIDATION_URL / CACHE_REVALIDATION_SECRET for the write command):
bun run content:prepare --check
bun run content:prepare--check does not write and exits with status 1 if any completed problems need preparation. The write command processes bounded batches, preserves catalog ordering, and refreshes completed problem page caches. Re-running it skips matching documents and retries cache invalidation.
Run the full local quality gate before shipping:
bun run checkMigration/startup integration tests use a separate disposable local PostgreSQL database whose name starts with nudge_migrations_test_:
TEST_MIGRATION_DATABASE_URL=postgresql://postgres@127.0.0.1:5432/nudge_migrations_test_local bun test tests/migrations.test.tsThe test creates and removes its own schema. It checks fresh initialization, repeat startup, applying a new migration while preserving data, and refusing to start after a migration failure.
Most editorial sites give you the whole answer or nothing. Nudge sits in between: every problem has progressive hints that go from a gentle nudge toward the right area all the way to the key insight, plus a prose editorial and the full C++ solution when you're ready.
All content is generated locally through OpenCode, then stored in Postgres and served through a Next.js frontend. Problems are synced from the Codeforces API automatically.
Generation is local-only, using the project-pinned OpenCode V2 CLI, client, and plugin packages. The server does not run OpenCode and there is no encoded cloud credential path. The generation agent allows tools automatically, including shell commands and file edits. Questions are disabled: the tool is removed and native permission rules deny it. Generation can run on macOS or Linux. Each run uses a temporary working directory and a one-hour timeout.
Nudge starts its own authenticated server on a random loopback port and shuts it down when the command finishes. It does not attach to or replace your personal OpenCode background service. The local client disables Bun's five-minute socket idle timeout so a quiet session wait can last for the full one-hour generation deadline; cancellation still interrupts it. Use bun run opencode -- <command> for the bundled CLI; your global opencode installation can have a different version.
For a fresh Linux worker, install Bun and run bun install --frozen-lockfile. Put a GNU C++ compiler, Python 3, curl, and Poppler (pdftotext and pdftoppm) on PATH so the agent can compile solutions and extract or render PDF statements. Give the worker writable temporary, OpenCode state, and .opencode-runs directories. Allow loopback connections and outbound HTTPS to Nudge, Codeforces, the model provider, and the search service. Use a dedicated sandbox account with only the worker's credentials: shell tools run with that account's filesystem and network access.
-
Existing local provider credentials are reused. Check them with
bun run opencode -- auth list. If needed, usebun run opencode -- auth loginand select the provider/account you want to use.bun run modelsconfirms which providers are available to Nudge. OpenCode picks an available web search provider at random for each session and retries with another provider on HTTP 429. For authenticated searches, set the provider keys listed in.env.examplein the generation worker’s untracked.env.localor process environment. Start a new generation process to pick up the keys. -
Set
CACHE_REVALIDATION_URL=https://nudge.wikiand the same strongCACHE_REVALIDATION_SECRETused by the deployed app. These authenticate the generator's HTTPS requests; keep the secret in your untracked environment, never in client code or Git. -
Transcripts are stored in the deployed app's persistent
/data/transcriptsvolume. No separate storage provider is required. -
Generation claims work and submits results through
/api/generation. The server validates content, records usage, writes Postgres, and invalidates caches. No database credentials, SSH tunnel, Tailscale, or separate terminal are required for generation. -
Configure the model, reasoning variant, and public display label in
nudge.config.json(see Switching models or providers).{ "model": "openai/gpt-6-astra", "variant": "low", "display": { "model": "GPT-6 Astra", "reasoning": "low" } } -
Run one queued generation:
bun run opencode:next
To run several queued generations sequentially:
bun run opencode:next -- 3
The explicit form also works:
bun run opencode:next -- --count 3
From one terminal, run 250 problems with up to 25 active generations on a single private OpenCode server:
bun run opencode:next -- 250 --parallel 25The count is the total for the batch. Each session has its own problem, working directory, timeout, and transcript. When a job finishes and saves, its slot takes the next problem. --parallel 25 alone runs one batch of 25. Concurrency defaults to 1. Starting another runner starts another server.
For a no-write preview of the next candidate:
bun run opencode:next -- --dry-runIn an interactive terminal, batch runs support these keys (no Enter needed):
- p pauses new claims. Active generations finish and save. Press p again to resume.
- q stops new claims and exits once all active generations finish and save. A chained command such as
&& xruns after a clean exit. - Ctrl+C interrupts all active sessions and exits with an interruption status.
Controls apply to this runner only and require an interactive terminal. A claim already in flight when you press a key is allowed to finish. An empty queue ends the batch after active jobs drain. In parallel mode, a recorded problem failure counts toward the requested total and other jobs continue. An API or persistence exception stops new claims while already claimed jobs finish. Any failure gives the command a nonzero exit status. The batch summary includes completed count, elapsed time, and reported tokens.
Each generation claims one eligible problem and creates an isolated OpenCode session. A local V2 plugin exposes nudge_submit_result, which validates the result against Nudge's JSON schema. Plain JSON text is not accepted as a submission; if the model finishes without submitting, Nudge sends at most two reminders before failing. The existing content validation still runs before persistence.
Claims and result submissions are safe to retry after a dropped response. If submission still fails after retries, the command saves a credential-free .opencode-runs/<claim-id>.pending.json and prints bun run opencode:resume -- <path> to retry the upload without running generation again. Stale or replaced claims are rejected.
The agent receives problem metadata and both Codeforces problem URLs, then retrieves the complete statement and researches solutions with its own tools. This includes PDF statements and relevant diagrams; Nudge does not scrape HTML or prefetch statement images/editorial pages before starting the session. Retrieval failures and fallback attempts appear in the generation transcript. A PDF or missing editorial alone is not an unsolvable result; the agent must identify a concrete statement/resource blocker after trying alternatives.
Nudge persists the generated hints/editorial/solution, records whole-session token usage (including tool turns and cached tokens), mirrors the exact opencode session export bytes into .opencode-runs, uploads that file to the Coolify app's transcript endpoint, and prints both transcript locations. The worker reuses the session export already in memory and releases the temporary directory’s cached OpenCode services after every job. A session is deleted only after its transcript has been mirrored; export failures leave it available in OpenCode and report a warning. Ctrl-C, SIGTERM, and the one-hour timeout interrupt the V2 session before cleanup. OpenCode reads provider credentials from its normal local credential store; Nudge never copies them into project configuration.
To load a saved transcript back into OpenCode, import its local path or published URL, then open the session ID printed by the import command:
bun run opencode -- session import .opencode-runs/<session-id>.json
bun run opencode -- --session <session-id>You can use the transcript URL in place of the local path in the import command.
Never hand-type a model ID from memory; copy it verbatim from the CLI. bun run models queries the same bundled OpenCode runtime that generation spawns and validates against, drilling down in three steps:
- Connect the provider (skip if already authed): run
bun run opencode -- auth login, then confirm withbun run opencode -- auth list. - Pick a provider:
bun run modelslists connected providers. - Pick a model:
bun run models <provider>lists its models, marking with ✓ the ones that support tools and image input. Copy the fullprovider/model-idstring, slashes and dashes included. - Pick a variant:
bun run models <provider>/<model>shows the validvariantvalues, the model's display name, and a ready-to-pastenudge.config.jsonblock. - Verify without generating anything:
bun run opencode:next -- --dry-runruns preflight, which validates the model ID, variant, and required capabilities against live provider metadata and prints the exact display name. A typo'd variant fails fast withdoes not expose the <variant> variantinstead of wasting a generation.
Notes:
- The config is strict-parsed on startup: unknown keys or a
modelmissing theprovider/prefix are rejected immediately. variantis optional and must be one of the variant keys from step 4.display.modelis the public label — free text, so fix naming there, not inmodel.display.reasoningis optional and falls back tovariantwhen omitted. The label renders asdisplay.model (reasoning), or justdisplay.modelwhen neither is set, so the checked-in configuration rendersGPT-6 Astra (low).display.*is cosmetic and safe to edit anytime, but the label is stored on each problem at generation time — existing content keeps the label it was generated with, and the new label applies to future generations.
Deploy the repository with its Dockerfile on port 3000 in Coolify. Set the runtime variables in .env.example, and mount a persistent volume at /data/transcripts, writable by the image's bun user (UID 1000). Keep PostgreSQL private on the Coolify Docker network. Generation uses the authenticated HTTPS API. bun run db:tunnel is only needed for optional administrative access, such as Prisma Studio; no public database port is needed.
The Docker command runs scripts/start-production.sh, which applies committed migrations with bun run db:deploy before starting Next. A migration failure exits the new container before it can serve traffic. Builds only generate Prisma Client and compile the app; database changes happen at runtime. Keep the Docker startup command in Coolify rather than overriding it with next start, and do not add a duplicate migration hook. bun run db:status shows migration history without applying changes.
prisma/migrations/0_init captures the schema at the switch from db push to Prisma Migrate, including the nullable preparedContent field. Nudge production was verified and baselined on 2026-10-31; no further baseline step is needed there. A fresh database applies it automatically. For another existing populated database, first check it with bunx --bun prisma migrate diff --from-config-datasource --to-schema prisma/schema.prisma --exit-code; only if it matches, register the baseline once with bunx --bun prisma migrate resolve --applied 0_init. This records migration history without recreating tables or changing problem content. Never put baseline resolution in the startup script.
Keep migrations compatible with the previous app version during rolling deployments. Never edit applied migrations; use a new migration to make subsequent changes. Failed migrations may leave partial SQL changes, so inspect the database and deploy logs before using prisma migrate resolve to recover. Rolling back the app does not reverse schema changes. See Prisma's production migration workflow.
Configure a Coolify scheduled task with command bun run jobs:daily and cron 0 7 * * * (UTC), which is midnight in America/Phoenix. It runs the Codeforces sync and report digest; a PostgreSQL advisory lock prevents overlapping runs. bun run jobs:daily -- --check validates database connectivity and locking without running either job. Disable the previous cloud schedules before enabling this task.
The health check is /api/health. In Coolify, choose a container-command health check with bun scripts/healthcheck.ts; the image does not require curl or wget. Verify public problem pages, transcript downloads, and authenticated cache invalidation after deploys. Back up both PostgreSQL and the transcript volume; they must be restored together. Do not delete the migration source until data counts and transcript checksums match.
Production deploys automatically from main through a signed, push-only GitHub webhook to Coolify. The database backup runs at 08:00 UTC and the transcript-directory backup at 08:05 UTC, each retaining 14 archives. Coolify stores these under /data/coolify/backups/databases/ and /data/coolify/backups/volumes/ on the server. These local backups need a separate off-server copy to protect against disk or host loss.