From d14d7dad6e1566de0cded3695f01d550f1814297 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 24 Sep 2026 10:45:12 +0000 Subject: [PATCH 1/2] Design: publish the free tier as content pages, per company Proposal only. Company folders with a home page and interview-process page, one page per free question with hints and reference solution, Study guides as pages, fed by a secret-guarded export on the site rather than the public API. Lists the four decisions needed before any body is published. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YSnSdWBmgwyCFLKNcQiCKB --- CONTENT-DESIGN.md | 295 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 295 insertions(+) create mode 100644 CONTENT-DESIGN.md diff --git a/CONTENT-DESIGN.md b/CONTENT-DESIGN.md new file mode 100644 index 00000000..c2f6acc4 --- /dev/null +++ b/CONTENT-DESIGN.md @@ -0,0 +1,295 @@ +# From index to content: the free half of TrueInterview, on GitHub + +Status: **proposal** — nothing in this document is built yet. Four decisions in §8 need +the maintainer before any body text is published. + +`DESIGN.md` describes the repository as it is today: an hourly **index** over the question +bank — tables of titles, counts and dates, every row a link into trueinterview.io. It is +well built and it has no content. A visitor who opens `companies/google.md` learns that +Google asked 190 questions and cannot read a single one of them here. + +The reference this proposal is modelled on, +[`Schuture/OpenAI-Interview-Notes`](https://github.com/Schuture/OpenAI-Interview-Notes), +is the opposite shape: 63 pages, and each one *is* the thing — a full statement, a worked +solution, a round described in prose. That is what people star and share. This document +designs the same shape for **every company in the bank**, built from the part of the +catalog that is already free on the site, and generated by the same hourly job. + +--- + +## 1. What the reference does that we should copy + +Measured on `Schuture/OpenAI-Interview-Notes@main`. + +| Their choice | Why it works | Here | +| :-- | :-- | :-- | +| One folder per problem, `README.md` inside | GitHub renders a folder's README when you open it, so the URL *is* the page and the folder can grow (translations, code) without a new URL. | Same, for questions and for companies. | +| A metadata table at the top of every page, between `` markers | Scannable, and machine-editable without parsing prose. | Same markers, same position. | +| `## Problem` → `## Reference solution` (collapsed) | The reader decides whether to look. | Same order; solution and each hint in `
`. | +| Behavioral rounds are pages too | "What happens in the recruiter screen" is content, not a footnote. | Our 363 Study-section guides become those pages. | +| An honest disclaimer at the top of the README | Unofficial, reconstructed, not the exact question; open an issue to take something down. | Same, adapted. | +| Text licensed separately from code | CC BY-NC for prose makes a commercial mirror explicitly not permitted. | Proposed; see §8. | + +What we do **not** copy: they are one company and hand-written. We are 99 companies and +generated, so every page is a projection of a record on the site and nothing is edited +here by hand (the same rule `DESIGN.md` §4 already holds). + +## 2. What there is to publish + +Counted on production, 2026-09-24, non-archived rows only. + +| | Rows | Companies | Notes | +| :-- | --: | --: | :-- | +| Free questions — algorithm | 108 | 53 | Every one has a statement; hidden tests are never published (§5). | +| Free questions — OOP | 39 | 25 | | +| Free questions — system design | 12 | 8 | | +| Free questions — AI coding | 7 | 6 | Project zips stay on the site; the statement is published. | +| **Free questions, total** | **166** | **99** | Through `companies[]`, *every* company has at least one. Median **2** per company, p90 12, max 30. | +| Reference solutions for those | 166 | | Each free question has a `solution_discussion_id` → "Reference solution" (~3 MB total). | +| Hints for those | 147 | | `questions.hints`. | +| Study guides (`type = blog`) | 363 | 83 | All `access_tier = free`. Median 3 per company. | +| … of which company **interview-process** guides | 163 | 81 | `-interview-process` plus per-role (`…-software-engineer-interview-process`). 18 companies have none. | +| … of which short fragments (< 600 chars) | 32 | | Mostly UUID-slugged prompts filed as articles; see §6. | +| Paid questions (pro / insider) | 2,343 | | **Never published.** Listed by title with a link, exactly as today. | + +Two things follow. First, the median company has two free questions, so a company page +cannot be carried by questions alone — the **interview-process guide is the centre of the +page**, and the questions are the practice list beneath it. Second, 18 companies have no +process guide; their page falls back to today's counted preamble ("The loop, as +reported"), which is exactly what it is for. + +## 3. The repository layout + +``` +README.md landing: what this is, company grid, free counts +companies/ + README.md every company, grouped by company type + google/ + README.md company home (§4.1) + interview-process.md the loop, from google-interview-process (§4.2) + interview-process/ + software-engineer.md per-role process guides, when they exist + machine-learning-engineer.md + guides/ + behavioral-round-googliness.md every other Study guide filed under Google + google-hiring-assessment-gha.md + questions.md every question reported here: free → local page, + paid → site link (§4.4) + google.md one-line stub → google/ (old URL; §7) +questions/ + algorithm//README.md one page per FREE question (§4.3) + object-oriented-programming//README.md + system-design//README.md + ai-coding//README.md +formats/ by-month/ insights/ company-types/ free/ experiences/ data/ + unchanged — the index layer stays, and its free rows + now link to the local page instead of the site +``` + +**Why questions live outside `companies/`.** A free question is reported at up to twelve +employers (`Valid Parentheses`: Apple, Amazon, Bloomberg, ByteDance, Meta, NVIDIA, Oracle…). +Copying the body into twelve company folders would make one upstream edit a twelve-file +diff and give search engines twelve identical pages. The body lives once, under its +format; each company page links to it. Guides are the opposite: a Study article carries +exactly one `company`, so it lives in that company's folder. + +**Paths are stable, not derived per run.** 35 free rows have UUID slugs +(`03d208eb-7407-…`), which make unreadable URLs. A question's folder name is +`slugify(title)` the first time it is published, with a numeric suffix on collision, and +is then recorded in `data/paths.json` keyed by the catalog slug. A later title change does +not move the file — moving it would break every link anyone has shared. Pruning a path +only happens when the catalog row stops being free or disappears. + +## 4. The four page types + +### 4.1 Company home — `companies//README.md` + +Top to bottom, in the order a candidate needs it: + +1. **Title + one line**: `# Google interview process & questions`, then the counts line + that exists today. +2. **Metadata table** (`meta:begin/end`): company type, headcount band, questions tracked, + free to read here, most recent sighting, guides. +3. **The loop** — the first ~2 sections of `interview-process.md` inlined (the process + diagram and stage list), then *Read the full process →*. No process guide → today's + counted "The loop, as reported" table in its place. +4. **Free questions you can read here** — table: title (→ local page), format, difficulty, + round, last reported, *Practise* (→ site). Ordered the way `free/` orders them. +5. **Guides** — per-role process guides, then every other guide, one line each with its + tags. +6. **What's been asked lately** — today's 90-day block and "Start here", with paid rows + marked 🔒 and linking to the site. +7. **Every question** → `questions.md`. + +Every block is either a published body or a count, exactly the split `DESIGN.md` §3b +draws. The page never asserts anything about the employer that is not in a guide the site +already publishes. + +### 4.2 Interview process — `companies//interview-process.md` + +The body of `-interview-process`, verbatim after link rewriting (§5.2), under a +metadata table (roles covered, questions and reports it draws on, last updated) and above +a footer linking the per-role guides and the company's free questions. Per-role process +guides render the same way under `interview-process/.md`. + +### 4.3 Question — `questions///README.md` + +Mirrors the reference page exactly: + +```markdown +# Rate Limiter + + +| Format | Difficulty | Companies | Rounds | Topics | Target time | Last reported | +| --- | --- | --- | --- | --- | --- | --- | +| Algorithm | Easy | Stripe · Amazon · Atlassian · Google · +6 | Phone screen, Onsite | hashing, sliding-window | 30 min | Dec 2025 | + + +> ▶ **[Run it on TrueInterview](https://trueinterview.io/questions/rate-limiter)** — editor, +> sample and hidden tests, and a judged verdict. Free, no card. + +## Problem +…content_md… + +## Hints +
Hint 1 …
+ +## Reference solution +
Show the solution +…solution discussion… +
+ +## Asked at +Stripe (Dec 2025) · Amazon · … ← each links to companies// +``` + +The *Run it* link is the one call to action and sits above the statement: a reader who +wants to practise should never scroll past the answer to find the editor. + +### 4.4 Company question list — `companies//questions.md` + +Today's `companies/.md` catalog table, unchanged in content, paginated by the same +192 KB budget. The only difference is the title cell: a free question links to its local +page with *Practise* beside it; a paid one links to the site with 🔒. + +## 5. Where the bodies come from, and what never leaves + +### 5.1 A dedicated export, not the public API + +The public API's founding rule is *metadata travels, bodies never do*, and +`web/lib/openapi.test.ts` fails the build on a schema with a `content` field. That rule is +right for `/api/v1` and should stay: it is an unauthenticated interface anybody can page +through. So the bodies do **not** come from `/api/v1`. Three options were considered: + +| Option | Verdict | +| :-- | :-- | +| Add a body field to `/api/v1/questions` for free rows | Rejected. Breaks the API's one rule for every caller, to serve one consumer. | +| The sync reads Supabase directly with a service-role key | Rejected. A service-role key in a public repository's Actions secrets, and the *what is free* filter written in Python here, far from the code that decides it. | +| **A secret-guarded export route on the site** | **Proposed.** | + +`GET /api/export/free-content` on trueinterview, guarded by its own +`CONTENT_EXPORT_SECRET` (never `CRON_SECRET`, for the reason `CONFORMANCE_SECRET` gives: +a key that can be handed to a CI job must not also open cron routes). It returns: + +- free questions: catalog metadata + `content_md` + `hints` + the reference-solution + discussion + `target_minutes`; +- Study guides: metadata + `content_md` + tags; +- a `generatedAt`, and counts so a short read is detectable. + +**The filter lives in one server-side function**, and it is the whole safety argument: +`access_tier = 'free'` **as the entitlement code reads it** (not a second interpretation +of the column), `archived = false`, and for guides the same predicate `/study` uses to +publish. `access_tier` is Billing / Protected Zone data; this route reads it and never +writes it, and still needs the maintainer's sign-off because a wrong filter here publishes +a paid question permanently. + +### 5.2 What never leaves, whatever the tier + +| Never exported | Why | +| :-- | :-- | +| `test_cases`, hidden datasets, `sql_schema` expectations | The judge's protection is the number of hidden cases (see CLAUDE.md). Examples already inside `content_md` are the only tests published. | +| `code_stubs`, AI-coding project zips | Useful only in the workspace; the *Run it* link is where they belong. | +| Any pro / insider body | By construction of the filter. The export never selects them. | +| Interview experiences (面经) | Metered per reader in SQL (`claim_interview_read`). A GitHub copy would be the network-tab bypass `docs/paywall-exposure.md` exists to close. Titles + links only, as today. | +| Community discussions other than the reference solution | User-generated, with their own authors and moderation state. | + +**Link rewriting.** 162 guides contain site-relative links (`](/questions/…)`). The +renderer rewrites each one: to the local page if the target is published here, otherwise +to the absolute `https://trueinterview.io/…` URL. Images already point at public Supabase +Storage and render on GitHub unchanged. A link the rewriter cannot classify fails the run +(same rule as every other budget). + +### 5.3 The pipeline, extended + +``` +trueinterview.io/api/v1/* ──► catalog.py (unchanged: metadata) +trueinterview.io/api/export/free-content + ──► content.py fetch bodies, validate, rewrite links + ──► pages.py company home / process / guide / question + ──► build.py assemble every file (pure) + ──► sync.py budgets, diff, write, prune +``` + +Every property in `DESIGN.md` §4 holds unchanged, and three are worth restating because +bodies raise the stakes: + +- **A failed or short export writes nothing.** An hourly job that rendered zero free + questions would delete 166 pages from a public repository. The export returns its own + counts; if it returns fewer than 80% of the previous run's rows, the run fails and a + human looks. +- **Pruning is scoped** to `questions/` and the generated parts of `companies//`. + A question that becomes paid is removed on the next sync — it stays in git history, + which is why the filter in §5.1 has to be right the first time. +- **Deterministic output.** Bodies are written byte-for-byte as the site stores them + (after link rewriting), so an unchanged question is an unchanged file. + +## 6. Quality gates on what gets a page + +A generated page nobody would read is worse than no page: it is what makes a repository +look scraped. + +- **Short guides** (< 600 chars, 32 rows today) are listed on the company page, not given + a page of their own — they are prompts misfiled as articles, and the fix is upstream. +- **UUID slugs** never appear in a path (§3). +- **A company with neither a process guide nor more than two free questions** still gets + a home page, but it leads with the counted loop table, so it is never an empty shell. +- **Nothing claims quality** — the same rule as the site's comparison table and + `DESIGN.md`. Pages say what was reported, not that the content is the best. + +## 7. Compatibility + +- `companies/.md` is linked from the two job-list repositories and from search + results. It becomes a three-line stub pointing at `companies//`, and stays one + (GitHub has no redirects; a stub costs nothing). +- `free/`, `formats/`, `by-month/`, `insights/` keep their paths. Their free rows now link + to the local page. +- `data/questions.jsonl` gains a `path` field for free rows. No body goes into `data/` — + the export files are metadata, the pages are the content. + +## 8. Decisions needed before anything is published + +1. **Publishing bodies at all.** `trueinterview/docs/anti-scraping.md` says the catalog is + licensed content and mirroring it is not permitted, and `docs/public-api.md` builds on + that. This proposal mirrors the free tier on purpose. If accepted, both documents need a + sentence stating the exception and its boundary (free tier, through one export route), + or the next person to read them will treat this repository as the leak. +2. **Reference solutions.** Publishing them is most of the reference repo's value, and + they are free on the site. Recommended: yes, collapsed. +3. **License.** Recommended: text under CC BY-NC 4.0 (a commercial mirror is then + explicitly not permitted), the scripts under MIT, as the reference does. +4. **Search duplication.** A GitHub page with the full statement can outrank the site's + own page for the question title. Mitigations that keep the content: the *Run it* link + above the statement, `github.com` treated as a referral channel in + `/admin/sources`, and watching the site's impressions for free-question URLs for a + month after launch. The alternative — publishing statements but not solutions — keeps + more reason to click through, at the cost of the reference repo's main feature. + +## 9. Rollout + +| Step | Repo | Scope | +| :-- | :-- | :-- | +| 1 | trueinterview | Export route + service + tests (filter asserted against the entitlement code; a pro/insider fixture must never appear); `CONTENT_EXPORT_SECRET`; the doc exceptions from §8.1. Needs sign-off: reads `access_tier`. | +| 2 | here | `content.py`, `pages.py`, path registry, link rewriter; fixture tests that render a company end to end with no network. | +| 3 | here | Pilot: render **OpenAI, Google, Amazon** only (a feature list in `sync.py`), review by hand, check GitHub rendering on a phone. | +| 4 | here | All 99 companies; README rewritten as the landing page in §3. | +| 5 | both | Optional: `README.zh.md` per page, as the reference does, if the Chinese-speaking audience asks for it. | From c6585073f37ec0a4e3035d442797602f79ad41e2 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 24 Sep 2026 12:33:23 +0000 Subject: [PATCH 2/2] Publish the free tier as company homes and question pages Implements CONTENT-DESIGN.md. Every company gets companies//README.md: how it interviews (the opening of its interview-process guide), its free questions and its guides. Each free question gets questions///README.md with the statement and hints; the solution stays on the site behind a link. Interview-process guides and other Study guides are published under their company folder. Bodies come from the site's /api/cron/content-export when the CONTENT_EXPORT_SECRET Actions secret is set, and are checked again against the public metadata. Without the secret the homes still render, linking to the site. Folder names are recorded in data/paths.json so a published link never moves. Site-relative links in bodies are rewritten to the local page or to the absolute site URL. The sync refuses to delete published question pages when the secret is missing, or more than 20% of them at once. Text is licensed CC BY 4.0 (LICENSE-CONTENT.md); scripts stay MIT. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YSnSdWBmgwyCFLKNcQiCKB --- .github/workflows/sync.yml | 9 + .github/workflows/verify.yml | 2 +- CONTENT-DESIGN.md | 152 ++++---- DESIGN.md | 11 +- LICENSE-CONTENT.md | 30 ++ README.md | 32 +- scripts/build.py | 34 +- scripts/catalog.py | 130 ++++++- scripts/content.py | 661 +++++++++++++++++++++++++++++++++++ scripts/render.py | 2 +- scripts/sync.py | 56 ++- scripts/test_content.py | 260 ++++++++++++++ 12 files changed, 1275 insertions(+), 104 deletions(-) create mode 100644 LICENSE-CONTENT.md create mode 100644 scripts/content.py create mode 100644 scripts/test_content.py diff --git a/.github/workflows/sync.yml b/.github/workflows/sync.yml index d4698fca..b06417ea 100644 --- a/.github/workflows/sync.yml +++ b/.github/workflows/sync.yml @@ -36,6 +36,13 @@ jobs: # The summary line is kept for the commit body: the bot commits hourly, # and a log of identical one-line messages tells a reader nothing about # which hour the bank actually moved in. + # + # CONTENT_EXPORT_SECRET lets the sync read the free tier's bodies from + # /api/cron/content-export (see CONTENT-DESIGN.md). Unset, the repository + # renders its metadata-only pages exactly as before — and refuses to run + # at all once question pages are published, rather than deleting them. + env: + CONTENT_EXPORT_SECRET: ${{ secrets.CONTENT_EXPORT_SECRET }} run: python3 scripts/sync.py | tee "$RUNNER_TEMP/sync.log" - name: Confirm the result is self-consistent @@ -43,6 +50,8 @@ jobs: # second pass that still finds work means the render is not a pure # function of the snapshot, which would make the hourly job commit noise # for ever. --catalog-file so this costs no second read of the API. + env: + CONTENT_EXPORT_SECRET: ${{ secrets.CONTENT_EXPORT_SECRET }} run: | python3 scripts/sync.py --snapshot-out /tmp/snapshot.json --quiet python3 scripts/sync.py --catalog-file /tmp/snapshot.json --check diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml index 3178680e..6f899e58 100644 --- a/.github/workflows/verify.yml +++ b/.github/workflows/verify.yml @@ -40,7 +40,7 @@ jobs: run: | cp -r . "$RUNNER_TEMP/render-check" cd "$RUNNER_TEMP/render-check" - rm -rf companies company-types formats by-month guides insights free experiences data + rm -rf companies company-types formats by-month guides insights free experiences data questions python3 scripts/sync.py \ --catalog-file scripts/fixtures/catalog-sample.json \ --today 2026-09-11 diff --git a/CONTENT-DESIGN.md b/CONTENT-DESIGN.md index c2f6acc4..6079c903 100644 --- a/CONTENT-DESIGN.md +++ b/CONTENT-DESIGN.md @@ -1,7 +1,10 @@ # From index to content: the free half of TrueInterview, on GitHub -Status: **proposal** — nothing in this document is built yet. Four decisions in §8 need -the maintainer before any body text is published. +Status: **accepted and implemented** (`scripts/content.py`, and on the site +`problems/services/free-content-export.ts` + `/api/cron/content-export`). The four +decisions are recorded in §8. Bodies start appearing on the first sync after the +`CONTENT_EXPORT_SECRET` Actions secret is set; until then every page renders exactly as +below, with links to the site where a body would be. `DESIGN.md` describes the repository as it is today: an hourly **index** over the question bank — tables of titles, counts and dates, every row a link into trueinterview.io. It is @@ -25,7 +28,7 @@ Measured on `Schuture/OpenAI-Interview-Notes@main`. | :-- | :-- | :-- | | One folder per problem, `README.md` inside | GitHub renders a folder's README when you open it, so the URL *is* the page and the folder can grow (translations, code) without a new URL. | Same, for questions and for companies. | | A metadata table at the top of every page, between `` markers | Scannable, and machine-editable without parsing prose. | Same markers, same position. | -| `## Problem` → `## Reference solution` (collapsed) | The reader decides whether to look. | Same order; solution and each hint in `
`. | +| `## Problem` → `## Reference solution` (collapsed) | The reader decides whether to look. | Problem, then each hint in `
`; the solution is a link to the site (§8.2). | | Behavioral rounds are pages too | "What happens in the recruiter screen" is content, not a footnote. | Our 363 Study-section guides become those pages. | | An honest disclaimer at the top of the README | Unofficial, reconstructed, not the exact question; open an issue to take something down. | Same, adapted. | | Text licensed separately from code | CC BY-NC for prose makes a commercial mirror explicitly not permitted. | Proposed; see §8. | @@ -45,7 +48,7 @@ Counted on production, 2026-09-24, non-archived rows only. | Free questions — system design | 12 | 8 | | | Free questions — AI coding | 7 | 6 | Project zips stay on the site; the statement is published. | | **Free questions, total** | **166** | **99** | Through `companies[]`, *every* company has at least one. Median **2** per company, p90 12, max 30. | -| Reference solutions for those | 166 | | Each free question has a `solution_discussion_id` → "Reference solution" (~3 MB total). | +| Reference solutions for those | 166 | | Each free question has one on the site. **Not published here** (§8.2). | | Hints for those | 147 | | `questions.hints`. | | Study guides (`type = blog`) | 363 | 83 | All `access_tier = free`. Median 3 per company. | | … of which company **interview-process** guides | 163 | 81 | `-interview-process` plus per-role (`…-software-engineer-interview-process`). 18 companies have none. | @@ -67,15 +70,13 @@ companies/ google/ README.md company home (§4.1) interview-process.md the loop, from google-interview-process (§4.2) - interview-process/ - software-engineer.md per-role process guides, when they exist - machine-learning-engineer.md + interview-process-software-engineer.md per-role process guides, when they exist + interview-process-machine-learning-engineer.md guides/ - behavioral-round-googliness.md every other Study guide filed under Google + bq-round-google-style.md every other Study guide filed under Google google-hiring-assessment-gha.md - questions.md every question reported here: free → local page, - paid → site link (§4.4) - google.md one-line stub → google/ (old URL; §7) + google.md the counted statistics page, unchanged, with a link + to google/ at the top (old URL; §4.4, §7) questions/ algorithm//README.md one page per FREE question (§4.3) object-oriented-programming//README.md @@ -106,20 +107,17 @@ only happens when the catalog row stops being free or disappears. Top to bottom, in the order a candidate needs it: -1. **Title + one line**: `# Google interview process & questions`, then the counts line - that exists today. -2. **Metadata table** (`meta:begin/end`): company type, headcount band, questions tracked, - free to read here, most recent sighting, guides. -3. **The loop** — the first ~2 sections of `interview-process.md` inlined (the process - diagram and stage list), then *Read the full process →*. No process guide → today's - counted "The loop, as reported" table in its place. -4. **Free questions you can read here** — table: title (→ local page), format, difficulty, - round, last reported, *Practise* (→ site). Ordered the way `free/` orders them. -5. **Guides** — per-role process guides, then every other guide, one line each with its - tags. -6. **What's been asked lately** — today's 90-day block and "Start here", with paid rows - marked 🔒 and linking to the site. -7. **Every question** → `questions.md`. +1. **Title + one line**: `# Google interview process & questions`. +2. **At a glance**: questions reported, free to read here, process guides, other guides, + most recent sighting. +3. **How Google interviews** — the opening of `interview-process.md` up to its second + section (the process diagram and how the rounds run), then *Read the full process →*, + then the per-role guides. No process guide → a pointer at the counted "The loop, as + reported" table on the statistics page. +4. **Free questions** — table: title (→ local page), format, difficulty, round, last + reported, *Solve* (→ site). Newest sighting first. +5. **Guides** — every other guide, with its tags. +6. **Everything else** → the statistics page (`../google.md`) and the site. Every block is either a published body or a count, exactly the split `DESIGN.md` §3b draws. The page never asserts anything about the employer that is not in a guide the site @@ -145,7 +143,7 @@ Mirrors the reference page exactly: | Algorithm | Easy | Stripe · Amazon · Atlassian · Google · +6 | Phone screen, Onsite | hashing, sliding-window | 30 min | Dec 2025 | -> ▶ **[Run it on TrueInterview](https://trueinterview.io/questions/rate-limiter)** — editor, +> ▶ **[Solve it on TrueInterview](https://trueinterview.io/questions/rate-limiter)** — editor, > sample and hidden tests, and a judged verdict. Free, no card. ## Problem @@ -154,23 +152,22 @@ Mirrors the reference page exactly: ## Hints
Hint 1 …
-## Reference solution -
Show the solution -…solution discussion… -
+## Solution +The reference solution is on the question page, beside an editor … (a link, never the text) ## Asked at Stripe (Dec 2025) · Amazon · … ← each links to companies// ``` -The *Run it* link is the one call to action and sits above the statement: a reader who +The *Solve it* link is the one call to action and sits above the statement: a reader who wants to practise should never scroll past the answer to find the editor. -### 4.4 Company question list — `companies//questions.md` +### 4.4 Company statistics — `companies/.md` -Today's `companies/.md` catalog table, unchanged in content, paginated by the same -192 KB budget. The only difference is the title cell: a free question links to its local -page with *Practise* beside it; a paid one links to the site with 🔒. +Today's page, unchanged: the counted preamble and the full catalog table, paginated by +the same 192 KB budget. It gains one link at the top, to the company home. Keeping it at +its old path (rather than moving it into the folder) means every link the job-list +repositories and search results already hold still lands on a real page. ## 5. Where the bodies come from, and what never leaves @@ -187,14 +184,20 @@ through. So the bodies do **not** come from `/api/v1`. Three options were consid | The sync reads Supabase directly with a service-role key | Rejected. A service-role key in a public repository's Actions secrets, and the *what is free* filter written in Python here, far from the code that decides it. | | **A secret-guarded export route on the site** | **Proposed.** | -`GET /api/export/free-content` on trueinterview, guarded by its own +`GET /api/cron/content-export` on trueinterview (under `/api/cron/` because that is where the +site keeps its secret-guarded machine doors; nothing schedules it), guarded by its own `CONTENT_EXPORT_SECRET` (never `CRON_SECRET`, for the reason `CONFORMANCE_SECRET` gives: a key that can be handed to a CI job must not also open cron routes). It returns: -- free questions: catalog metadata + `content_md` + `hints` + the reference-solution - discussion + `target_minutes`; -- Study guides: metadata + `content_md` + tags; -- a `generatedAt`, and counts so a short read is detectable. +- free questions: `slug`, `type`, `contentMd`, `hints` — keyed by slug, because the + metadata already arrives from `/api/v1`; +- Study articles: `slug`, `contentMd`; +- a `generatedAt`. + +The read never selects the solution, the tests, the stubs, the schema or the project, so +no later edit to the mapping can ship one. The repository then checks every body against +the public metadata again (`catalog.content_from_payload`): a body whose slug `/api/v1` +does not list as free is dropped and counted. **The filter lives in one server-side function**, and it is the whole safety argument: `access_tier = 'free'` **as the entitlement code reads it** (not a second interpretation @@ -208,10 +211,10 @@ a paid question permanently. | Never exported | Why | | :-- | :-- | | `test_cases`, hidden datasets, `sql_schema` expectations | The judge's protection is the number of hidden cases (see CLAUDE.md). Examples already inside `content_md` are the only tests published. | -| `code_stubs`, AI-coding project zips | Useful only in the workspace; the *Run it* link is where they belong. | +| `code_stubs`, AI-coding project zips | Useful only in the workspace; the *Solve it* link is where they belong. | | Any pro / insider body | By construction of the filter. The export never selects them. | | Interview experiences (面经) | Metered per reader in SQL (`claim_interview_read`). A GitHub copy would be the network-tab bypass `docs/paywall-exposure.md` exists to close. Titles + links only, as today. | -| Community discussions other than the reference solution | User-generated, with their own authors and moderation state. | +| Reference solutions and community discussions | User-generated, with their own authors and moderation state. | **Link rewriting.** 162 guides contain site-relative links (`](/questions/…)`). The renderer rewrites each one: to the local page if the target is published here, otherwise @@ -223,7 +226,7 @@ Storage and render on GitHub unchanged. A link the rewriter cannot classify fail ``` trueinterview.io/api/v1/* ──► catalog.py (unchanged: metadata) -trueinterview.io/api/export/free-content +trueinterview.io/api/cron/content-export ──► content.py fetch bodies, validate, rewrite links ──► pages.py company home / process / guide / question ──► build.py assemble every file (pure) @@ -234,9 +237,10 @@ Every property in `DESIGN.md` §4 holds unchanged, and three are worth restating bodies raise the stakes: - **A failed or short export writes nothing.** An hourly job that rendered zero free - questions would delete 166 pages from a public repository. The export returns its own - counts; if it returns fewer than 80% of the previous run's rows, the run fails and a - human looks. + questions would delete 166 pages from a public repository. A failed read raises; a run + that would remove more than 20% of the published question pages stops + (`MAX_CONTENT_SHRINK`); and a run with no secret over a repository that already has + question pages stops rather than deleting them. - **Pruning is scoped** to `questions/` and the generated parts of `companies//`. A question that becomes paid is removed on the next sync — it stays in git history, which is why the filter in §5.1 has to be right the first time. @@ -259,37 +263,37 @@ look scraped. ## 7. Compatibility - `companies/.md` is linked from the two job-list repositories and from search - results. It becomes a three-line stub pointing at `companies//`, and stays one - (GitHub has no redirects; a stub costs nothing). + results. It stays where it is, as the statistics page, with the company home one link + away. The company index and the README's company list now point at the home. - `free/`, `formats/`, `by-month/`, `insights/` keep their paths. Their free rows now link to the local page. -- `data/questions.jsonl` gains a `path` field for free rows. No body goes into `data/` — - the export files are metadata, the pages are the content. - -## 8. Decisions needed before anything is published - -1. **Publishing bodies at all.** `trueinterview/docs/anti-scraping.md` says the catalog is - licensed content and mirroring it is not permitted, and `docs/public-api.md` builds on - that. This proposal mirrors the free tier on purpose. If accepted, both documents need a - sentence stating the exception and its boundary (free tier, through one export route), - or the next person to read them will treat this repository as the leak. -2. **Reference solutions.** Publishing them is most of the reference repo's value, and - they are free on the site. Recommended: yes, collapsed. -3. **License.** Recommended: text under CC BY-NC 4.0 (a commercial mirror is then - explicitly not permitted), the scripts under MIT, as the reference does. -4. **Search duplication.** A GitHub page with the full statement can outrank the site's - own page for the question title. Mitigations that keep the content: the *Run it* link - above the statement, `github.com` treated as a referral channel in - `/admin/sources`, and watching the site's impressions for free-question URLs for a - month after launch. The alternative — publishing statements but not solutions — keeps - more reason to click through, at the cost of the reference repo's main feature. +- `data/paths.json` is the path registry. No body goes into `data/` — the export files + are metadata, the pages are the content. + +## 8. Decisions (settled 2026-09-24) + +1. **Publish the free tier's bodies: yes**, to make the free part of the product + findable and shareable. The site's `docs/anti-scraping.md` and `docs/public-api.md` + now state the exception and its boundary (the free tier, through one export route); + `/api/v1` still carries no bodies. +2. **Reference solutions: not published.** The page links to the solution on the site, + beside the editor. It is the reason to click through, and it keeps the answer one step + away from someone who has not tried the problem yet. +3. **License: CC BY 4.0** for the text ([`LICENSE-CONTENT.md`](LICENSE-CONTENT.md)), + MIT for the scripts. Chosen for reach: anyone may repost it anywhere, including + commercially, and every repost has to credit TrueInterview with a link. The cost, + accepted knowingly, is that a competitor may republish the free questions too — with + attribution. +4. **Search duplication: accepted.** The *Solve it* link sits above every statement, and + the solution stays on the site. Worth watching the site's impressions for free-question + URLs for a month after launch. ## 9. Rollout -| Step | Repo | Scope | +| Step | Where | State | | :-- | :-- | :-- | -| 1 | trueinterview | Export route + service + tests (filter asserted against the entitlement code; a pro/insider fixture must never appear); `CONTENT_EXPORT_SECRET`; the doc exceptions from §8.1. Needs sign-off: reads `access_tier`. | -| 2 | here | `content.py`, `pages.py`, path registry, link rewriter; fixture tests that render a company end to end with no network. | -| 3 | here | Pilot: render **OpenAI, Google, Amazon** only (a feature list in `sync.py`), review by hand, check GitHub rendering on a phone. | -| 4 | here | All 99 companies; README rewritten as the landing page in §3. | -| 5 | both | Optional: `README.zh.md` per page, as the reference does, if the Chinese-speaking audience asks for it. | +| 1 | trueinterview: `free-content-export.ts`, `/api/cron/content-export`, tests, doc exceptions | in a PR to `develop` | +| 2 | here: `scripts/content.py`, the path registry, link rewriting, the sync guards, tests | this PR | +| 3 | Deploy step 1, set `CONTENT_EXPORT_SECRET` in Vercel **and** as this repository's Actions secret (same value, `openssl rand -hex 32`) | manual | +| 4 | Run the sync workflow by hand once, read a few company homes on a phone | manual | +| 5 | Optional: a `README.zh.md` per page, as the reference does, if the Chinese-speaking audience asks for it | later | diff --git a/DESIGN.md b/DESIGN.md index 3f9288c1..c9e1e83b 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -278,11 +278,12 @@ trueinterview.io/api/v1/interview-experiences ──┤ pure functions of `(records, date)`, which is what lets the test suite render the entire repository from a fixture and compare bytes, with no network and no clock. -**Metadata, never bodies.** The API this reads publishes titles, companies, formats, -difficulties, sighting months and URLs — and deliberately no problem statements, no -solutions and no test cases. This repository carries exactly what that API carries. The -distinction is the whole reason an index like this can be public: it is a pointer into the -site, not a copy of it. +**Metadata, and the free tier's bodies — nothing more.** The API this reads publishes +titles, companies, formats, difficulties, sighting months and URLs, and deliberately no +problem statements, solutions or test cases. Since Sep 2026 one more source is read: the +free tier's statements, hints and interview guides, from a separate secret-guarded export, +rendered as company homes and question pages. Solutions, test cases and paid questions +are still never here. How that works and why: [`CONTENT-DESIGN.md`](CONTENT-DESIGN.md). ### Properties worth keeping when you change something diff --git a/LICENSE-CONTENT.md b/LICENSE-CONTENT.md new file mode 100644 index 00000000..43b1553c --- /dev/null +++ b/LICENSE-CONTENT.md @@ -0,0 +1,30 @@ +# Content license + +The **text** in this repository — the question statements and hints under +`questions/`, and the company pages, interview-process guides and other guides +under `companies/` — is © TrueInterview and licensed under the +[Creative Commons Attribution 4.0 International license (CC BY 4.0)](https://creativecommons.org/licenses/by/4.0/). +The full legal text is at . + +You may copy, repost, translate and adapt it — in a blog post, a study group, +a course, another repository, commercially or not — as long as you give credit. + +## How to credit + +Name TrueInterview, link to the original page, and say whether you changed it. +For example: + +> From [TrueInterview](https://trueinterview.io) — +> [Rate Limiter](https://trueinterview.io/questions/rate-limiter), CC BY 4.0. + +A link to this repository instead of the page is fine too. + +## What is not covered + +- **The scripts** in `scripts/` and the workflows in `.github/` are under the + MIT license in [`LICENSE`](LICENSE). +- **Company names and logos** belong to their owners. They are used here only + to say where a question was reported; no company endorses this repository. +- **Anything linked on trueinterview.io but not published here** — reference + solutions, test cases, paid questions and interview reports — is not part of + this license. diff --git a/README.md b/README.md index fc31099c..84dc2ce0 100644 --- a/README.md +++ b/README.md @@ -24,9 +24,14 @@ --- -Every title here opens the real problem on [TrueInterview](https://trueinterview.io) — a -runnable workspace, not a screenshot, and a server-judged verdict on the algorithm, -low-level-design and SQL formats. Synced from the live catalog every hour. +**Every company has a home page** — how it interviews, its interview-process guides in +full, and its free questions with the whole statement and hints — under +[`companies/`](companies/README.md). The free questions live under +[`questions/`](questions/README.md), one folder each. Everything else opens the real problem on +[TrueInterview](https://trueinterview.io): a runnable workspace, not a screenshot, and a +server-judged verdict on the algorithm, object-oriented-programming and SQL formats. +Synced from the live catalog every hour, and free to share under +[CC BY 4.0](LICENSE-CONTENT.md). ## 📊 What companies are actually asking @@ -267,16 +272,17 @@ is on a company page, a format page, and (if it carries a sighting date) a month | [`data/companies.csv`](data/companies.csv) | every company and its question count | | [`data/guides.csv`](data/guides.csv) | every Study-section writeup, with its company and topics | | [`data/insights.json`](data/insights.json) | every number on the [insights pages](insights/README.md), as data | +| [`data/paths.json`](data/paths.json) | the folder each published question and guide was given — stable, so links never move | | [Live API](https://trueinterview.io/developers/api) | what this repo is generated from | ## ⚙️ How it stays current -Everything under `companies/`, `formats/`, `by-month/`, `guides/`, `insights/`, `free/`, -`experiences/` and `data/` is generated hourly by [`scripts/sync.py`](scripts/sync.py) from TrueInterview's public, documented, -read-only catalog API. That API publishes **metadata only** — a title, a company, a format, -a difficulty, a sighting month, a URL. No problem statements, no solutions, no test cases, -and neither does this repository: what you get here is the index, and the questions -themselves live on the site. +Everything under `companies/`, `questions/`, `formats/`, `by-month/`, `guides/`, `insights/`, +`free/`, `experiences/` and `data/` is generated hourly by [`scripts/sync.py`](scripts/sync.py) +from TrueInterview's public, documented, read-only catalog API — which publishes metadata +only — plus one export of the **free tier's** bodies: the statements and hints of free +questions, and the interview guides. Solutions, test cases and paid questions are never +exported, so they are never here; they live on the site. ```bash python3 scripts/sync.py # refresh from the live catalog @@ -296,9 +302,11 @@ never a screenshot or a copied problem statement.** ## 📄 Licence -The tracker — these scripts and the index they generate — is MIT ([LICENSE](LICENSE)). The -questions and guides it points at belong to TrueInterview and are published on the site -under its own terms. +**The text** — question statements, hints, company pages and interview guides — is +licensed [CC BY 4.0](LICENSE-CONTENT.md): repost, translate or adapt it anywhere, +commercially or not, crediting TrueInterview with a link back. **The scripts** are MIT +([LICENSE](LICENSE)). Reference solutions, test cases and paid questions are not published +here and are not covered by either. --- diff --git a/scripts/build.py b/scripts/build.py index 454c0c8f..01fcc170 100644 --- a/scripts/build.py +++ b/scripts/build.py @@ -8,12 +8,14 @@ from __future__ import annotations +import json from datetime import date from typing import Sequence import report from catalog import Catalog, Experience, Guide, Question, parse_catalog_date from company_page import company_preamble, company_type_preamble +from content import render_content from segments import SECTORS, SECTOR_BY_ID, SIZE_LABELS, segment_of from insights import compute as compute_insights from labels import FORMAT_ORDER, JUDGED_FORMATS, company_key, company_label, format_label @@ -247,7 +249,7 @@ def _companies_index(stats_view, api_labels: dict[str, str], cut_ids: frozenset[ by_sector.setdefault(sector, []).append(row) def link(row) -> str: - return f"[{escape_cell(row.name)} ({row.questions:,})]({row.key}.md)" + return f"[{escape_cell(row.name)} ({row.questions:,})]({row.key}/README.md)" body = [ GENERATED_NOTICE, @@ -363,7 +365,14 @@ def _type_cell(name: str, api_labels: dict[str, str]) -> str: return " · ".join(parts) -def build(catalog: Catalog, readme_template: str, today: date) -> RenderResult: +def build( + catalog: Catalog, + readme_template: str, + today: date, + paths: dict[str, str] | None = None, +) -> RenderResult: + """Every generated file. ``paths`` is the committed ``data/paths.json``: the + folder each published question and guide was given, which must not move.""" questions, guides, api_labels = catalog.questions, catalog.guides, catalog.labels ordered = sort_questions(questions, today) guides_by_company = group_guides_by_company(guides, api_labels) @@ -439,7 +448,8 @@ def build(catalog: Catalog, readme_template: str, today: date) -> RenderResult: else ", judged server-side on the algorithm, low-level-design and SQL formats." ) ), - back="[← All companies](README.md) · [← Question bank](../README.md)", + back=f"[📖 How {escape_cell(name)} interviews & the free questions]({key}/README.md) · " + "[← All companies](README.md) · [← Question bank](../README.md)", questions=rows, cols=columns_for("company", api_labels, today), today=today, @@ -460,6 +470,22 @@ def build(catalog: Catalog, readme_template: str, today: date) -> RenderResult: files["companies/README.md"] = _companies_index(stats_view, api_labels, cut_ids) + # ── the content layer ──────────────────────────────────────────────────── + # A home per company, and the free tier in full — see `content.py`. The + # path registry is an output as well as an input: a question published for + # the first time is given its folder here, and keeps it from then on. + content_files, registry, content_stats = render_content( + questions=ordered, + guides=guides, + by_company=by_company, + content=catalog.content, + registry=dict(paths or {}), + api_labels=api_labels, + today=today, + ) + files.update(content_files) + files["data/paths.json"] = json.dumps(registry, indent=1, sort_keys=True, ensure_ascii=False) + "\n" + # ── company-type pages ─────────────────────────────────────────────────── # "What do quant firms ask" was not a question this repository could answer: # it knew what Citadel asks and what Optiver asks, and had no way to put the @@ -825,6 +851,8 @@ def build(catalog: Catalog, readme_template: str, today: date) -> RenderResult: future_dated = [q.slug for q in ordered if q.reported_date and q.reported_date > today] stats = { + **{f"content_{k}": v for k, v in content_stats.items()}, + "content_configured": catalog.content is not None, "future_dated": future_dated, "questions": len(ordered), "guides": len(guides), diff --git a/scripts/catalog.py b/scripts/catalog.py index 8c325250..1d321525 100644 --- a/scripts/catalog.py +++ b/scripts/catalog.py @@ -5,11 +5,16 @@ it reads exactly one thing: the public, documented, read-only API at ``/api/v1`` (spec: https://trueinterview.io/openapi.json). That API publishes metadata and never bodies — a title, a company, a format, a difficulty, a -sighting month, a URL — so this repository is a pointer into the site, not a -copy of it. Nothing here fetches a question statement, a solution, or a test -case, and nothing may be added that does: the moment this directory holds the -content instead of the address, it stops being an index and starts being a -mirror of a product that people pay for. +sighting month, a URL. + +The one exception is the FREE tier, which this repository republishes on +purpose: the statements and hints of free practice questions and the Study +articles, read from ``/api/cron/content-export`` behind the +``CONTENT_EXPORT_SECRET`` Actions secret (see ``CONTENT-DESIGN.md``). The site +decides what is free and never sends a solution, a test case or a paid row; +:func:`load_catalog` checks every body against the metadata again anyway. With +the secret unset the export is simply not read, and the repository renders the +metadata-only pages it always did. Two properties the rest of the pipeline relies on: @@ -27,6 +32,7 @@ from __future__ import annotations import json +import os import time import urllib.error import urllib.request @@ -161,6 +167,31 @@ class Experience: posted_date: date | None +@dataclass(frozen=True) +class QuestionBody: + """A free question's statement and hints, as the site's export hands them over.""" + + slug: str + type: str + content_md: str + hints: tuple[str, ...] + + +@dataclass(frozen=True) +class Content: + """The free tier's bodies, keyed by catalog slug. + + ``dropped`` counts bodies the export sent that the metadata did not vouch + for — a slug the question list does not carry, or one it does not mark + free. They are never rendered; the count is printed so a disagreement + between the two endpoints is seen rather than silently resolved. + """ + + questions: dict[str, QuestionBody] + articles: dict[str, str] + dropped: int = 0 + + def _str_list(value: Any) -> tuple[str, ...]: if not isinstance(value, list): return () @@ -440,6 +471,31 @@ def fetch_experiences(base_url: str, *, timeout: int = 30) -> tuple[list[dict[st return [item for item in rows if isinstance(item, dict)], total +def fetch_content(base_url: str, secret: str, *, timeout: int = 60) -> dict[str, Any]: + """The free tier's bodies from the site's export. + + Not the public API, and not its ``{ok, data}`` envelope: a plain JSON + object ``{generatedAt, questions, articles}``. Every failure raises — the + renderer prunes question pages that stop appearing, so an unreadable export + must stop the sync rather than read as "nothing is free any more". + """ + url = f"{base_url.rstrip('/')}/api/cron/content-export" + request = urllib.request.Request( + url, + headers={"User-Agent": USER_AGENT, "Accept": "application/json", "Authorization": f"Bearer {secret}"}, + ) + try: + with urllib.request.urlopen(request, timeout=timeout) as response: + payload = json.load(response) + except (urllib.error.HTTPError, urllib.error.URLError, TimeoutError, json.JSONDecodeError, OSError) as error: + raise CatalogError(f"could not read {url}: {error}") from error + if not isinstance(payload, dict) or not isinstance(payload.get("questions"), list) or not isinstance( + payload.get("articles"), list + ): + raise CatalogError(f"{url} did not answer with a content export") + return payload + + def fetch_catalog(base_url: str = DEFAULT_BASE_URL, *, timeout: int = 30) -> dict[str, Any]: """The whole snapshot this repository is rendered from.""" base = base_url.rstrip("/") @@ -453,6 +509,9 @@ def fetch_catalog(base_url: str = DEFAULT_BASE_URL, *, timeout: int = 30) -> dic "experiences": experiences, "experiencesTotal": experiences_total, "companyLabels": fetch_company_labels(base, timeout=timeout), + # Absent (None) is "not configured", which renders the metadata-only + # pages; it is never read as "nothing is free". + "content": fetch_content(base, secret) if (secret := os.environ.get("CONTENT_EXPORT_SECRET")) else None, } @@ -473,6 +532,10 @@ class Catalog: #: that it is a slice; `None` means the size is unknown, not zero. experiences_total: int | None labels: dict[str, str] + #: The free tier's bodies, or ``None`` when the export was not read. ``None`` + #: renders the metadata-only pages; an empty :class:`Content` is a real + #: answer ("nothing is free") and is treated as one. + content: Content | None = None def load_catalog(payload: Any) -> Catalog: @@ -526,7 +589,9 @@ def load_catalog(payload: Any) -> Catalog: # Absent means complete: a hand-written fixture should not have to opt in to # the normal case, and only a live read that fell short sets it False. guides_complete = payload.get("guidesComplete") + content = content_from_payload(payload.get("content"), questions, guides) return Catalog( + content=content, questions=questions, guides=guides, guides_complete=guides_complete is not False, @@ -536,6 +601,50 @@ def load_catalog(payload: Any) -> Catalog: ) +def content_from_payload(raw: Any, questions: list[Question], guides: list[Guide]) -> Content | None: + """Validate the export against the metadata it will be rendered beside. + + The second fence. The site already exports only free rows; a body is kept + here only if the public question list ALSO says that slug is free, or the + public article list carries it. Anything else is dropped and counted — a + disagreement between two endpoints is resolved toward publishing less. + """ + if raw is None: + return None + if not isinstance(raw, dict): + raise CatalogError("content export must be a JSON object") + raw_questions, raw_articles = raw.get("questions"), raw.get("articles") + if not isinstance(raw_questions, list) or not isinstance(raw_articles, list): + raise CatalogError("content export has no questions/articles arrays") + free = {q.slug: q for q in questions if q.access_tier == "free"} + guide_slugs = {g.slug for g in guides} + bodies: dict[str, QuestionBody] = {} + articles: dict[str, str] = {} + dropped = 0 + for item in raw_questions: + if not isinstance(item, dict): + raise CatalogError("content export has a malformed question") + slug, text = item.get("slug"), item.get("contentMd") + if not isinstance(slug, str) or not isinstance(text, str) or not text.strip(): + raise CatalogError(f"content export question {slug!r} has no body") + meta = free.get(slug) + if meta is None or item.get("type") != meta.type: + dropped += 1 + continue + bodies[slug] = QuestionBody(slug=slug, type=meta.type, content_md=text.strip(), hints=_str_list(item.get("hints"))) + for item in raw_articles: + if not isinstance(item, dict): + raise CatalogError("content export has a malformed article") + slug, text = item.get("slug"), item.get("contentMd") + if not isinstance(slug, str) or not isinstance(text, str) or not text.strip(): + raise CatalogError(f"content export article {slug!r} has no body") + if slug not in guide_slugs: + dropped += 1 + continue + articles[slug] = text.strip() + return Content(questions=bodies, articles=articles, dropped=dropped) + + def snapshot(catalog: "Catalog", source: str) -> dict[str, Any]: """Round-trip a set of records back into the snapshot shape (for --snapshot-out).""" questions, guides, labels = catalog.questions, catalog.guides, catalog.labels @@ -544,6 +653,17 @@ def snapshot(catalog: "Catalog", source: str) -> dict[str, Any]: "companyLabels": labels, "guidesComplete": catalog.guides_complete, "experiencesTotal": catalog.experiences_total, + "content": None + if catalog.content is None + else { + "questions": [ + {"slug": b.slug, "type": b.type, "contentMd": b.content_md, "hints": list(b.hints)} + for b in sorted(catalog.content.questions.values(), key=lambda b: b.slug) + ], + "articles": [ + {"slug": slug, "contentMd": text} for slug, text in sorted(catalog.content.articles.items()) + ], + }, "experiences": [ { "id": e.id, diff --git a/scripts/content.py b/scripts/content.py new file mode 100644 index 00000000..a9d85c12 --- /dev/null +++ b/scripts/content.py @@ -0,0 +1,661 @@ +#!/usr/bin/env python3 +"""The free tier, rendered as pages you can read here. + +Everything else in this repository is an index: titles, counts and dates, each +row a link into trueinterview.io. This module renders the part that is CONTENT, +from the free tier's bodies (``catalog.Content``): + + * ``companies//README.md`` — a company's home: how it interviews, its + free questions, its guides. Rendered for every company, with or without + bodies; without them every link simply points at the site. + * ``companies//interview-process.md`` (+ ``interview-process-.md``) + — the site's interview-process guides, in full. + * ``companies//guides/.md`` — every other Study guide filed there. + * ``questions///README.md`` — one page per free question: the + statement and the hints. Never the solution: that stays on the site, next to + the editor that runs an attempt against the hidden tests, and it is the + reason to click through. + +Three rules, each with a reason: + + * **A path, once published, does not move.** A question's folder is named + from its slug (or, for a UUID slug, its title) the first time it appears, + and recorded in ``data/paths.json``. A later title change leaves the file + where it is, because a moved file is a broken link on every page that + shared it. See :func:`assign_paths`. + * **A body is stored once.** A free question is reported at up to a dozen + employers; its page lives under its format and every company links to it, + rather than a dozen copies drifting apart. + * **Links in a body land somewhere real.** The site writes site-relative + links (``/questions/x``, ``/study/y``). Each one becomes the page here when + this repository publishes that target, and the absolute site URL when it + does not. See :func:`rewrite_links`. + +Pure, like ``build.py``: records in, a path → text map out. +""" + +from __future__ import annotations + +import posixpath +import re +from dataclasses import dataclass +from datetime import date +from typing import Sequence + +from catalog import Content, Guide, Question +from insights import ROUND_LABELS +from labels import company_key, company_label, difficulty_label, format_label +from render import GENERATED_NOTICE, date_label, escape_cell, plural, sort_questions, table + +SITE = "https://trueinterview.io" + +LICENSE_URL = "https://creativecommons.org/licenses/by/4.0/" + +REPO = "https://github.com/kevin-2023-code/Tech-Interview-Questions" + +#: Formats whose runs get a server-judged verdict on the site. Object-oriented +#: programming routes into the algorithm workspace, so it is judged too. +JUDGED = frozenset({"algorithm", "object-oriented-programming", "sql"}) + +#: A guide shorter than this is a prompt filed as an article, not a writeup, and +#: gets no page of its own: a page of two sentences is what makes a repository +#: look scraped. It is still listed, linking to the site. +MIN_GUIDE_CHARS = 600 + +#: How much of the interview-process guide the company home quotes before +#: "Read the full process". The first section is the loop itself. +PROCESS_EXCERPT_CHARS = 3500 + +MAX_NAME_CHARS = 72 + +_UUID = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$") +PROCESS_SUFFIX = "interview-process" + + +def slugify(text: str) -> str: + """A file-name-safe slug, the site's own shape (``[a-z0-9-]``).""" + slug = re.sub(r"[^a-z0-9]+", "-", text.lower().replace("&", " and ")).strip("-") + return slug[:MAX_NAME_CHARS].rstrip("-") or "untitled" + + +def _readable(slug: str, title: str) -> str: + return slugify(title) if _UUID.match(slug) else slugify(slug) + + +# ── paths ──────────────────────────────────────────────────────────────────── + + +@dataclass(frozen=True) +class GuidePlan: + """Where one guide lives here, if anywhere, and what kind it is.""" + + guide: Guide + company: str | None # the company home it is filed under + kind: str # "process" | "role" | "guide" + role: str | None + path: str | None # None: listed, but no page of its own + + +def assign_paths( + registry: dict[str, str], + wanted: Sequence[tuple[str, str, str]], +) -> dict[str, str]: + """Stable paths for ``(key, directory, name)`` requests. + + An entry already in ``registry`` keeps its path as long as it is still in + the directory asked for — a question whose FORMAT changed moves, because + its old folder now sits under the wrong heading. Every path the registry has + ever held stays reserved, so a retired question's URL is never handed to a + different question. New entries are named in the order given, which the + caller makes deterministic, with ``-2``, ``-3`` on a collision. + """ + taken = set(registry.values()) + out = dict(registry) + for key, directory, name in wanted: + current = registry.get(key) + if current is not None and posixpath.dirname(current) == directory: + continue + candidate, n = name, 1 + while True: + path = f"{directory}/{candidate}" + if path not in taken: + break + n += 1 + candidate = f"{name}-{n}" + taken.add(path) + out[key] = path + return out + + +def question_path(registry: dict[str, str], question: Question) -> str: + return f"{registry[f'question:{question.slug}']}/README.md" + + +def _process_role(guide: Guide) -> tuple[str, str | None] | None: + """``("process", None)``, ``("role", "software-engineer")`` or ``None``. + + The site names a company's process guide ``-interview-process`` and + a role's ``--interview-process``, where ```` is the + STORED company value (``akunacapital``, ``scale.ai``), not this repository's + page key — so the prefix is derived from the raw values the guide carries. + """ + if not guide.slug.endswith(PROCESS_SUFFIX): + return None + stem = guide.slug[: -len(PROCESS_SUFFIX)].rstrip("-") + for raw in guide.companies: + # `Akuna Capital` is stored as `akunacapital`: try the slug both with and + # without its word breaks, so a display name matches as well as a raw value. + for prefix in dict.fromkeys((slugify(raw), slugify(raw).replace("-", ""))): + if stem == prefix: + return "process", None + if stem.startswith(prefix + "-"): + return "role", stem[len(prefix) + 1 :] + return None + + +def plan_guides( + guides: Sequence[Guide], + homes: frozenset[str], + content: Content | None, + registry: dict[str, str], + api_labels: dict[str, str], +) -> tuple[list[GuidePlan], dict[str, str]]: + """Decide where every guide goes. Returns the plans and the updated registry.""" + bodies = content.articles if content else {} + plans: list[GuidePlan] = [] + wanted: list[tuple[str, str, str]] = [] + taken_process: set[tuple[str, str | None]] = set() + pending: list[tuple[Guide, str | None, str, str | None]] = [] + for guide in sorted(guides, key=lambda g: g.slug): + home = next( + (key for key in (company_key(c, api_labels) for c in guide.companies) if key in homes), + None, + ) + kind, role = "guide", None + detected = _process_role(guide) if home else None + if detected and (home, detected[1]) not in taken_process: + kind, role = detected + taken_process.add((home, role)) + pending.append((guide, home, kind, role)) + body = bodies.get(guide.slug) + # A guide filed under no company home gets no page: nothing here would + # link to it, and the guides index already points at the site. + if kind == "guide" and home and body is not None and len(body) >= MIN_GUIDE_CHARS: + wanted.append((f"guide:{guide.slug}", f"companies/{home}/guides", _readable(guide.slug, guide.title))) + registry = assign_paths(registry, wanted) + for guide, home, kind, role in pending: + path = None + if guide.slug in bodies: + if kind == "process": + path = f"companies/{home}/interview-process.md" + elif kind == "role": + path = f"companies/{home}/interview-process-{role}.md" + elif home and f"guide:{guide.slug}" in registry and len(bodies[guide.slug]) >= MIN_GUIDE_CHARS: + path = f"{registry[f'guide:{guide.slug}']}.md" + plans.append(GuidePlan(guide=guide, company=home, kind=kind, role=role, path=path)) + return plans, registry + + +# ── bodies ─────────────────────────────────────────────────────────────────── + +_INLINE = re.compile(r"(\]\(\s*]*)") +_REFERENCE = re.compile(r"^(\s*\[[^\]]+\]:\s*?\s*)$", re.M) +_ATTRIBUTE = re.compile(r"""((?:href|src)=["'])(/[^"']*)""") + + +def rewrite_links(markdown: str, from_path: str, local: dict[str, str]) -> str: + """Point every site-relative link at the page here, or at the site. + + ``local`` maps a site path (``/questions/two-sum``) to a repository path. + Anything not in it becomes absolute, so nothing is left pointing at a path + that does not exist in this repository. + """ + here = posixpath.dirname(from_path) + + def target(path: str) -> str: + split = re.match(r"^([^?#]*)(.*)$", path) + assert split is not None + bare, rest = split.group(1).rstrip("/") or "/", split.group(2) + if bare in local: + return posixpath.relpath(local[bare], here) + (rest if rest.startswith("#") else "") + return SITE + path + + markdown = _INLINE.sub(lambda m: m.group(1) + target(m.group(2)), markdown) + markdown = _REFERENCE.sub(lambda m: m.group(1) + target(m.group(2)) + m.group(3), markdown) + return _ATTRIBUTE.sub(lambda m: m.group(1) + target(m.group(2)), markdown) + + +def demote_headings(markdown: str) -> str: + """One heading level down, outside code fences — for a body quoted under an H2.""" + out, fenced = [], False + for line in markdown.split("\n"): + if line.lstrip().startswith(("```", "~~~")): + fenced = not fenced + if not fenced and re.match(r"^#{1,5} ", line): + line = "#" + line + out.append(line) + return "\n".join(out) + + +def process_excerpt(markdown: str) -> tuple[str, bool]: + """The opening of a process guide — up to its second section — and whether it was cut.""" + headings = [m.start() for m in re.finditer(r"^## ", markdown, re.M)] + end = headings[1] if len(headings) > 1 else len(markdown) + if end > PROCESS_EXCERPT_CHARS: + cut = markdown.rfind("\n\n", 0, PROCESS_EXCERPT_CHARS) + end = cut if cut > 0 else PROCESS_EXCERPT_CHARS + return markdown[:end].rstrip(), end < len(markdown.rstrip()) + + +# ── pieces ─────────────────────────────────────────────────────────────────── + + +def _root(path: str) -> str: + """The relative prefix from ``path`` back to the repository root.""" + depth = path.count("/") + return "../" * depth + + +def footer(path: str) -> str: + issues = f"{REPO}/issues/new?template=correction.yml" + return ( + "---\n\n" + f"From [TrueInterview]({SITE}) — the free part of its question bank and company interview " + f"guides, synced every hour. Text licensed [CC BY 4.0]({LICENSE_URL}): share or adapt it anywhere, " + f"crediting TrueInterview with a link back ([how]({_root(path)}LICENSE-CONTENT.md)). " + f"[Report a problem with this page]({issues}).\n" + ) + + +def _companies_line(names: Sequence[tuple[str, str]], homes: frozenset[str], from_path: str) -> str: + root = _root(from_path) + return " · ".join( + f"[{escape_cell(name)}]({root}companies/{key}/README.md)" if key in homes else escape_cell(name) + for key, name in names + ) + + +def _question_companies(question: Question, api_labels: dict[str, str]) -> list[tuple[str, str]]: + seen: dict[str, str] = {} + for raw in question.companies: + key = company_key(raw, api_labels) + if key and key not in seen: + seen[key] = company_label(raw, api_labels) + return list(seen.items()) + + +def _rounds(question: Question) -> str: + return ", ".join(ROUND_LABELS.get(r, r) for r in question.rounds) or "—" + + +def _reported(question: Question) -> str: + return date_label(question.reported_date, month_only=True) + + +# ── pages ──────────────────────────────────────────────────────────────────── + + +def question_page( + question: Question, + body_md: str, + hints: Sequence[str], + path: str, + local: dict[str, str], + homes: frozenset[str], + api_labels: dict[str, str], +) -> str: + companies = _question_companies(question, api_labels) + shown = companies[:6] + asked = " · ".join(escape_cell(name) for _key, name in shown) + ( + f" · +{len(companies) - len(shown)}" if len(companies) > len(shown) else "" + ) + meta = table( + ["Format", "Difficulty", "Asked at", "Round", "Topics", "Last reported"], + ["---"] * 6, + [ + [ + format_label(question.type), + difficulty_label(question.difficulty) or "—", + asked or "—", + _rounds(question), + escape_cell(", ".join(question.topics)) or "—", + _reported(question), + ] + ], + ) + offer = ( + "a runnable editor, the sample and hidden tests, a judged verdict, and the reference solution" + if question.type in JUDGED + else "the interview workspace, an AI interviewer to push back on your design, and the reference solution" + ) + lines = [ + GENERATED_NOTICE, + "", + f"# {question.title}", + "", + "", + meta, + "", + "", + f"> **▶ [Solve it on TrueInterview]({question.url})** — free, no card: {offer}.", + "", + "## Problem", + "", + rewrite_links(demote_headings(body_md) if re.search(r"^# ", body_md, re.M) else body_md, path, local), + "", + ] + if hints: + lines += ["## Hints", ""] + for index, hint in enumerate(hints, start=1): + lines += [ + "
", + f"Hint {index}", + "", + rewrite_links(hint, path, local), + "", + "
", + "", + ] + lines += [ + "## Solution", + "", + f"The reference solution is on [the question page]({question.url}), beside an editor that runs your " + "own attempt first. It is not reproduced here — try the problem before you read the answer.", + "", + ] + if companies: + lines += ["## Asked at", "", _companies_line(companies, homes, path), ""] + lines.append(footer(path)) + return "\n".join(lines) + + +def guide_page(plan: GuidePlan, body_md: str, name: str, key: str | None, local: dict[str, str], + siblings: Sequence[GuidePlan] = ()) -> str: + path = plan.path + assert path is not None + guide = plan.guide + root = _root(path) + if key: + home = posixpath.relpath(f"companies/{key}/README.md", posixpath.dirname(path)) + stats = posixpath.relpath(f"companies/{key}.md", posixpath.dirname(path)) + back = ( + f"[← {escape_cell(name)}]({home}) · [Every {escape_cell(name)} question]({stats}) · " + f"[Read it on TrueInterview]({guide.url})" + ) + else: + back = f"[← All guides]({root}guides/README.md) · [Read it on TrueInterview]({guide.url})" + lines = [GENERATED_NOTICE, "", f"# {guide.title}", "", back, ""] + if guide.tags: + lines += [" ".join(f"`{escape_cell(tag)}`" for tag in guide.tags), ""] + roles = [s for s in siblings if s.kind == "role" and s.path] + if plan.kind == "process" and roles: + lines += [ + "**By role:** " + + " · ".join( + f"[{escape_cell(_role_label(s.role))}]({posixpath.relpath(s.path, posixpath.dirname(path))})" + for s in roles + ), + "", + ] + lines += ["---", "", rewrite_links(body_md, path, local), "", footer(path)] + return "\n".join(lines) + + +def _role_label(role: str | None) -> str: + words = (role or "").split("-") + small = {"ai": "AI", "ml": "ML", "sre": "SRE"} + return " ".join(small.get(w, w.capitalize()) for w in words if w) + + +def company_home( + *, + key: str, + name: str, + questions: Sequence[Question], + plans: Sequence[GuidePlan], + content: Content | None, + local: dict[str, str], + registry: dict[str, str], + today: date, +) -> str: + path = f"companies/{key}/README.md" + free = [q for q in sort_questions(questions, today) if q.access_tier == "free"] + readable = [q for q in free if content and q.slug in content.questions] + process = next((p for p in plans if p.kind == "process"), None) + roles = [p for p in plans if p.kind == "role"] + others = [p for p in plans if p.kind == "guide"] + dated = [q.reported_date for q in questions if q.reported_date and q.reported_date <= today] + + glance = table( + ["", ""], + [":--", ":--"], + [ + ["Questions reported", f"[{len(questions):,}](../{key}.md)"], + ["Free to read here", f"{len(readable):,}" if content else f"{len(free):,} (on TrueInterview)"], + ["Interview-process guides", f"{int(process is not None) + len(roles)}"], + ["Other guides", f"{len(others):,}"], + ["Most recent sighting", date_label(max(dated)) if dated else "—"], + ], + ) + lines = [ + GENERATED_NOTICE, + "", + f"# {name} interview process & questions", + "", + f"How {escape_cell(name)} interviews, and the questions candidates reported there. Free questions are " + "published here in full, statement and hints; everything else links to TrueInterview.", + "", + f"[← All companies](../README.md) · [Every {escape_cell(name)} question, with statistics](../{key}.md) · " + f"[Practise on TrueInterview]({SITE}/problems/company/{key})", + "", + glance, + "", + f"## How {name} interviews", + "", + ] + process_body = content.articles.get(process.guide.slug) if (content and process) else None + if process and process.path and process_body: + excerpt, cut = process_excerpt(process_body) + lines += [ + rewrite_links(demote_headings(excerpt), path, local), + "", + f"**[Read the full {escape_cell(name)} interview process →](interview-process.md)**" + if cut + else f"From [{escape_cell(process.guide.title)}](interview-process.md).", + "", + ] + elif process: + lines += [f"[{escape_cell(process.guide.title)}]({process.guide.url}) — the full guide, on TrueInterview.", ""] + else: + lines += [ + f"No written process guide yet. [The loop, as reported](../{key}.md#the-loop-as-reported) counts which " + "round each reported question came from.", + "", + ] + if roles: + lines += [ + "**By role:** " + + " · ".join( + f"[{escape_cell(_role_label(p.role))}]({posixpath.relpath(p.path, f'companies/{key}') if p.path else p.guide.url})" + for p in roles + ), + "", + ] + + lines += [f"## Free {name} questions", ""] + if free: + rows = [] + for q in free: + target = ( + posixpath.relpath(question_path(registry, q), f"companies/{key}") + if content and q.slug in content.questions and f"question:{q.slug}" in registry + else q.url + ) + rows.append( + [ + f"[{escape_cell(q.title)}]({target})", + format_label(q.type), + difficulty_label(q.difficulty) or "—", + _rounds(q), + _reported(q), + f"[Solve]({q.url})", + ] + ) + lines += [ + f"{plural(len(free), 'question')} reported at {escape_cell(name)} open without a paid plan" + + (" — the statement and hints are on each linked page here." if readable else ".") + + " Newest sighting first.", + "", + table(["Question", "Format", "Difficulty", "Round", "Reported", ""], + [":--", ":--", ":-:", ":--", ":--", ":--"], rows), + "", + ] + else: + lines += ["None of the questions reported here is on the free tier yet.", ""] + + if others: + lines += [f"## Guides", ""] + guide_rows = [] + for p in sorted(others, key=lambda p: p.guide.title.casefold()): + target = posixpath.relpath(p.path, f"companies/{key}") if p.path else p.guide.url + guide_rows.append( + [f"[{escape_cell(p.guide.title)}]({target})", escape_cell(", ".join(p.guide.tags)) or "—"] + ) + lines += [table(["Guide", "Tags"], [":--", ":--"], guide_rows), ""] + + lines += [ + "## Everything else", + "", + f"- [All {len(questions):,} questions reported at {escape_cell(name)}](../{key}.md) — the loop by round, " + "topics, what was asked in the last 90 days, and where to start.", + f"- [Practise every {escape_cell(name)} question on TrueInterview]({SITE}/problems/company/{key}).", + "", + footer(path), + ] + return "\n".join(lines) + + +def questions_index(publishable: Sequence[Question], registry: dict[str, str], api_labels: dict[str, str]) -> str: + """``questions/README.md``: every free question published here, by format, easiest first.""" + path = "questions/README.md" + lines = [ + GENERATED_NOTICE, + "", + "# Free interview questions", + "", + "Every free question in the TrueInterview bank, published here in full — the statement and the " + "hints. The reference solution, and an editor that runs your attempt against the hidden tests, are " + "one click away on each page.", + "", + "[← Question bank](../README.md) · [Companies](../companies/README.md) · " + "[Free questions, with statistics](../free/README.md)", + "", + ] + if not publishable: + lines += [ + "No question pages are published yet: the sync has not been given the free-content export. " + "[Every free question is on TrueInterview](../free/README.md) in the meantime.", + "", + footer(path), + ] + return "\n".join(lines) + order = {"easy": 0, "medium": 1, "hard": 2} + by_format: dict[str, list[Question]] = {} + for q in publishable: + by_format.setdefault(q.type, []).append(q) + for fmt in sorted(by_format, key=lambda f: (-len(by_format[f]), f)): + rows = sorted(by_format[fmt], key=lambda q: (order.get(q.difficulty or "", 3), q.title.casefold(), q.slug)) + lines += [f"## {format_label(fmt)} ({len(rows)})", ""] + lines += [ + table( + ["Question", "Difficulty", "Asked at"], + [":--", ":-:", ":--"], + [ + [ + f"[{escape_cell(q.title)}]({posixpath.relpath(question_path(registry, q), 'questions')})", + difficulty_label(q.difficulty) or "—", + " · ".join(escape_cell(n) for _k, n in _question_companies(q, api_labels)[:5]) or "—", + ] + for q in rows + ], + ), + "", + ] + lines.append(footer(path)) + return "\n".join(lines) + + +# ── the whole content layer ────────────────────────────────────────────────── + + +def render_content( + *, + questions: Sequence[Question], + guides: Sequence[Guide], + by_company: dict[str, tuple[str, list[Question]]], + content: Content | None, + registry: dict[str, str], + api_labels: dict[str, str], + today: date, +) -> tuple[dict[str, str], dict[str, str], dict[str, int]]: + """Every content page. Returns ``(files, registry, stats)``.""" + homes = frozenset(by_company) + bodies = content.questions if content else {} + + publishable = sorted( + (q for q in questions if q.slug in bodies and q.access_tier == "free"), + key=lambda q: (q.number, q.slug), + ) + registry = assign_paths( + registry, + [(f"question:{q.slug}", f"questions/{q.type}", _readable(q.slug, q.title)) for q in publishable], + ) + plans, registry = plan_guides(guides, homes, content, registry, api_labels) + + local: dict[str, str] = {} + for q in publishable: + local[f"/questions/{q.slug}"] = question_path(registry, q) + for plan in plans: + if plan.path: + # Both spellings: the site serves an article at /study/, and its + # own guides link to one another as /questions/, which redirects. + local[f"/study/{plan.guide.slug}"] = plan.path + local[f"/questions/{plan.guide.slug}"] = plan.path + + files: dict[str, str] = {} + for q in publishable: + body = bodies[q.slug] + path = question_path(registry, q) + files[path] = question_page(q, body.content_md, body.hints, path, local, homes, api_labels) + + plans_by_company: dict[str | None, list[GuidePlan]] = {} + for plan in plans: + plans_by_company.setdefault(plan.company, []).append(plan) + for plan in plans: + if plan.path and content: + key = plan.company + name = by_company[key][0] if key else "" + files[plan.path] = guide_page( + plan, content.articles[plan.guide.slug], name, key, local, plans_by_company.get(key, []) + ) + + for key, (name, rows) in by_company.items(): + files[f"companies/{key}/README.md"] = company_home( + key=key, + name=name, + questions=rows, + plans=plans_by_company.get(key, []), + content=content, + local=local, + registry=registry, + today=today, + ) + + files["questions/README.md"] = questions_index(publishable, registry, api_labels) + + stats = { + "question_pages": len(publishable), + "guide_pages": sum(1 for p in plans if p.path), + "dropped": content.dropped if content else 0, + } + return files, registry, stats diff --git a/scripts/render.py b/scripts/render.py index 5e521a38..14cc0cfb 100644 --- a/scripts/render.py +++ b/scripts/render.py @@ -464,7 +464,7 @@ def company_nav(companies: Sequence[tuple[str, str, int]]) -> str: def link(entry: tuple[str, str, int]) -> str: key, name, count = entry - return f"[{escape_cell(name)} ({count})](companies/{key}.md)" + return f"[{escape_cell(name)} ({count})](companies/{key}/README.md)" shown = companies[:README_TOP_COMPANIES] line = " · ".join(link(entry) for entry in shown) diff --git a/scripts/sync.py b/scripts/sync.py index 798aeb8e..2be55c83 100644 --- a/scripts/sync.py +++ b/scripts/sync.py @@ -54,8 +54,17 @@ "free", "experiences", "data", + "questions", ) +PATHS_FILE = ROOT / "data" / "paths.json" + +#: A content sync that would remove more than this share of the published +#: question pages stops instead. A question leaving the free tier is normal; a +#: fifth of them at once is an export that went wrong, and a removed page is a +#: broken link everywhere it was shared. +MAX_CONTENT_SHRINK = 0.2 + def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) @@ -129,7 +138,10 @@ def main() -> int: payload = fetch_catalog(args.base_url) catalog = load_catalog(payload) template = README_TEMPLATE.read_text(encoding="utf-8") - result = build(catalog, template, today) + paths = json.loads(PATHS_FILE.read_text(encoding="utf-8")) if PATHS_FILE.exists() else {} + if not isinstance(paths, dict): + raise ValueError("data/paths.json must be a JSON object") + result = build(catalog, template, today, paths) except (CatalogError, OSError, ValueError, json.JSONDecodeError) as error: print(f"sync failed: {error}", file=sys.stderr) return 2 @@ -147,7 +159,33 @@ def main() -> int: return 2 rendered = set(result.files) - stale = sorted(generated_paths() - rendered) + existing = generated_paths() + stale = sorted(existing - rendered) + + # The content layer's own guard. With no export configured the question + # pages are simply not rendered — which, over a repository that HAS them, + # would delete every one. That is a removed secret or a misconfigured run, + # never a decision, so it stops here and says what to do. + def question_pages(paths: set[str]) -> set[str]: + # `questions///README.md`, never the index, which every run renders. + return {p for p in paths if p.startswith("questions/") and p.count("/") == 3} + + published = question_pages(existing) + kept = question_pages(rendered) + if published and not result.stats["content_configured"]: + print( + f"sync failed: {len(published)} question pages are published but CONTENT_EXPORT_SECRET is not set, " + "so this run would delete them. Set the secret, or delete questions/ by hand if that is the intent.", + file=sys.stderr, + ) + return 2 + if published and len(published - kept) > MAX_CONTENT_SHRINK * len(published): + print( + f"sync failed: this run would remove {len(published - kept)} of {len(published)} question pages " + f"(more than {MAX_CONTENT_SHRINK:.0%}). Check the free-content export before letting it through.", + file=sys.stderr, + ) + return 2 changed = sorted( path for path, content in result.files.items() @@ -163,7 +201,12 @@ def main() -> int: f"{stats['months']} months · {stats['undated']:,} undated · " f"{stats['free']:,} free · {stats['window']:,} in the last {stats['window_days']}d · " f"{stats['experiences']:,} reports · " - f"{stats['files']} files · README {stats['readme_bytes']:,} B · " + + ( + f"{stats['content_question_pages']:,} question pages · {stats['content_guide_pages']:,} guide pages · " + if stats["content_configured"] + else "content export not configured · " + ) + + f"{stats['files']} files · README {stats['readme_bytes']:,} B · " f"largest page {largest_bytes:,} B ({largest_path})" ) @@ -175,6 +218,13 @@ def main() -> int: file=sys.stderr, ) + if stats["content_dropped"]: + print( + f"warning: {stats['content_dropped']} body/bodies from the free-content export were not rendered — " + "the public metadata does not list them as free (question) or published (article).", + file=sys.stderr, + ) + future_dated = stats["future_dated"] # type: ignore[index] if future_dated: shown = ", ".join(future_dated[:10]) + ("…" if len(future_dated) > 10 else "") diff --git a/scripts/test_content.py b/scripts/test_content.py new file mode 100644 index 00000000..c2b007a1 --- /dev/null +++ b/scripts/test_content.py @@ -0,0 +1,260 @@ +#!/usr/bin/env python3 +"""Offline tests for the content layer (``content.py``) and its two fences. + +The fixture carries no bodies, so every test here adds a small export to it — +the same shape ``/api/cron/content-export`` answers with — and renders the whole +repository from that. What each test defends is written beside it. + + python3 -m unittest discover scripts -v +""" + +from __future__ import annotations + +import io +import json +import os +import re +import sys +import unittest +from contextlib import redirect_stderr, redirect_stdout +from datetime import date +from pathlib import Path, PurePosixPath +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import sync # noqa: E402 +from build import build # noqa: E402 +from catalog import CatalogError, Guide, load_catalog # noqa: E402 +from content import MIN_GUIDE_CHARS, _process_role, assign_paths, rewrite_links, slugify # noqa: E402 + +ROOT = Path(__file__).resolve().parent.parent +FIXTURE = ROOT / "scripts" / "fixtures" / "catalog-sample.json" +TODAY = date(2026, 9, 11) +LONG = "A paragraph long enough to be a guide rather than a prompt. " * 20 + + +def payload() -> dict: + return json.loads(FIXTURE.read_text(encoding="utf-8")) + + +def free_and_paid(data: dict): + free = [q for q in data["questions"] if q["accessTier"] == "free" and q["companies"]] + paid = [q for q in data["questions"] if q["accessTier"] != "free"] + return free, paid + + +def with_content(data: dict | None = None, **overrides) -> tuple[dict, dict]: + """The fixture plus an export: two free questions, one paid body, two guides.""" + data = data or payload() + free, paid = free_and_paid(data) + guide = next(g for g in data["guides"] if g["companies"]) + short = next(g for g in data["guides"] if g["slug"] != guide["slug"] and g["companies"]) + content = { + "questions": [ + { + "slug": free[0]["slug"], + "type": free[0]["type"], + "contentMd": f"Solve it. See [the other one](/questions/{free[1]['slug']}) and " + f"[a paid one](/questions/{paid[0]['slug']}) and [the guide](/study/{guide['slug']}).", + "hints": ["First hint.", "Second hint."], + }, + {"slug": free[1]["slug"], "type": free[1]["type"], "contentMd": "## Problem\n\nThe second one.", "hints": []}, + # The site should never send this. The repository must not publish it if it does. + {"slug": paid[0]["slug"], "type": paid[0]["type"], "contentMd": "PAID BODY", "hints": []}, + ], + "articles": [ + {"slug": guide["slug"], "contentMd": LONG + f"\n\n[Practise](/questions/{free[0]['slug']})"}, + {"slug": short["slug"], "contentMd": "Too short to be a page."}, + ], + } + content.update(overrides) + data["content"] = content + return data, {"free": free, "paid": paid, "guide": guide, "short": short} + + +def render(data: dict, paths: dict | None = None): + template = (ROOT / "README.md").read_text(encoding="utf-8") + return build(load_catalog(data), template, TODAY, paths) + + +def question_pages(result) -> dict[str, str]: + return {p: c for p, c in result.files.items() if p.startswith("questions/") and p != "questions/README.md"} + + +class TestFences(unittest.TestCase): + def test_a_body_the_metadata_does_not_call_free_is_never_published(self): + data, rows = with_content() + catalog = load_catalog(data) + self.assertNotIn(rows["paid"][0]["slug"], catalog.content.questions) + self.assertEqual(catalog.content.dropped, 1) + result = render(data) + self.assertFalse(any("PAID BODY" in text for text in result.files.values())) + self.assertEqual(len(question_pages(result)), 2) + + def test_a_body_filed_under_a_different_format_is_dropped(self): + data, rows = with_content() + data["content"]["questions"][1]["type"] = "not-its-format" + self.assertEqual(load_catalog(data).content.dropped, 2) + + def test_a_malformed_export_stops_the_sync(self): + data, _ = with_content() + data["content"]["questions"].append({"slug": "x", "type": "algorithm", "contentMd": ""}) + with self.assertRaises(CatalogError): + load_catalog(data) + data["content"] = {"questions": "nope", "articles": []} + with self.assertRaises(CatalogError): + load_catalog(data) + + def test_no_export_is_not_an_empty_export(self): + data = payload() + self.assertIsNone(load_catalog(data).content) + result = render(data) + self.assertEqual(question_pages(result), {}) + self.assertFalse(result.stats["content_configured"]) + # Every company still gets a home, linking at the site. + self.assertTrue(any(p.endswith("/README.md") and p.startswith("companies/") and p.count("/") == 2 + for p in result.files)) + + +class TestQuestionPage(unittest.TestCase): + def setUp(self): + self.data, self.rows = with_content() + self.result = render(self.data) + + def page(self, row) -> str: + registry = json.loads(self.result.files["data/paths.json"]) + return self.result.files[registry[f"question:{row['slug']}"] + "/README.md"] + + def test_statement_and_hints_are_published_and_the_solution_is_not(self): + text = self.page(self.rows["free"][0]) + self.assertIn("Solve it.", text) + self.assertIn("Hint 2", text) + self.assertIn("It is not reproduced here", text) + self.assertIn(f"]({self.rows['free'][0]['url']})", text) + + def test_links_land_on_a_page_here_or_on_the_site(self): + text = self.page(self.rows["free"][0]) + registry = json.loads(self.result.files["data/paths.json"]) + here = registry[f"question:{self.rows['free'][0]['slug']}"] + other = registry[f"question:{self.rows['free'][1]['slug']}"] + self.assertIn(f"]({os.path.relpath(other + '/README.md', here)})", text) + self.assertIn(f"](https://trueinterview.io/questions/{self.rows['paid'][0]['slug']})", text) + self.assertNotRegex(text, r"\]\(/") + + def test_every_relative_link_resolves(self): + generated = set(self.result.files) + broken = [] + for path, contents in self.result.files.items(): + if not path.endswith(".md"): + continue + here = PurePosixPath(path).parent + for href in re.findall(r"\]\(([^)\s]+)\)", contents): + if href.startswith(("http://", "https://", "#", "../../issues", "../../../issues")): + continue + target = os.path.normpath(str(here / href.split("#")[0])) + if target not in generated and not (ROOT / target).exists(): + broken.append(f"{path} → {href}") + self.assertEqual(broken, []) + + def test_a_guide_gets_a_page_and_a_fragment_does_not(self): + pages = [p for p in self.result.files if "/guides/" in p and p.startswith("companies/")] + self.assertEqual(len(pages), 1) + text = self.result.files[pages[0]] + self.assertIn(LONG.strip()[:40], text) + self.assertLess(len("Too short to be a page."), MIN_GUIDE_CHARS) + self.assertFalse(any("Too short to be a page." in t for t in self.result.files.values())) + + +class TestPaths(unittest.TestCase): + def test_a_published_path_survives_a_title_change(self): + data, rows = with_content() + first = render(data) + registry = json.loads(first.files["data/paths.json"]) + slug = rows["free"][0]["slug"] + for q in data["questions"]: + if q["slug"] == slug: + q["title"] = "A completely different title" + second = render(data, registry) + self.assertEqual(json.loads(second.files["data/paths.json"])[f"question:{slug}"], registry[f"question:{slug}"]) + + def test_rendering_from_its_own_registry_is_a_no_op(self): + data, _ = with_content() + first = render(data) + second = render(data, json.loads(first.files["data/paths.json"])) + self.assertEqual(first.files, second.files) + + def test_collisions_and_retired_paths(self): + registry = assign_paths({"question:old": "questions/algorithm/two-sum"}, [ + ("question:a", "questions/algorithm", "two-sum"), + ("question:b", "questions/algorithm", "two-sum"), + ]) + # A retired question's path is never handed to a different one. + self.assertEqual(registry["question:a"], "questions/algorithm/two-sum-2") + self.assertEqual(registry["question:b"], "questions/algorithm/two-sum-3") + + def test_a_question_that_changes_format_moves(self): + registry = assign_paths({"question:a": "questions/algorithm/x"}, [("question:a", "questions/system-design", "x")]) + self.assertEqual(registry["question:a"], "questions/system-design/x") + + def test_slugify(self): + self.assertEqual(slugify("Design A Top-K System (v2) & More"), "design-a-top-k-system-v2-and-more") + self.assertEqual(slugify("???"), "untitled") + + +class TestProcessGuides(unittest.TestCase): + def guide(self, slug, companies): + return Guide(slug=slug, title=slug, companies=companies, tags=(), url="https://x", added_at=None) + + def test_the_stored_company_value_names_the_guide(self): + self.assertEqual(_process_role(self.guide("akunacapital-interview-process", ("akunacapital",))), ("process", None)) + self.assertEqual(_process_role(self.guide("akunacapital-interview-process", ("Akuna Capital",))), ("process", None)) + self.assertEqual(_process_role(self.guide("scale-ai-interview-process", ("scale.ai",))), ("process", None)) + self.assertEqual( + _process_role(self.guide("openai-software-engineer-interview-process", ("openai",))), + ("role", "software-engineer"), + ) + + def test_another_companys_guide_is_an_ordinary_guide(self): + self.assertIsNone(_process_role(self.guide("meta-interview-process", ("openai",)))) + self.assertIsNone(_process_role(self.guide("hm-bq-why-openai", ("openai",)))) + + +class TestRewrite(unittest.TestCase): + def test_reference_links_attributes_and_fragments(self): + local = {"/questions/a": "questions/algorithm/a/README.md"} + text = rewrite_links( + "[x](/questions/a#examples) [y](/pricing)\n[ref]: /questions/a\nz", + "companies/meta/README.md", + local, + ) + self.assertIn("[x](../../questions/algorithm/a/README.md#examples)", text) + self.assertIn("[y](https://trueinterview.io/pricing)", text) + self.assertIn("[ref]: ../../questions/algorithm/a/README.md", text) + self.assertIn('href="../../questions/algorithm/a/README.md"', text) + + +class TestSyncGuard(unittest.TestCase): + def run_sync(self, *published: str) -> int: + argv = ["sync.py", "--catalog-file", str(FIXTURE), "--today", TODAY.isoformat(), "--check"] + with mock.patch.object(sys, "argv", argv), mock.patch.object( + sync, "generated_paths", return_value=set(published) + ), mock.patch.object(sync, "PATHS_FILE", ROOT / "does-not-exist.json"), redirect_stdout( + io.StringIO() + ), redirect_stderr(io.StringIO()) as err: + code = sync.main() + self.stderr = err.getvalue() + return code + + def test_an_unconfigured_run_never_deletes_published_question_pages(self): + self.assertEqual(self.run_sync("questions/algorithm/x/README.md"), 2) + self.assertIn("CONTENT_EXPORT_SECRET", self.stderr) + + def test_an_unconfigured_run_over_no_pages_is_fine(self): + # The index is always rendered, so it must not count as a published page. + self.assertNotEqual(self.run_sync(), 2) + self.assertNotEqual(self.run_sync("questions/README.md"), 2) + + +if __name__ == "__main__": + unittest.main()