mirror of
https://github.com/prdlk/leetcode.git
synced 2026-11-02 13:12:44 +00:00
Compare commits
21
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
51ce47a49a | ||
|
|
4650b33364 | ||
|
|
804ad1379e | ||
|
|
0d845838c2 | ||
|
|
b7041b1440 | ||
|
|
5655cede21 | ||
|
|
025ce82041 | ||
|
|
a3657732f6 | ||
|
|
1622bf39b7 | ||
|
|
5ea123e46d | ||
|
|
38fbb18f32 | ||
|
|
7e46fceb1c | ||
|
|
b21ab75e0e | ||
|
|
d784575c87 | ||
|
|
70f88122e0 | ||
|
|
47c2b20646 | ||
|
|
e8b0d4dc30 | ||
|
|
bd9afc6ea1 | ||
|
|
8396c4a7ed | ||
|
|
bf4a1f4c7a | ||
|
|
e23a68c91c |
No files matched your search
@@ -0,0 +1,54 @@
|
||||
name: Spaced Repetition
|
||||
|
||||
# Opens (or refreshes) today's `Spaced Repetition — <Month D, YYYY>` issue from
|
||||
# whatever the SRS ladder has due (`POST /admin/due`, the same rows the 8 AM
|
||||
# digest mails — so the two cannot disagree). The script stores nothing and
|
||||
# schedules nothing: it asks D1 what is standing today, keyed by the ET date in
|
||||
# the title, so a re-run rewrites one body instead of stacking duplicates.
|
||||
# Sunday is the rest day and the ladder never books it, so nothing is written.
|
||||
|
||||
on:
|
||||
schedule:
|
||||
# 10:00 UTC = 06:00 ET while the campaign runs (EDT through Nov 1), 05:00 ET
|
||||
# after. No DST guard and no second cron: the issue is keyed by ET calendar
|
||||
# date, not by the hour it was created, so the drift is cosmetic.
|
||||
- cron: "0 10 * * *"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
dry_run:
|
||||
description: Print the issue body without creating or updating anything
|
||||
type: boolean
|
||||
default: false
|
||||
date:
|
||||
description: ET date to treat as today (YYYY-MM-DD) — backfill a missed day
|
||||
type: string
|
||||
default: ""
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
|
||||
concurrency:
|
||||
group: spaced-repetition
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
drill:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: oven-sh/setup-bun@v2
|
||||
|
||||
# No install step: the script only uses Bun builtins + fetch.
|
||||
#
|
||||
# SRS_ADMIN_KEY reads today's due list from the Worker. Unset is fatal
|
||||
# here, unlike in close-solved: without D1 there is no schedule to render,
|
||||
# and inventing one from issue close dates is exactly the second source of
|
||||
# truth this replaced.
|
||||
- run: bun apps/cli/spaced-repetition.ts
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
DRY_RUN: ${{ inputs.dry_run }}
|
||||
SRS_TODAY: ${{ inputs.date }}
|
||||
SRS_ADMIN_KEY: ${{ secrets.SRS_ADMIN_KEY }}
|
||||
@@ -1,6 +1,8 @@
|
||||
# dependencies (bun install)
|
||||
node_modules
|
||||
tmp/
|
||||
*.log
|
||||
.crush
|
||||
|
||||
# output
|
||||
out
|
||||
|
||||
@@ -21,11 +21,15 @@ flowchart LR
|
||||
D1 -->|best-effort mirror: Target Date only| Proj[GitHub Project fields]
|
||||
GH -->|close-solved.yml sync-project-fields| Proj
|
||||
D1 -->|Sat midnight ET| Review[Review — Week N issue]
|
||||
PI -->|"spaced-repetition.yml (6 AM ET cron, closed +3d/+7d)"| SR[Spaced Repetition — Month D issue]
|
||||
D1 --> Charts[SVG charts + /api/stats]
|
||||
```
|
||||
|
||||
- **Reconcile, don't react.** `close-solved.ts`, `close-topics.ts`, and the Worker's catalog sync recompute desired state from scratch each run: re-runs are no-ops, backfills need no special casing, closing is one-directional. `close-solved` posts its *whole* implemented set to `/admin/solved`, not just the issues it closed this run.
|
||||
- **Solving has three doors, one write path.** A digest one-tap, a `/done` comment, and a solution landing in `work/` all end in `logAttempt()`. Closing an issue is *not* one of them: the catalog reconcile never reads issue state, so a `work/` push that skipped the email would otherwise leave `stage='new'` — invisible to the charts, the digest's solved ticks, and the drill/gate pools. Hence `/admin/solved` (`source='commit'`, first solve only, no index needed for idempotency: it refuses any problem past stage `new`). `close-topics` needs no such call — D1 stores no topic completion, only problem rows.
|
||||
- **Solving has three doors, one write path.** A digest one-tap, a `/done` comment, and a solution landing in `work/` all end in `logAttempt()`. Closing an issue is *not* one of them: the catalog reconcile never reads issue state, so a `work/` push that skipped the email would otherwise leave `stage='new'` — invisible to the charts, the digest's solved ticks, and the drill/gate pools. Hence `/admin/solved`, which takes `{lc, bucket}` pairs (`source='commit'`): the bucket names the rung the file settles — `work/1` settles `new`, `work/3` settles `+3`, `work/7` settles `+7` — so a pushed re-solve advances the ladder instead of vanishing, and re-posting the whole implemented set writes nothing because the rung named has already been left behind. That stage check is the entire idempotency mechanism; no index, no dedupe table, no state file. `close-topics` needs no such call — D1 stores no topic completion, only problem rows.
|
||||
- **The rest day is structural, not cosmetic.** Sunday is never booked: topics run Mon–Fri (`apps/api/data/schedule.json`), the gate is Saturday, and the ladder's windows are 3 and 7 precisely because those return a solve to a working day. Every scheduled date — ladder review, levelled overflow, deferred-Hard release, review-issue window — comes out of `workingDay()` in `apps/api/src/srs.ts`, which slides the one exception (a Thursday solve's `+3`) forward to Monday. Forward, never back: a review may slip later than its interval, never shorten it. Never mint a scheduled date with bare `addDays()`, and never "fix" a Sunday landing downstream — the digest's Sunday rest branch is a courtesy, not the mechanism. `apps/api/src/srs.test.ts` sweeps the campaign calendar to keep this honest.
|
||||
- **One schedule, one answer to "what is open today".** D1's ladder IS the schedule; `dueToday()` (`POST /admin/due`) is its read side and `DUE_WHERE` is the single SQL definition of "due", shared by the digest, the review issue and the docs queue chart. `spaced-repetition.yml` renders that answer into today's `Spaced Repetition — <Month D, YYYY>` issue — grouped by rung, `WINDOW_CAP` (3) required per rung with the overflow listed as optional, keyed by the ET date in the title so a re-run rewrites one body. It schedules nothing, stores nothing, and writes nothing on Sunday. Without `SRS_ADMIN_KEY` it FAILS rather than inventing a second schedule from issue close dates — that reconstruction was the drift, and it is gone. NEVER add a JSON state file (`.github/problems.json` and friends) or a second "when is this due" rule: D1 answers it, with one writer (`logAttempt`) and git-free history in `attempts`.
|
||||
- **The picker owns the local review loop; the buckets are its state.** `work/` holds three buckets (`1` = first solve, `3`/`7` = blind re-solves, named after the ladder rungs) and `bun run pick` has three sections — Tab cycles them. Pools are reconciled from the filesystem plus one `git log` (`apps/cli/work.ts`): a first solve dates from the ET date of the commit that added its `work/1` file — the same push that closes the problem issue and starts the +3/+7 windows — and a window stops being owed the moment its bucket holds a file. Uncapped, unlike the review issue's `WINDOW_CAP`: that issue is one day's assignment, the picker is everything still owed. An empty scaffold under `work/1` owes nothing (it is unsolved), which is why `isImplemented()` lives in `apps/cli/source.ts` and is shared with `close-solved.ts`. leetcode-cli reads its output directory from `~/.leetcode/workspaces/<active>/config.json` and nowhere else — no flag, no env var — so `pick.ts` MERGES `workDir` into that file around the child (never replays saved bytes: the CLI owns the file too) and leaves it pointed at `work/1`, then treats the scaffold's existence as the acceptance test, since leetcode-cli exits 0 even when an expired session made it write nothing. The picker itself writes no state: pushing the re-solve is what moves the ladder, via `close-solved` → `/admin/solved` with that file's bucket.
|
||||
- **The README charts are live, never committed.** They are Worker endpoints reading D1 per request (`Cache-Control: max-age=300`, honored by GitHub Camo), so a solved push moves them within ~5 minutes with no commit and no workflow of their own.
|
||||
- **D1 owns SRS state; GitHub issues own the catalog; `apps/api/data/schedule.json` owns the calendar.** The catalog reconcile never invents rows and never overwrites SRS columns (`stage`, `next_review`). `Target Date` is the *only* Project field the Worker mirrors (`apps/api/src/mirror.ts`): failures are warnings, never lost D1 writes; topic rows' `Target Date` is never written. SRS stage and first-attempt result live **only** in D1 — do not re-add them as Project fields. The Project's `Set`/`Difficulty` single-selects are a projection of the issue labels, reconciled by `bun run sync-project-fields` — a best-effort final step of `close-solved.yml`, never the Worker.
|
||||
- **Determinism = idempotency.** Drill/gate sampling uses a seeded PRNG (`rng()` in `apps/api/src/srs.ts`, FNV-1a → mulberry32, seed = date / ISO week); the digest is keyed by ET date in `email_log`; one-tap links are unique on (problem, date, kind).
|
||||
@@ -36,25 +40,27 @@ flowchart LR
|
||||
|
||||
| Path | Purpose |
|
||||
|---|---|
|
||||
| `work/<Difficulty>/<Category>/<num>.<slug>.{js,py}` | Solutions, e.g. `work/Easy/Array/1.two-sum.py`. Machine-parsed header comment (title / `Difficulty:` / URL / `─` rule / statement) — preserve its exact shape |
|
||||
| `work/<1\|3\|7>/<Difficulty>/<Category>/<num>.<slug>.{js,py}` | Solutions, e.g. `work/1/Easy/Array/1.two-sum.py`. The top directory is the spaced-repetition bucket: `1` = first solve, `3`/`7` = the blind re-solves of that problem 3 and 7 days later. Machine-parsed header comment (title / `Difficulty:` / URL / `─` rule / statement) — preserve its exact shape |
|
||||
| `apps/cli/` | Flat Bun TS workspace: automation entries (shebang + top-level await) and libraries (no shebang, side-effect-free on import). Root `bun run` scripts delegate here |
|
||||
| `apps/docs/` | Blume site (`blume.config.ts`, `content/`, `islands/`, `public/`). `content/(<category>)/<num>-<slug>.mdx` generated by sync |
|
||||
| `apps/api/` | Cloudflare Worker workspace: `src/` modules, `data/schedule.json` (day → topic issue, human-edited, bundled at deploy), `migrations/`, `scripts/import-srs.ts` |
|
||||
| `.github/workflows/` | deploy (docs → Pages, Worker → Cloudflare, on every main push), close-solved (issues + `/admin/solved` + Project `Set`/`Difficulty`, needs `SRS_ADMIN_KEY` and `PROJECT_PAT`), close-topics, sync-d1 (issue edits → `/admin/reconcile`) |
|
||||
| `apps/api/` | Cloudflare Worker workspace: `src/` modules, `data/schedule.json` (day → topic issue, human-edited, bundled at deploy), `migrations/` (append-only; `0002` is the +3/+7 ladder rebuild) |
|
||||
| `.github/workflows/` | deploy (docs → Pages, Worker → Cloudflare, on every main push), close-solved (issues + `/admin/solved` + Project `Set`/`Difficulty`, needs `SRS_ADMIN_KEY` and `PROJECT_PAT`), close-topics, sync-d1 (issue edits → `/admin/reconcile`), spaced-repetition (daily 06:00 ET cron → today's review issue; `GITHUB_TOKEN` only, no secrets) |
|
||||
|
||||
## Development Commands
|
||||
|
||||
All from the repo root (a Bun workspace over `apps/*`):
|
||||
|
||||
```sh
|
||||
bun run pick # scaffold a solution via leetcode-cli (fuzzy picker; hides problems
|
||||
# already under work/, caches index+descriptions in
|
||||
bun run pick # scaffold a solution via leetcode-cli (fuzzy picker; Tab cycles the
|
||||
# sections: new problems → work/1, then the owed 3-day and 7-day
|
||||
# re-solves → work/3, work/7. Each section hides what its own bucket
|
||||
# already holds; index+descriptions cached in
|
||||
# ~/.local/share/leetcode/data.db — see apps/cli/db.ts)
|
||||
bun run test # run ONE solution against LeetCode's judge (not a test suite;
|
||||
# most recently tested first, stamped in the db on exit 0)
|
||||
bun run submit # submit ONE solution to LeetCode (newest scaffold first, nothing
|
||||
# hidden; last_submitted stamped in the db on exit 0)
|
||||
bun run sync # work/ → apps/docs/content/ pages
|
||||
bun run sync # work/1 → apps/docs/content/ pages (re-solves are never published)
|
||||
bun run dev|build # Blume docs site (runs in apps/docs/)
|
||||
bun run close-solved -- --dry-run # issue reconcilers (also DRY_RUN=1)
|
||||
bun run close-topics -- --dry-run
|
||||
@@ -64,7 +70,11 @@ SRS_API=http://localhost:8787 SRS_ADMIN_KEY=$LINK_KEY bun run close-solved -- --
|
||||
# Project Set/Difficulty from the issue labels (needs a `project`-scoped token;
|
||||
# runs as the last step of close-solved.yml in CI):
|
||||
GH_TOKEN=$PROJECT_PAT bun run sync-project-fields -- --dry-run
|
||||
bun run api:dev # wrangler dev on :8787 (local D1); api:test = DST guard tests
|
||||
# today's review issue from the +3d/+7d closes (--date backfills a missed day;
|
||||
# a Sunday date writes nothing — the rest day has no assignment):
|
||||
bun run spaced-repetition -- --dry-run --date=2026-08-31
|
||||
bun run api:dev # wrangler dev on :8787 (local D1)
|
||||
bun run api:test # DST guards + the rest-day calendar sweep
|
||||
bun run api:deploy # deploy the Worker by hand (CI also deploys on main pushes)
|
||||
curl -X POST -H "Authorization: Bearer $LINK_KEY" \
|
||||
"localhost:8787/admin/digest?dry=1&date=2026-08-30" # preview a digest, send nothing
|
||||
@@ -78,18 +88,19 @@ curl -X POST -H "Authorization: Bearer $LINK_KEY" \
|
||||
- **Dry-run everything:** reconcilers take `--dry-run`/`DRY_RUN=1`; Worker admin routes take `?dry=1&force=1&date=` (the `SRS_TODAY` equivalent) and `wrangler dev` runs against local D1 — exercise logic there before touching production state.
|
||||
- **Dates:** always ET calendar strings (`YYYY-MM-DD`), arithmetic anchored at noon UTC (`atNoon` in `apps/api/src/srs.ts`) to dodge DST. Never `new Date()` math directly.
|
||||
- **Style:** section-divider comments (`// ── name ───`), file-top doc comments explaining the *why* and invariants, 2-space JSON with trailing newline, `Map` for dynamic keys / `Record` for static tables, no tiny one-expression wrapper functions.
|
||||
- **Known intentional duplication:** `close-solved.ts` re-implements header stripping instead of importing from `sync.ts` because `sync.ts` runs its pipeline on import. Don't "deduplicate" it.
|
||||
- **Known intentional duplication:** `sync.ts` keeps its own header split instead of sharing `apps/cli/source.ts`, because `sync.ts` runs its whole pipeline on import and so cannot be imported from. Don't "deduplicate" it. `close-solved.ts` and `work.ts` do share it — the stub test decides both "close the issue" and "owes a review", and the two must never disagree.
|
||||
|
||||
## Important Files
|
||||
|
||||
- `apps/api/src/srs.ts` — SRS domain: ladder (`new → +2 → +5 → +10 → retired`; fail resets to `+2`; first-ever log enters at `+2`), ET date math, seeded sampling, `logAttempt()` (the ONE write path — email taps, webhook, gate scoring all converge here), and overload leveling: at most `REVIEW_CAP` (3) reviews surface per day — `levelReviews()` (run by `sendDigest` on real sends only, never dry) gives everything past the cap a concrete future date, ≤ 3 per day, oldest first, instead of letting the due pile grow.
|
||||
- `apps/api/src/srs.ts` — SRS domain: the ladder (`new → +3 → +7 → retired`; fail resets to `+3`; first-ever log enters at `+3`), `WINDOWS`/`STAGES` (the one vocabulary shared by the charts, the `work/<n>` buckets and the review issues), ET date math, `workingDay()` (no scheduled date is ever a Sunday), seeded sampling, `logAttempt()` (the ONE write path — email taps, webhook, gate scoring all converge here), and overload leveling: at most `REVIEW_CAP` (3) reviews surface per day — `levelReviews()` (run by `sendDigest` on real sends only, never dry) gives everything past the cap a concrete future WORKING day, ≤ 3 per day, oldest first, instead of letting the due pile grow.
|
||||
- `apps/api/src/index.ts` — router + cron dispatch; `apps/api/wrangler.jsonc` — bindings (`DB`, `EMAIL`), crons, vars; secrets `GH_PAT`/`WEBHOOK_SECRET`/`LINK_KEY` via `wrangler secret put`.
|
||||
- `apps/api/src/digest.ts` / `apps/api/src/email.tsx` — the daily digest, split data/presentation. `digest.ts` reads D1 into a `DigestData`; `email.tsx` owns every colour and every sentence, and renders both the HTML and (via its own `plainDigest`, not React Email's `plainText` mode, which flattens the tables) the text alternative. The retrieval rules hold by construction: `DigestRow` has no title and no issue field, so a review or drill line *cannot* leak the topic or a solution link. Subject is `(Day N/56) LeetCode Daily Digest`.
|
||||
- `apps/api/src/png.ts` — hand-rolled PNG encoder (RGB8, one IDAT, zlib via `CompressionStream("deflate")`, CRC32, 5×7 bitmap font). It exists because every major email client refuses remote SVG, so `/chart/heatmap.png` rasters the heatmap for the digest while `/chart/heatmap.svg` keeps serving the README byte-for-byte. Both come from one `heatmapCells()` so the two pictures cannot drift.
|
||||
- `apps/cli/sync.ts` — work→docs contract: only `## Solution` onward is script-owned on existing pages; human prose is never touched; never hand-write solution pages or edit inside `## Solution`.
|
||||
- `apps/cli/work.ts` — the `work/` layout: bucket paths, `firstSolved()` (one `git log`, ET dates, keyed by LC number so past layout moves don't matter), and `reviewQueues()` (what each window still owes). Everything that needs to know where a solution file lives, or when it was solved, goes through here.
|
||||
- `README.md` live charts are Worker endpoints (`/chart/*.svg`, `/badge/gate.svg`, 5-min Camo cache); the docs `/progress` page fetches `/api/stats` client-side (`apps/docs/islands/ProgressDashboard.tsx`).
|
||||
- `apps/docs/blume.config.ts` — site base `/leetcode`; `README.md` campaign table doubles as topic-map input to `sync.ts` (`readmeTopics()`, `TOPIC_ALIASES`).
|
||||
- Old `.github/srs/` JSON state and the `srs-*` Actions are RETIRED — do not resurrect; `apps/api/scripts/import-srs.ts` documents the migration.
|
||||
- Old `.github/srs/` JSON state, its `srs-*` Actions, and the one-shot `import-srs.ts` importer are RETIRED and deleted — do not resurrect; git history is the record.
|
||||
|
||||
## Runtime/Tooling Preferences
|
||||
|
||||
|
||||
@@ -10,6 +10,8 @@
|
||||
|
||||
<p align="center">
|
||||
<sub>8-week interview-prep fight camp. Each phase is a milestone; each topic an issue; each problem a sub-issue.<br>
|
||||
New topic Mon–Fri, gate on Saturday, Sunday off — every solve comes back at <strong>+3</strong> and <strong>+7</strong> days,
|
||||
the two windows that keep the rest day clear (a Thursday solve's +3 slides to Monday).<br>
|
||||
Charts are live from the SRS Worker, never committed: pushing a solution or tapping the daily digest moves them within ~5 min.</sub>
|
||||
</p>
|
||||
|
||||
@@ -18,7 +20,7 @@
|
||||
<td colspan="2" align="center"><img alt="phase progress" width="100%" src="https://srs-api.prdlk.workers.dev/chart/progress.svg" /></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center" width="53%"><img alt="SRS ladder" width="100%" src="https://srs-api.prdlk.workers.dev/chart/ladder.svg" /></td>
|
||||
<td align="center" width="53%"><img alt="SRS ladder — new / +3 / +7 / retired" width="100%" src="https://srs-api.prdlk.workers.dev/chart/ladder.svg" /></td>
|
||||
<td align="center" width="47%"><img alt="attempt heatmap" width="100%" src="https://srs-api.prdlk.workers.dev/chart/heatmap.svg" /></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
+42
-19
@@ -26,10 +26,23 @@ Live at `https://srs-api.prdlk.workers.dev`.
|
||||
|
||||
## The ladder
|
||||
|
||||
`new → +2 → +5 → +10 → retired`; pass advances, fail resets to `+2`.
|
||||
A problem's first-ever log enters at `+2` regardless of result. Stage names
|
||||
the NEXT review's interval. All dates are ET calendar strings anchored at
|
||||
noon UTC (`src/srs.ts`) — never raw `Date` math.
|
||||
`new → +3 → +7 → retired`; pass advances, fail resets to `+3`. A problem's
|
||||
first-ever log enters at `+3` regardless of result. Stage names the NEXT
|
||||
review's interval, and the two rungs are the same numbers as the `work/3` and
|
||||
`work/7` buckets `bun run pick` scaffolds re-solves into.
|
||||
|
||||
**Sunday is never booked.** Topics run Mon–Fri, the gate is Saturday, and 3/7
|
||||
are chosen so a solve returns on a working day: only a Thursday solve's `+3`
|
||||
would land on the rest day, and `workingDay()` in `src/srs.ts` slides it to
|
||||
Monday. Every scheduled date in the Worker — ladder reviews, levelled
|
||||
overflow, deferred-Hard release dates — is minted by that one function, so the
|
||||
rest day cannot be booked and then swallowed by the digest's Sunday branch.
|
||||
Reviews may slip later, never earlier: pulling one back to Saturday would
|
||||
shorten the interval it exists to test. `src/srs.test.ts` sweeps the whole
|
||||
campaign calendar to prove it.
|
||||
|
||||
All dates are ET calendar strings anchored at noon UTC (`src/srs.ts`) — never
|
||||
raw `Date` math.
|
||||
|
||||
Blind drills draw only from topics **already learned**: scheduled in an
|
||||
earlier week (the current week's optional pool is reserved for Saturday's
|
||||
@@ -44,7 +57,8 @@ day never feeds drills just because its calendar week lapsed.
|
||||
| `POST /webhook/github` | HMAC (`WEBHOOK_SECRET`) | `/done <n> pass\|fail` comments (owner only, any issue); `review`-issue close → gate scoring |
|
||||
| `GET /chart/{progress,ladder,heatmap}.svg`, `GET /badge/gate.svg` | public | hand-rolled SVGs, `max-age=300` (GitHub Camo's freshness floor) |
|
||||
| `GET /api/stats` | public, CORS-pinned to the docs origin | one JSON document for `/progress` |
|
||||
| `POST /admin/solved` | `Authorization: Bearer <LINK_KEY>` | `{"lc":[…]}` — solutions committed under `work/`; logs each *first* solve (`source='commit'`), skips anything past stage `new`, takes `?dry=1&date=` |
|
||||
| `POST /admin/solved` | `Authorization: Bearer <LINK_KEY>` | `{"solved":[{"lc":1,"bucket":1},…]}` — solutions committed under `work/`; the bucket names the rung it settles (1 → `new`, 3 → `+3`, 7 → `+7`), so a first solve enters the ladder and a pushed re-solve advances it. Writes only when the problem stands on that rung, which is what makes re-posting the whole set a no-op. Takes `?dry=1&date=` |
|
||||
| `POST /admin/due` | `Authorization: Bearer <LINK_KEY>` | read-only: what the ladder has due on `?date=` (default today), oldest first, with the rung/bucket, how late it is, and when it was last seen. The one answer behind the daily `Spaced Repetition` issue |
|
||||
| `POST /admin/{digest,review,reconcile}` | `Authorization: Bearer <LINK_KEY>` | manual triggers; `digest` takes `?dry=1&force=1&date=` |
|
||||
|
||||
## Crons (DST-proof)
|
||||
@@ -64,15 +78,23 @@ routes). Bindings in `wrangler.jsonc`: `DB` (D1 `srs`), `EMAIL`
|
||||
(`send_email`, restricted to the verified destination). Sender domain
|
||||
`prdlk.com` is onboarded to Email Sending.
|
||||
|
||||
Two Actions workflows push into D1 with the `SRS_ADMIN_KEY` repo secret:
|
||||
`sync-d1.yml` sends curriculum issue edits to `POST /admin/reconcile`
|
||||
(the morning cron is the backstop), and `close-solved.yml` sends the whole
|
||||
implemented `work/` set to `POST /admin/solved` on every push to `main`.
|
||||
That second call is what keeps a committed solution from being invisible
|
||||
here: closing its issue is not a state change the Worker can see — the
|
||||
catalog reconcile ignores issue state, and only `logAttempt()` moves the
|
||||
ladder. `close-solved` still owns the issue close itself (it knows the files
|
||||
and the commit), so this path only writes D1 and mirrors Project fields.
|
||||
Three Actions workflows talk to this Worker with the `SRS_ADMIN_KEY` repo
|
||||
secret:
|
||||
|
||||
- `sync-d1.yml` sends curriculum issue edits to `POST /admin/reconcile` (the
|
||||
morning cron is the backstop).
|
||||
- `close-solved.yml` sends the whole implemented `work/` set — each entry
|
||||
tagged with its bucket — to `POST /admin/solved` on every push to `main`.
|
||||
That call is what keeps a committed solution from being invisible here:
|
||||
closing an issue is not a state change the Worker can see (the catalog
|
||||
reconcile ignores issue state, and only `logAttempt()` moves the ladder), and
|
||||
the bucket is what lets a pushed re-solve advance `+3 → +7` instead of
|
||||
being read as a stale first solve. `close-solved` still owns the issue close
|
||||
itself (it knows the files and the commit), so this path only writes D1 and
|
||||
mirrors Project fields.
|
||||
- `spaced-repetition.yml` reads `POST /admin/due` at 06:00 ET and renders
|
||||
today's `Spaced Repetition` issue. Read-only, and the only schedule involved
|
||||
is this Worker's ladder.
|
||||
|
||||
## Local dev
|
||||
|
||||
@@ -83,13 +105,14 @@ bunx wrangler d1 migrations apply srs --local
|
||||
bun run dev # wrangler dev on :8787, local D1
|
||||
curl -X POST -H "Authorization: Bearer $LINK_KEY" \
|
||||
"localhost:8787/admin/digest?dry=1&date=2026-08-31" # prints HTML, sends nothing
|
||||
bun test src # DST guard + date math
|
||||
bun test src # DST guards, date math, the rest-day sweep
|
||||
```
|
||||
|
||||
`?date=` on admin routes is the `SRS_TODAY` equivalent. The one-shot
|
||||
migration from the retired `.github/srs/srs.json` lives at
|
||||
`scripts/import-srs.ts` (`--remote` for production D1); it is re-runnable —
|
||||
import-sourced attempts are wiped and re-inserted.
|
||||
`?date=` on admin routes is the `SRS_TODAY` equivalent. Migrations are
|
||||
append-only and applied in order; `0002_ladder_3_7.sql` is the +2/+5/+10 →
|
||||
`+3`/`+7` rebuild, which also lifts every date that was sitting on a Sunday.
|
||||
The one-shot importer for the retired `.github/srs/srs.json` is gone — that
|
||||
state no longer exists, and git history is its record.
|
||||
|
||||
## Deploy
|
||||
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
-- Ladder rebuild: +2/+5/+10 → +3/+7, and no scheduled date on a Sunday.
|
||||
--
|
||||
-- The old three rungs scattered reviews across every weekday, so roughly one
|
||||
-- review in seven came due on the rest day: the digest hid it (Sunday builds
|
||||
-- an empty body) and Monday inherited the pile. The campaign's windows are 3
|
||||
-- and 7 days — the same numbers as the work/3 and work/7 buckets and the
|
||||
-- Spaced Repetition issue windows — and srs.ts now mints every date through
|
||||
-- workingDay(), which never returns a Sunday.
|
||||
--
|
||||
-- Stage remap keeps earned progress: a problem at +5 has passed one review, so
|
||||
-- it owes the 7-day one; a problem at +10 has passed two and is done. Existing
|
||||
-- next_review dates keep their day (recomputing them would move work the
|
||||
-- reader has already been told about) — only Sunday landings shift, forward to
|
||||
-- Monday, because a review may come later than its interval but never sooner.
|
||||
--
|
||||
-- problems.stage is now: new | +3 | +7 | retired
|
||||
|
||||
UPDATE problems SET stage = '+3' WHERE stage = '+2';
|
||||
UPDATE problems SET stage = '+7' WHERE stage = '+5';
|
||||
UPDATE problems SET stage = 'retired', next_review = NULL WHERE stage = '+10';
|
||||
|
||||
UPDATE problems
|
||||
SET next_review = date(next_review, '+1 day')
|
||||
WHERE next_review IS NOT NULL AND strftime('%w', next_review) = '0';
|
||||
|
||||
-- defer_until is the deferred Hards' release date; catalog.ts spreads them two
|
||||
-- per working day, so the same rule applies. next_review tracks it for a row
|
||||
-- that is still `new`, and the shift above kept the two in step.
|
||||
UPDATE problems
|
||||
SET defer_until = date(defer_until, '+1 day')
|
||||
WHERE defer_until IS NOT NULL AND strftime('%w', defer_until) = '0';
|
||||
@@ -1,94 +0,0 @@
|
||||
#!/usr/bin/env bun
|
||||
/**
|
||||
* One-shot migration: .github/srs/srs.json → D1.
|
||||
*
|
||||
* Run AFTER the catalog reconcile has filled `problems` (the import only
|
||||
* overlays SRS-owned fields — stage, next_review, defer_until — and inserts
|
||||
* attempts/topic counters). Re-runnable without duplicates: import-sourced
|
||||
* attempts are wiped and re-inserted, everything else upserts.
|
||||
*
|
||||
* bun apps/api/scripts/import-srs.ts # local D1 (wrangler dev state)
|
||||
* bun apps/api/scripts/import-srs.ts --remote # production D1
|
||||
*
|
||||
* Prints row counts; verify them against srs.json before deleting anything.
|
||||
*/
|
||||
import { $ } from "bun";
|
||||
import { join } from "node:path";
|
||||
|
||||
const ROOT = join(import.meta.dir, "..", "..");
|
||||
const API = join(ROOT, "api");
|
||||
const REMOTE = process.argv.includes("--remote");
|
||||
|
||||
interface Attempt {
|
||||
date: string;
|
||||
kind: string;
|
||||
result: string;
|
||||
}
|
||||
interface Problem {
|
||||
issue: number;
|
||||
topic: number;
|
||||
difficulty: string;
|
||||
set: string;
|
||||
solved_on?: string;
|
||||
stage: string;
|
||||
next_review?: string;
|
||||
defer_until?: string;
|
||||
history: Attempt[];
|
||||
}
|
||||
interface State {
|
||||
problems: Record<string, Problem>;
|
||||
topics: Record<string, { misses: number; boost: boolean }>;
|
||||
drill_pool_used: number[];
|
||||
}
|
||||
|
||||
const state: State = JSON.parse(
|
||||
await Bun.file(join(ROOT, ".github", "srs", "srs.json")).text(),
|
||||
);
|
||||
|
||||
const q = (v: string | null | undefined) => (v == null ? "NULL" : `'${v}'`);
|
||||
const lines: string[] = ["DELETE FROM attempts WHERE source = 'import';"];
|
||||
|
||||
let attempts = 0;
|
||||
for (const [lc, p] of Object.entries(state.problems)) {
|
||||
lines.push(
|
||||
`UPDATE problems SET stage = ${q(p.stage)}, next_review = ${q(p.next_review ?? null)}, ` +
|
||||
`defer_until = ${q(p.defer_until ?? null)} WHERE lc_number = ${Number(lc)};`,
|
||||
);
|
||||
for (const a of p.history) {
|
||||
lines.push(
|
||||
`INSERT INTO attempts (lc_number, date, kind, result, source) ` +
|
||||
`VALUES (${Number(lc)}, ${q(a.date)}, ${q(a.kind)}, ${q(a.result)}, 'import');`,
|
||||
);
|
||||
attempts++;
|
||||
}
|
||||
}
|
||||
for (const [topic, t] of Object.entries(state.topics)) {
|
||||
lines.push(
|
||||
`UPDATE topics SET misses = ${t.misses}, boost = ${t.boost ? 1 : 0} WHERE issue = ${Number(topic)};`,
|
||||
);
|
||||
}
|
||||
for (const lc of state.drill_pool_used) {
|
||||
lines.push(`INSERT OR IGNORE INTO drill_pool_used (lc_number) VALUES (${lc});`);
|
||||
}
|
||||
|
||||
const sqlPath = join(API, "migrations", ".import.sql");
|
||||
await Bun.write(sqlPath, lines.join("\n") + "\n");
|
||||
const flag = REMOTE ? "--remote" : "--local";
|
||||
await $`bunx wrangler d1 execute srs ${flag} --file ${sqlPath}`.cwd(API);
|
||||
await $`rm ${sqlPath}`;
|
||||
|
||||
const counts =
|
||||
await $`bunx wrangler d1 execute srs ${flag} --json --command ${"SELECT (SELECT COUNT(*) FROM problems) AS problems, (SELECT COUNT(*) FROM problems WHERE stage != 'new') AS laddered, (SELECT COUNT(*) FROM problems WHERE defer_until IS NOT NULL) AS deferred, (SELECT COUNT(*) FROM attempts WHERE source='import') AS imported_attempts, (SELECT COUNT(*) FROM topics) AS topics, (SELECT COUNT(*) FROM drill_pool_used) AS drills_used"}`
|
||||
.cwd(API)
|
||||
.json();
|
||||
|
||||
const expected = {
|
||||
json_problems: Object.keys(state.problems).length,
|
||||
json_attempts: attempts,
|
||||
json_laddered: Object.values(state.problems).filter((p) => p.stage !== "new").length,
|
||||
json_deferred: Object.values(state.problems).filter((p) => p.defer_until).length,
|
||||
json_topics: Object.keys(state.topics).length,
|
||||
json_drills_used: state.drill_pool_used.length,
|
||||
};
|
||||
console.log("expected from srs.json:", JSON.stringify(expected));
|
||||
console.log("in D1:", JSON.stringify(counts[0]?.results?.[0] ?? counts));
|
||||
@@ -10,7 +10,7 @@
|
||||
* so relabelling a problem is enough to move it and titles stay readable.
|
||||
* The `problem` label is what marks a sub-issue as curriculum.
|
||||
*/
|
||||
import { addDays } from "./srs.ts";
|
||||
import { workingDay } from "./srs.ts";
|
||||
import type { GitHub } from "./github.ts";
|
||||
|
||||
const TITLE_RE = /^LC (\d+) · (.+)$/;
|
||||
@@ -18,7 +18,7 @@ const TITLE_RE = /^LC (\d+) · (.+)$/;
|
||||
const DIFFICULTIES = ["easy", "medium", "hard"] as const;
|
||||
const SETS = ["core", "optional", "deferred"] as const;
|
||||
|
||||
/** Deferred Hards enter the queue from this date, two per day. */
|
||||
/** Deferred Hards enter the queue from this date, two per working day. */
|
||||
const DEFER_FROM = "2026-09-28";
|
||||
|
||||
export interface ReconcileReport {
|
||||
@@ -96,9 +96,10 @@ export async function reconcileCatalog(db: D1Database, gh: GitHub): Promise<Reco
|
||||
continue;
|
||||
}
|
||||
const lc = Number(m[1]);
|
||||
// Two deferred Hards per day from DEFER_FROM, in catalog walk order —
|
||||
// applied only when the row is first created (SRS owns it afterwards).
|
||||
const defer = set === "deferred" ? addDays(DEFER_FROM, Math.floor(deferredSeen / 2)) : null;
|
||||
// Two deferred Hards per WORKING day from DEFER_FROM, in catalog walk
|
||||
// order — applied only when the row is first created (SRS owns it
|
||||
// afterwards). Sunday is skipped like every other scheduled date.
|
||||
const defer = set === "deferred" ? workingDay(DEFER_FROM, Math.floor(deferredSeen / 2)) : null;
|
||||
if (set === "deferred") deferredSeen++;
|
||||
statements.push(
|
||||
db
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
* badges: rounded #09090b cards, #fafafa/#a1a1aa text, GitHub dark-mode
|
||||
* green ramp. Every function renders on a zero-row DB.
|
||||
*/
|
||||
import { STAGES } from "./srs.ts";
|
||||
import { Canvas, textWidth } from "./png.ts";
|
||||
|
||||
// D1Database comes from the generated worker-configuration.d.ts runtime types.
|
||||
@@ -43,8 +44,6 @@ const PHASES = [
|
||||
{ milestone: 5, name: "V — Decision Space" },
|
||||
];
|
||||
|
||||
const STAGES = ["new", "+2", "+5", "+10", "retired"];
|
||||
|
||||
// ── svg helpers ──────────────────────────────────────────────────
|
||||
|
||||
/** Opening tag plus the rounded dark card every chart starts with. */
|
||||
@@ -159,6 +158,9 @@ export async function progressChart(db: D1Database): Promise<string> {
|
||||
|
||||
// ── ladder: bar per stage ────────────────────────────────────────
|
||||
|
||||
// One bar per rung, labelled and ordered by srs.ts's STAGES, so changing the
|
||||
// ladder can never leave a stale bar here: the slot width is derived from the
|
||||
// rung count, only the bar width inside a slot is fixed.
|
||||
export async function ladderChart(db: D1Database): Promise<string> {
|
||||
const { results } = await db
|
||||
.prepare(`SELECT stage, COUNT(*) AS count FROM problems GROUP BY stage`)
|
||||
|
||||
@@ -62,12 +62,12 @@ const DIFFICULTY: Record<string, { label: string; color: string }> = {
|
||||
hard: { label: "Hard", color: RED },
|
||||
};
|
||||
|
||||
// The SRS ladder in plain English — "+5" means the last look was 5 days back.
|
||||
// The SRS ladder in plain English — stage "+3" means the last clean look was
|
||||
// three days back, so that is what the reader is told.
|
||||
const LAST_SEEN: Record<string, string> = {
|
||||
new: "first look",
|
||||
"+2": "2 days ago",
|
||||
"+5": "5 days ago",
|
||||
"+10": "10 days ago",
|
||||
"+3": "3 days ago",
|
||||
"+7": "7 days ago",
|
||||
retired: "retired",
|
||||
};
|
||||
|
||||
@@ -302,7 +302,7 @@ function DigestEmail({ data }: { data: DigestData }) {
|
||||
<Text style={{ color: MUTED, fontSize: "13px", margin: "8px 0 0" }}>
|
||||
{data.progress}
|
||||
{data.rest
|
||||
? " · nothing is due today, and anything overdue waits for Monday."
|
||||
? " · the ladder never books a Sunday, so nothing is due — anything still open waits for Monday."
|
||||
: data.streak === 0
|
||||
? " · no streak going yet — today is a good day to start one."
|
||||
: ` · 🔥 ${data.streak} day${data.streak === 1 ? "" : "s"} in a row, keep it going.`}
|
||||
@@ -403,7 +403,7 @@ function plainDigest(data: DigestData): string {
|
||||
data.rest ? `Take the day off — ${data.day}` : `Good morning. It's ${data.day}.`,
|
||||
data.progress +
|
||||
(data.rest
|
||||
? " · nothing is due today, and anything overdue waits for Monday."
|
||||
? " · the ladder never books a Sunday, so nothing is due — anything still open waits for Monday."
|
||||
: data.streak === 0
|
||||
? " · no streak going yet — today is a good day to start one."
|
||||
: ` · ${data.streak} day${data.streak === 1 ? "" : "s"} in a row, keep it going.`),
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
* The gate half is a topic-blind quiz — one unsolved optional problem per
|
||||
* topic scheduled this week (which is why daily drills only draw from
|
||||
* earlier weeks). The recap half is generated data, deliberately NOT a task
|
||||
* list: the week's solved problems are already scheduled by the +2 ladder,
|
||||
* list: the week's solved problems are already scheduled by the +3/+7 ladder,
|
||||
* and re-assigning them on Saturday would be massed practice.
|
||||
*
|
||||
* Label is `review` (the retired Actions system owned `gate`). Creation is
|
||||
|
||||
+37
-16
@@ -19,7 +19,9 @@ import { type Mirror, projectMirror } from "./mirror.ts";
|
||||
import {
|
||||
CAMPAIGN_START,
|
||||
type LogOutcome,
|
||||
type Stage,
|
||||
daysBetween,
|
||||
dueToday,
|
||||
etDate,
|
||||
etHour,
|
||||
getProblem,
|
||||
@@ -44,7 +46,7 @@ async function mirrorOutcome(env: Env, outcome: LogOutcome, source: string): Pro
|
||||
try {
|
||||
await gh.closeIssue(
|
||||
outcome.issue,
|
||||
`First attempt passed (${outcome.kind}, via ${source}) — entering the review ladder at +2. Logged by the SRS Worker.`,
|
||||
`First attempt passed (${outcome.kind}, via ${source}) — entering the review ladder at +3. Logged by the SRS Worker.`,
|
||||
);
|
||||
} catch (err) {
|
||||
console.warn(`close #${outcome.issue}: ${err}`);
|
||||
@@ -96,7 +98,7 @@ async function handleTap(request: Request, env: Env, ctx: ExecutionContext): Pro
|
||||
}
|
||||
ctx.waitUntil(mirrorOutcome(env, outcome, "email"));
|
||||
return page(
|
||||
result === "pass" ? "Logged ✅" : "Logged — back to +2",
|
||||
result === "pass" ? "Logged ✅" : "Logged — back to +3",
|
||||
outcomeLine(outcome),
|
||||
);
|
||||
}
|
||||
@@ -202,43 +204,56 @@ async function adminAuthorized(request: Request, env: Env): Promise<boolean> {
|
||||
/**
|
||||
* Solutions landing in `work/` are the third way a problem gets solved, after
|
||||
* the digest tap and a /done comment. `close-solved` posts its whole
|
||||
* implemented set here on every push to main: logAttempt ignores anything
|
||||
* already on the ladder, so this is a total recompute like the reconcilers
|
||||
* that call it — a re-run changes nothing.
|
||||
* implemented set here on every push to main, each entry tagged with the
|
||||
* BUCKET the file sits in — 1 for the first solve, 3 and 7 for the blind
|
||||
* re-solves the picker scaffolds. The bucket names the ladder rung the file
|
||||
* settles, and logAttempt writes only when the problem is standing on that
|
||||
* rung, so this is a total recompute like the reconcilers that call it: a
|
||||
* re-run changes nothing, and a pushed re-solve advances +3 → +7 instead of
|
||||
* being invisible.
|
||||
*
|
||||
* Closing the sub-issue stays with close-solved: it is the side that knows
|
||||
* which files at which commit, so this path mirrors Project fields only.
|
||||
* Charts read D1 live, so a push moves them within the 5-minute cache.
|
||||
*/
|
||||
const RUNG_OF_BUCKET: Record<number, Stage> = { 1: "new", 3: "+3", 7: "+7" };
|
||||
|
||||
async function handleSolved(request: Request, env: Env, date: string): Promise<Response> {
|
||||
const body: unknown = await request.json().catch(() => null);
|
||||
const raw: unknown = body && typeof body === "object" && "lc" in body ? body.lc : null;
|
||||
if (!Array.isArray(raw)) return new Response('expected {"lc": [<number>, ...]}', { status: 400 });
|
||||
const lcs: number[] = [];
|
||||
const raw: unknown = body && typeof body === "object" && "solved" in body ? body.solved : null;
|
||||
const shape = 'expected {"solved": [{"lc": <number>, "bucket": 1|3|7}, ...]}';
|
||||
if (!Array.isArray(raw)) return new Response(shape, { status: 400 });
|
||||
const entries: { lc: number; rung: Stage; bucket: number }[] = [];
|
||||
for (const item of raw) {
|
||||
const lc: unknown = item;
|
||||
if (!item || typeof item !== "object") return new Response(shape, { status: 400 });
|
||||
const lc: unknown = "lc" in item ? item.lc : null;
|
||||
const bucket: unknown = "bucket" in item ? item.bucket : null;
|
||||
if (typeof lc !== "number" || !Number.isFinite(lc)) {
|
||||
return new Response(`not an LC number: ${JSON.stringify(lc)}`, { status: 400 });
|
||||
}
|
||||
lcs.push(lc);
|
||||
const rung = typeof bucket === "number" ? RUNG_OF_BUCKET[bucket] : undefined;
|
||||
if (rung === undefined) return new Response(`not a work/ bucket: ${JSON.stringify(bucket)}`, { status: 400 });
|
||||
entries.push({ lc, rung, bucket });
|
||||
}
|
||||
const dry = new URL(request.url).searchParams.get("dry") === "1";
|
||||
|
||||
const logged: string[] = [];
|
||||
const skipped: string[] = [];
|
||||
let mirror: Mirror | undefined;
|
||||
for (const lc of lcs) {
|
||||
for (const { lc, rung, bucket } of entries) {
|
||||
if (dry) {
|
||||
const p = await getProblem(env.DB, lc);
|
||||
if (!p) skipped.push(`LC ${lc} is not in the curriculum`);
|
||||
else if (p.stage !== "new") skipped.push(`LC ${lc}: already at stage ${p.stage}`);
|
||||
else logged.push(`LC ${lc}: would enter the ladder at +2`);
|
||||
else if (p.stage !== rung) skipped.push(`LC ${lc}: work/${bucket} settles ${rung}, stage is ${p.stage}`);
|
||||
else if (rung === "new") logged.push(`LC ${lc}: would enter the ladder at +3`);
|
||||
else logged.push(`LC ${lc}: would pass ${rung} and move on`);
|
||||
continue;
|
||||
}
|
||||
const outcome = await logAttempt(env.DB, { lc, date, result: "pass", source: "commit" });
|
||||
const outcome = await logAttempt(env.DB, { lc, date, result: "pass", source: "commit", rung });
|
||||
if (outcome.error) skipped.push(outcome.error);
|
||||
else if (outcome.duplicate) skipped.push(`LC ${lc}: already at stage ${outcome.stage}`);
|
||||
else {
|
||||
else if (outcome.duplicate) {
|
||||
skipped.push(`LC ${lc}: work/${bucket} settles ${rung}, stage is ${outcome.stage}`);
|
||||
} else {
|
||||
logged.push(outcomeLine(outcome));
|
||||
// One mirror for the batch: field IDs resolve once, not per problem.
|
||||
mirror ??= projectMirror(github(env.GH_PAT, env.REPO), env.REPO.split("/")[0]!);
|
||||
@@ -271,6 +286,12 @@ async function handleAdmin(request: Request, env: Env, path: string): Promise<Re
|
||||
if (path === "/admin/review") {
|
||||
return Response.json(await createReviewIssue(env, gh(), date));
|
||||
}
|
||||
// What is due on `date`, straight out of the ladder — the ONE answer to
|
||||
// "which problems are open today", so the daily review issue and the digest
|
||||
// cannot disagree. Read-only; the caller decides what to render.
|
||||
if (path === "/admin/due") {
|
||||
return Response.json(await dueToday(env.DB, date));
|
||||
}
|
||||
return new Response("not found", { status: 404 });
|
||||
}
|
||||
|
||||
|
||||
@@ -1,11 +1,30 @@
|
||||
/**
|
||||
* DST-guard and date-math checks with fixed instants — the acceptance proof
|
||||
* that the double crons fire exactly once at 8 AM ET (digest) and midnight
|
||||
* Saturday ET (review issue) on BOTH UTC offsets.
|
||||
* Acceptance proof for the two rules that cannot be eyeballed in production:
|
||||
* the double crons fire exactly once at 8 AM ET (digest) and midnight Saturday
|
||||
* ET (review issue) on BOTH UTC offsets, and NOTHING is ever scheduled on the
|
||||
* Sunday rest day — which is the whole reason the ladder's windows are 3 and 7.
|
||||
*/
|
||||
import { describe, expect, test } from "bun:test";
|
||||
|
||||
import { addDays, campaignDay, campaignWeek, etDate, etHour, isoWeek, rng, sample, weekdayOf } from "./srs.ts";
|
||||
import {
|
||||
INTERVAL,
|
||||
STAGES,
|
||||
WINDOWS,
|
||||
addDays,
|
||||
campaignDay,
|
||||
campaignWeek,
|
||||
etDate,
|
||||
etHour,
|
||||
isRestDay,
|
||||
isoWeek,
|
||||
rng,
|
||||
sample,
|
||||
weekdayOf,
|
||||
workingDay,
|
||||
} from "./srs.ts";
|
||||
|
||||
/** Every ET date of the campaign, plus the deferred-Hard tail. */
|
||||
const CALENDAR = Array.from({ length: 70 }, (_, i) => addDays("2026-08-17", i));
|
||||
|
||||
describe("DST-proof cron guard", () => {
|
||||
test("digest fires only at ET hour 8 — EDT (UTC-4)", () => {
|
||||
@@ -50,6 +69,69 @@ describe("date math (noon-UTC anchored)", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("the rest day", () => {
|
||||
test("Sunday is the only rest day", () => {
|
||||
expect(isRestDay("2026-08-30")).toBe(true); // Sunday
|
||||
expect(isRestDay("2026-08-29")).toBe(false); // Saturday: gate day, still work
|
||||
expect(isRestDay("2026-08-31")).toBe(false);
|
||||
});
|
||||
|
||||
test("workingDay never returns a Sunday, from any day and any offset", () => {
|
||||
for (const date of CALENDAR) {
|
||||
for (let offset = 0; offset < 10; offset++) {
|
||||
expect(isRestDay(workingDay(date, offset))).toBe(false);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("workingDay(date) leaves a working day alone and slides Sunday to Monday", () => {
|
||||
expect(workingDay("2026-09-04")).toBe("2026-09-04"); // Friday
|
||||
expect(workingDay("2026-09-05")).toBe("2026-09-05"); // Saturday
|
||||
expect(workingDay("2026-09-06")).toBe("2026-09-07"); // Sunday → Monday
|
||||
});
|
||||
|
||||
test("offsets count working days, so a spill skips the rest day", () => {
|
||||
// Levelling from Saturday: tomorrow is Sunday, so the spill starts Monday.
|
||||
expect(workingDay("2026-09-05", 1)).toBe("2026-09-07");
|
||||
expect(workingDay("2026-09-05", 2)).toBe("2026-09-08");
|
||||
// Two deferred Hards per working day from a Monday.
|
||||
expect(workingDay("2026-09-28", 5)).toBe("2026-10-03"); // Saturday
|
||||
expect(workingDay("2026-09-28", 6)).toBe("2026-10-05"); // Sunday skipped
|
||||
});
|
||||
|
||||
test("every ladder interval lands on a working day, from every learning day", () => {
|
||||
for (const date of CALENDAR) {
|
||||
if (isRestDay(date)) continue;
|
||||
for (const days of WINDOWS) {
|
||||
const review = workingDay(addDays(date, days));
|
||||
expect(isRestDay(review)).toBe(false);
|
||||
// Never earlier than the interval: a review may slip, never shorten.
|
||||
expect(review >= addDays(date, days)).toBe(true);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("only Thursday's +3 needs the slide", () => {
|
||||
const slid = CALENDAR.filter(
|
||||
(date) => !isRestDay(date) && workingDay(addDays(date, 3)) !== addDays(date, 3),
|
||||
);
|
||||
expect(new Set(slid.map(weekdayOf))).toEqual(new Set([4])); // Thursday only
|
||||
for (const date of CALENDAR) {
|
||||
if (isRestDay(date)) continue;
|
||||
expect(workingDay(addDays(date, 7))).toBe(addDays(date, 7)); // +7 keeps the weekday
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("the ladder", () => {
|
||||
test("two rungs, named after the windows", () => {
|
||||
expect(STAGES).toEqual(["new", "+3", "+7", "retired"]);
|
||||
expect(WINDOWS.map((w) => INTERVAL[`+${w}`])).toEqual([...WINDOWS]);
|
||||
// Every non-terminal stage has an interval, and only those.
|
||||
expect(Object.keys(INTERVAL).sort()).toEqual(STAGES.slice(1, -1).sort());
|
||||
});
|
||||
});
|
||||
|
||||
describe("deterministic sampling", () => {
|
||||
test("same seed, same picks", () => {
|
||||
const pool = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
|
||||
|
||||
+160
-32
@@ -1,12 +1,19 @@
|
||||
/**
|
||||
* SRS domain: ET dates, the interval ladder, deterministic sampling, and the
|
||||
* one write path for attempts — ported from scripts/srs.ts, re-homed on D1.
|
||||
* SRS domain: ET dates, the work week, the interval ladder, deterministic
|
||||
* sampling, and the one write path for attempts.
|
||||
*
|
||||
* D1 is the single source of truth. The stage names the review a problem must
|
||||
* pass NEXT (`+2` = due 2 days after last clean solve). Passing advances
|
||||
* new → +2 → +5 → +10 → retired; any failure resets to +2. A problem's
|
||||
* FIRST-ever log enters the ladder at +2 regardless of result: a pass earns
|
||||
* a +2 review, a fail must be re-solved just as soon.
|
||||
* pass NEXT (`+3` = due 3 working days after the last clean solve). Passing
|
||||
* advances new → +3 → +7 → retired; any failure resets to +3. A problem's
|
||||
* FIRST-ever log enters the ladder at +3 regardless of result: a pass earns a
|
||||
* 3-day review, a fail must be re-solved just as soon. Two rungs, 3 and 7 —
|
||||
* the same numbers as the `work/3` and `work/7` buckets a re-solve is
|
||||
* scaffolded into, and as the review-issue windows in
|
||||
* apps/cli/spaced-repetition.ts.
|
||||
*
|
||||
* Sunday is off, structurally: every scheduled date comes out of
|
||||
* workingDay(), which never returns one. Nothing "falls on" the rest day and
|
||||
* gets swallowed or carried — it is simply never booked there.
|
||||
*
|
||||
* All dates are America/New_York calendar strings (YYYY-MM-DD); arithmetic is
|
||||
* anchored at noon UTC so DST edges cannot shift a date. Never raw Date math.
|
||||
@@ -56,6 +63,37 @@ export function weekdayOf(date: string): number {
|
||||
return atNoon(date).getUTCDay();
|
||||
}
|
||||
|
||||
// ── the work week ────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Sunday, the one day the campaign never schedules: topics run Mon–Fri
|
||||
* (data/schedule.json), the gate is Saturday, and the review windows below are
|
||||
* picked so a solve comes back on a working day.
|
||||
*/
|
||||
const REST_DAY = 0;
|
||||
|
||||
export function isRestDay(date: string): boolean {
|
||||
return weekdayOf(date) === REST_DAY;
|
||||
}
|
||||
|
||||
/**
|
||||
* The `offset`-th working day counting from `from` (0 = `from` itself), with
|
||||
* Sundays skipped — the ONE place a scheduled date is minted.
|
||||
*
|
||||
* Work may slide later, never earlier: pulling a review back to Saturday would
|
||||
* shorten the very interval it exists to test, so a Sunday landing becomes
|
||||
* Monday. With the +3/+7 ladder that only ever happens to a Thursday solve's
|
||||
* 3-day review; +7 lands on the solve's own weekday, which is never a Sunday.
|
||||
*/
|
||||
export function workingDay(from: string, offset = 0): string {
|
||||
let cursor = isRestDay(from) ? addDays(from, 1) : from;
|
||||
for (let i = 0; i < offset; i++) {
|
||||
cursor = addDays(cursor, 1);
|
||||
if (isRestDay(cursor)) cursor = addDays(cursor, 1);
|
||||
}
|
||||
return cursor;
|
||||
}
|
||||
|
||||
export function campaignDay(date: string): number {
|
||||
return daysBetween(CAMPAIGN_START, date) + 1;
|
||||
}
|
||||
@@ -126,7 +164,21 @@ export function sample<T>(pool: T[], n: number, random: () => number): T[] {
|
||||
|
||||
// ── rows ─────────────────────────────────────────────────────────
|
||||
|
||||
export type Stage = "new" | "+2" | "+5" | "+10" | "retired";
|
||||
/**
|
||||
* Review windows in days. One vocabulary for the whole campaign: these are the
|
||||
* ladder rungs, the `work/<n>` buckets the picker scaffolds into, and the
|
||||
* windows the `Spaced Repetition — <date>` issues are built from.
|
||||
*
|
||||
* 3 and 7 keep the rest day free. +7 returns a solve to its own weekday, and
|
||||
* of the five learning weekdays only Thursday's +3 touches a Sunday — which
|
||||
* workingDay() slides to Monday.
|
||||
*/
|
||||
export const WINDOWS = [3, 7] as const;
|
||||
export type Window = (typeof WINDOWS)[number];
|
||||
|
||||
export type Stage = "new" | `+${Window}` | "retired";
|
||||
/** Chart / stats order, low to high. */
|
||||
export const STAGES: Stage[] = ["new", "+3", "+7", "retired"];
|
||||
export type Result = "pass" | "fail";
|
||||
export type Kind = "first" | "review" | "drill" | "gate";
|
||||
|
||||
@@ -142,8 +194,8 @@ export interface ProblemRow {
|
||||
defer_until: string | null;
|
||||
}
|
||||
|
||||
export const INTERVAL: Record<string, number> = { "+2": 2, "+5": 5, "+10": 10 };
|
||||
const NEXT_STAGE: Record<string, Stage> = { new: "+2", "+2": "+5", "+5": "+10", "+10": "retired" };
|
||||
export const INTERVAL: Record<string, number> = { "+3": 3, "+7": 7 };
|
||||
const NEXT_STAGE: Record<string, Stage> = { new: "+3", "+3": "+7", "+7": "retired" };
|
||||
|
||||
// ── queries ──────────────────────────────────────────────────────
|
||||
|
||||
@@ -151,31 +203,97 @@ export async function getProblem(db: D1Database, lc: number): Promise<ProblemRow
|
||||
return db.prepare("SELECT * FROM problems WHERE lc_number = ?").bind(lc).first<ProblemRow>();
|
||||
}
|
||||
|
||||
/**
|
||||
* What "due" means, in one place: not retired, scheduled on/before ?1, and
|
||||
* past its deferral if it has one. Every caller that asks "what is open on
|
||||
* this day" — the digest, the review issue, the docs queue chart — shares
|
||||
* this clause so they cannot answer differently.
|
||||
*/
|
||||
export const DUE_WHERE = `stage != 'retired' AND next_review IS NOT NULL AND next_review <= ?1
|
||||
AND (defer_until IS NULL OR defer_until <= ?1)`;
|
||||
|
||||
/** Reviews due on/before `date`, oldest first — the overflow carry order. */
|
||||
export async function dueReviews(db: D1Database, date: string): Promise<ProblemRow[]> {
|
||||
const { results } = await db
|
||||
.prepare(
|
||||
`SELECT * FROM problems
|
||||
WHERE stage != 'retired' AND next_review IS NOT NULL AND next_review <= ?1
|
||||
AND (defer_until IS NULL OR defer_until <= ?1)
|
||||
ORDER BY next_review, lc_number`,
|
||||
)
|
||||
.prepare(`SELECT * FROM problems WHERE ${DUE_WHERE} ORDER BY next_review, lc_number`)
|
||||
.bind(date)
|
||||
.all<ProblemRow>();
|
||||
return results;
|
||||
}
|
||||
|
||||
/** One problem the ladder wants re-solved today. */
|
||||
export interface DueRow {
|
||||
lc: number;
|
||||
issue: number;
|
||||
title: string;
|
||||
difficulty: string;
|
||||
/** The rung being settled: also the `work/<n>` bucket the re-solve goes in. */
|
||||
stage: Stage;
|
||||
bucket: number;
|
||||
/** Scheduled day; earlier than `date` when a day was missed. */
|
||||
due: string;
|
||||
/** Days late (0 = due today), so a renderer can say so. */
|
||||
late: number;
|
||||
/** Last logged attempt, and how long ago — the "last seen" line. */
|
||||
last_seen: string | null;
|
||||
days_since: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything the ladder wants re-solved on `date`, oldest first.
|
||||
*
|
||||
* The read side of "which problems are open today": the same rows the digest
|
||||
* mails, shaped for whoever renders them (the daily Spaced Repetition issue).
|
||||
* Nothing here writes, so it is safe to call repeatedly, and there is no
|
||||
* second schedule to drift — D1's ladder is the schedule.
|
||||
*/
|
||||
export async function dueToday(db: D1Database, date: string): Promise<{ date: string; due: DueRow[] }> {
|
||||
const { results } = await db
|
||||
.prepare(
|
||||
`SELECT lc_number, issue, title, difficulty, stage, next_review,
|
||||
(SELECT MAX(a.date) FROM attempts a WHERE a.lc_number = problems.lc_number) AS last_seen
|
||||
FROM problems WHERE ${DUE_WHERE} ORDER BY next_review, lc_number`,
|
||||
)
|
||||
.bind(date)
|
||||
.all<{
|
||||
lc_number: number;
|
||||
issue: number;
|
||||
title: string;
|
||||
difficulty: string;
|
||||
stage: Stage;
|
||||
next_review: string;
|
||||
last_seen: string | null;
|
||||
}>();
|
||||
return {
|
||||
date,
|
||||
due: results.map((r) => ({
|
||||
lc: r.lc_number,
|
||||
issue: r.issue,
|
||||
title: r.title,
|
||||
difficulty: r.difficulty,
|
||||
stage: r.stage,
|
||||
// "+3" -> 3: the rung's number IS its work/ bucket.
|
||||
bucket: Number(r.stage.slice(1)),
|
||||
due: r.next_review,
|
||||
late: daysBetween(r.next_review, date),
|
||||
last_seen: r.last_seen,
|
||||
days_since: r.last_seen === null ? null : daysBetween(r.last_seen, date),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
/** Reviews surfaced per day; the digest levels everything past this forward. */
|
||||
export const REVIEW_CAP = 3;
|
||||
|
||||
/**
|
||||
* Load-level an overloaded review queue: everything due beyond today's
|
||||
* REVIEW_CAP is pushed to a concrete future date — at most REVIEW_CAP per
|
||||
* day, oldest first — instead of piling up as "due today". Runs every digest
|
||||
* morning, so a future day that grows past the cap (spill plus newly
|
||||
* REVIEW_CAP is pushed to a concrete future WORKING day — at most REVIEW_CAP
|
||||
* per day, oldest first — instead of piling up as "due today". Runs every
|
||||
* digest morning, so a future day that grows past the cap (spill plus newly
|
||||
* maturing reviews) is simply re-levelled when it arrives. Idempotent within
|
||||
* a date: after one pass at most REVIEW_CAP problems remain due today, so a
|
||||
* second pass moves nothing.
|
||||
* second pass moves nothing. The spill starts tomorrow, or Monday when
|
||||
* tomorrow is the rest day.
|
||||
*/
|
||||
export async function levelReviews(db: D1Database, date: string): Promise<number> {
|
||||
const overflow = (await dueReviews(db, date)).slice(REVIEW_CAP);
|
||||
@@ -184,7 +302,7 @@ export async function levelReviews(db: D1Database, date: string): Promise<number
|
||||
overflow.map((p, i) =>
|
||||
db
|
||||
.prepare("UPDATE problems SET next_review = ? WHERE lc_number = ?")
|
||||
.bind(addDays(date, 1 + Math.floor(i / REVIEW_CAP)), p.lc_number),
|
||||
.bind(workingDay(addDays(date, 1), Math.floor(i / REVIEW_CAP)), p.lc_number),
|
||||
),
|
||||
);
|
||||
return overflow.length;
|
||||
@@ -273,9 +391,14 @@ export interface LogOutcome {
|
||||
* Email idempotency comes from the partial unique index on
|
||||
* (lc_number, date, kind) WHERE source='email': a replayed link inserts
|
||||
* nothing and must not touch the ladder. Webhook corrections (pass then fail
|
||||
* on the same day) remain legal — every webhook attempt appends. Commit
|
||||
* idempotency needs no index: a commit records a FIRST solve only, so the
|
||||
* stage check below turns every re-push into a no-op.
|
||||
* on the same day) remain legal — every webhook attempt appends.
|
||||
*
|
||||
* Commit idempotency needs no index either. A commit names the rung the file
|
||||
* it landed in settles — `work/1` settles `new`, `work/3` settles `+3`,
|
||||
* `work/7` settles `+7` — and the stage check below writes only when the
|
||||
* ladder is actually standing on that rung. So re-pushing a solution, or the
|
||||
* reconciler re-sending its whole implemented set on every push, moves
|
||||
* nothing: the rung it names has already been left behind.
|
||||
*/
|
||||
export async function logAttempt(
|
||||
db: D1Database,
|
||||
@@ -284,6 +407,8 @@ export async function logAttempt(
|
||||
date: string;
|
||||
result: Result;
|
||||
source: "email" | "webhook" | "commit";
|
||||
/** Commit only: the stage this file settles. Default `new` = first solve. */
|
||||
rung?: Stage;
|
||||
gate?: boolean;
|
||||
},
|
||||
): Promise<LogOutcome> {
|
||||
@@ -300,11 +425,12 @@ export async function logAttempt(
|
||||
duplicate: false,
|
||||
};
|
||||
if (!p) return { ...nothing, error: `LC ${opts.lc} is not in the curriculum` };
|
||||
// A commit only ever reports a first solve: pushing the file again — or the
|
||||
// reconciler re-sending the whole solved set — must never move the ladder,
|
||||
// and must never wake a retired problem. Reviews come from the digest tap,
|
||||
// a /done comment, or a gate.
|
||||
if (opts.source === "commit" && p.stage !== "new") {
|
||||
// A commit reports a file, not an event: it may only settle the rung that
|
||||
// file's bucket IS. Any other stage means the push is old news (the ladder
|
||||
// already moved past it) or premature — no write either way, and a retired
|
||||
// problem can never be woken. Fresh reviews otherwise come from the digest
|
||||
// tap, a /done comment, or a gate.
|
||||
if (opts.source === "commit" && p.stage !== (opts.rung ?? "new")) {
|
||||
return {
|
||||
...nothing,
|
||||
title: p.title,
|
||||
@@ -336,16 +462,18 @@ export async function logAttempt(
|
||||
return { ...nothing, title: p.title, kind, stage: p.stage, next_review: p.next_review, issue: p.issue, duplicate: true };
|
||||
}
|
||||
|
||||
// Ladder move. First-ever logs enter at +2 for pass AND fail.
|
||||
// Ladder move. First-ever logs enter at +3 for pass AND fail.
|
||||
let stage: Stage;
|
||||
if (first) {
|
||||
stage = "+2";
|
||||
stage = "+3";
|
||||
} else if (opts.result === "pass") {
|
||||
stage = NEXT_STAGE[p.stage] ?? "retired";
|
||||
} else {
|
||||
stage = "+2";
|
||||
stage = "+3";
|
||||
}
|
||||
const next = stage === "retired" ? null : addDays(opts.date, INTERVAL[stage]!);
|
||||
// workingDay(), not addDays(): a Thursday solve's +3 would land on the rest
|
||||
// day, and it takes Monday instead.
|
||||
const next = stage === "retired" ? null : workingDay(addDays(opts.date, INTERVAL[stage]!));
|
||||
|
||||
const writes = [
|
||||
db.prepare(
|
||||
|
||||
@@ -7,10 +7,12 @@
|
||||
import {
|
||||
CAMPAIGN_DAYS,
|
||||
CAMPAIGN_START,
|
||||
DUE_WHERE,
|
||||
addDays,
|
||||
campaignDay,
|
||||
campaignWeek,
|
||||
isoWeek,
|
||||
STAGES,
|
||||
streak,
|
||||
} from "./srs.ts";
|
||||
|
||||
@@ -59,7 +61,8 @@ export async function buildStats(db: D1Database, today: string): Promise<object>
|
||||
const { results: ladderRows } = await db
|
||||
.prepare("SELECT stage, COUNT(*) AS n FROM problems GROUP BY stage")
|
||||
.all<{ stage: string; n: number }>();
|
||||
const ladder: Record<string, number> = { new: 0, "+2": 0, "+5": 0, "+10": 0, retired: 0 };
|
||||
// Every rung is present even at zero: the page's bar list is this object.
|
||||
const ladder: Record<string, number> = Object.fromEntries(STAGES.map((s) => [s, 0]));
|
||||
for (const row of ladderRows) ladder[row.stage] = row.n;
|
||||
|
||||
// gates rows are keyed by ISO week (that's the digest/gate contract), but
|
||||
@@ -76,11 +79,7 @@ export async function buildStats(db: D1Database, today: string): Promise<object>
|
||||
for (let i = 0; i < 14; i++) {
|
||||
const date = addDays(today, i);
|
||||
const row = await db
|
||||
.prepare(
|
||||
`SELECT COUNT(*) AS n FROM problems
|
||||
WHERE stage != 'retired' AND next_review IS NOT NULL AND next_review <= ?1
|
||||
AND (defer_until IS NULL OR defer_until <= ?1)`,
|
||||
)
|
||||
.prepare(`SELECT COUNT(*) AS n FROM problems WHERE ${DUE_WHERE}`)
|
||||
.bind(date)
|
||||
.first<{ n: number }>();
|
||||
queue.push({ date, due: row?.n ?? 0 });
|
||||
|
||||
+28
-75
@@ -10,7 +10,7 @@
|
||||
*
|
||||
* `bun run pick` scaffolds a statement header plus an empty function body, so
|
||||
* file existence alone means nothing — a stub must not close its issue. See
|
||||
* isImplemented().
|
||||
* isImplemented() in source.ts.
|
||||
*
|
||||
* bun apps/cli/close-solved.ts # close matches, log them in D1
|
||||
* bun apps/cli/close-solved.ts --dry-run # report only, touch nothing
|
||||
@@ -19,68 +19,18 @@
|
||||
* SRS_ADMIN_KEY for the D1 push (unset = skip it); SRS_API overrides
|
||||
* the Worker URL for local `wrangler dev` runs.
|
||||
*/
|
||||
import { basename, join } from "node:path";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { github } from "./github.ts";
|
||||
import { markdownTable, printTable, writeStepSummary } from "./report.ts";
|
||||
|
||||
const ROOT = join(import.meta.dir, "..", "..");
|
||||
const WORK = join(ROOT, "work");
|
||||
import { isImplemented } from "./source.ts";
|
||||
import { WORK, parseWorkPath, type Bucket } from "./work.ts";
|
||||
|
||||
const DRY =
|
||||
process.argv.includes("--dry-run") ||
|
||||
process.env.DRY_RUN === "1" ||
|
||||
process.env.DRY_RUN === "true";
|
||||
|
||||
// ── is the file a real solution or just a scaffolded stub? ────────
|
||||
|
||||
/** Placeholder bodies that leetcode-cli / a human leaves behind. */
|
||||
const PLACEHOLDERS: Record<string, true> = { pass: true, "...": true, TODO: true };
|
||||
|
||||
/**
|
||||
* Decide whether a work/ file contains an implementation.
|
||||
*
|
||||
* The header comment is dropped the same way sync.ts splitSource() does it
|
||||
* (duplicated rather than imported, because sync.ts runs its whole pipeline on
|
||||
* import). Comments must go before any brace analysis: the scaffold's JSDoc
|
||||
* carries `@param {number[]}`, whose braces would otherwise read as a body.
|
||||
*
|
||||
* A brace-language file counts as implemented when at least one *innermost*
|
||||
* brace pair holds real content. That distinguishes a bare stub
|
||||
* (`function(nums) {}`) and a class-shaped design stub (every method body
|
||||
* empty) from any genuine solution, whose innermost block always has code.
|
||||
*/
|
||||
function isImplemented(src: string, lang: "js" | "py"): boolean {
|
||||
if (lang === "py") {
|
||||
const open = src.indexOf('"""');
|
||||
const close = src.indexOf('"""', open + 3);
|
||||
const code = open === -1 || close === -1 ? src : src.slice(close + 3);
|
||||
for (const raw of code.split("\n")) {
|
||||
const line = raw.replace(/#.*$/, "").trim();
|
||||
if (!line || PLACEHOLDERS[line]) continue;
|
||||
if (/^(?:@|def\s|class\s)/.test(line)) continue;
|
||||
return true; // a statement inside some def body
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const headerEnd = src.indexOf("*/");
|
||||
const body = headerEnd === -1 ? src : src.slice(headerEnd + 2);
|
||||
const code = body.replace(/\/\*[\s\S]*?\*\//g, " ").replace(/\/\/.*$/gm, " ");
|
||||
|
||||
let innermost = -1;
|
||||
for (let i = 0; i < code.length; i++) {
|
||||
if (code[i] === "{") {
|
||||
innermost = i;
|
||||
} else if (code[i] === "}" && innermost !== -1) {
|
||||
const inner = code.slice(innermost + 1, i).replace(/[\s;]/g, "");
|
||||
if (inner && !PLACEHOLDERS[inner]) return true;
|
||||
innermost = -1; // measured; the enclosing pair is not innermost
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// ── repo + auth ──────────────────────────────────────────────────
|
||||
|
||||
const gh = await github();
|
||||
@@ -89,27 +39,27 @@ const gh = await github();
|
||||
|
||||
interface WorkEntry {
|
||||
files: string[];
|
||||
/** Any bucket implemented — this is what closes the problem issue. */
|
||||
implemented: boolean;
|
||||
/** Buckets holding a real solution: 1 = first solve, 3/7 = the re-solves. */
|
||||
solved: Set<Bucket>;
|
||||
}
|
||||
|
||||
/** LC number -> solution files (a problem may have both js and py). */
|
||||
/** LC number -> its solution files across every bucket (js and py both count). */
|
||||
const work = new Map<number, WorkEntry>();
|
||||
for await (const rel of new Bun.Glob("**/*.{js,py}").scan(WORK)) {
|
||||
const m = basename(rel).match(/^(\d+)\.(.+)\.(?:js|py)$/);
|
||||
if (!m) {
|
||||
console.warn(`skip (unrecognized name): work/${rel}`);
|
||||
const file = parseWorkPath(rel);
|
||||
if (!file) {
|
||||
console.warn(`skip (off-layout): work/${rel}`);
|
||||
continue;
|
||||
}
|
||||
const num = Number(m[1]);
|
||||
const src = await Bun.file(join(WORK, rel)).text();
|
||||
const implemented = isImplemented(src, rel.endsWith(".py") ? "py" : "js");
|
||||
const entry = work.get(num);
|
||||
if (entry) {
|
||||
entry.files.push(`work/${rel}`);
|
||||
entry.implemented ||= implemented;
|
||||
} else {
|
||||
work.set(num, { files: [`work/${rel}`], implemented });
|
||||
}
|
||||
const entry = work.get(file.lc) ?? { files: [], implemented: false, solved: new Set<Bucket>() };
|
||||
entry.files.push(`work/${rel}`);
|
||||
entry.implemented ||= implemented;
|
||||
if (implemented) entry.solved.add(file.bucket);
|
||||
work.set(file.lc, entry);
|
||||
}
|
||||
|
||||
// ── open problem issues ──────────────────────────────────────────
|
||||
@@ -205,14 +155,17 @@ for (const num of [...work.keys()].sort((a, b) => a - b)) {
|
||||
// or the charts, the digest's "already solved" ticks, and the drill/gate
|
||||
// pools all keep treating it as untouched.
|
||||
//
|
||||
// The whole implemented set goes over, not just this run's closes: the
|
||||
// Worker drops anything already on the ladder, so the call is a total
|
||||
// recompute and backfills whatever earlier runs missed.
|
||||
// Each entry carries the BUCKET the file sits in, which is the rung it
|
||||
// settles: work/1 is the first solve, work/3 the 3-day review, work/7 the
|
||||
// 7-day one. That is what makes a pushed re-solve advance the ladder instead
|
||||
// of vanishing — and the Worker writes only when a problem is standing on the
|
||||
// rung named, so the whole implemented set can go over on every push (a total
|
||||
// recompute that backfills whatever earlier runs missed) and re-runs write
|
||||
// nothing.
|
||||
const SRS_API = process.env.SRS_API ?? "https://srs-api.prdlk.workers.dev";
|
||||
const solved = [...work.entries()]
|
||||
.filter(([, entry]) => entry.implemented)
|
||||
.map(([lc]) => lc)
|
||||
.sort((a, b) => a - b);
|
||||
.flatMap(([lc, entry]) => [...entry.solved].sort().map((bucket) => ({ lc, bucket })))
|
||||
.sort((a, b) => a.lc - b.lc || a.bucket - b.bucket);
|
||||
|
||||
let syncNote: string;
|
||||
let syncFailed = false;
|
||||
@@ -228,7 +181,7 @@ if (!process.env.SRS_ADMIN_KEY) {
|
||||
authorization: `Bearer ${process.env.SRS_ADMIN_KEY}`,
|
||||
"content-type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ lc: solved }),
|
||||
body: JSON.stringify({ solved }),
|
||||
});
|
||||
if (!res.ok) throw new Error(`${res.status} ${await res.text()}`);
|
||||
// Narrow the report payload instead of casting it; a shape change should
|
||||
@@ -257,7 +210,7 @@ printTable(rows);
|
||||
|
||||
const actionable = report.filter((r) => r[3] !== "no open issue");
|
||||
console.log(
|
||||
`\n${work.size} in work/ · ${solved.length} implemented · ` +
|
||||
`\n${work.size} problems in work/ · ${solved.length} solved files across buckets · ` +
|
||||
`${actionable.length} matched an open issue · ` +
|
||||
`${DRY ? `would close ${actionable.filter((r) => r[3] === "would close").length}` : `closed ${closed}`}` +
|
||||
`\nd1: ${syncNote}`,
|
||||
@@ -265,7 +218,7 @@ console.log(
|
||||
|
||||
await writeStepSummary(
|
||||
`### close-solved${DRY ? " (dry run)" : ""}\n\n` +
|
||||
`${work.size} files in \`work/\`, ${solved.length} implemented, ` +
|
||||
`${work.size} problems in \`work/\`, ${solved.length} solved files across buckets, ` +
|
||||
`${actionable.length} matched an open issue.\n\n` +
|
||||
(actionable.length
|
||||
? `${markdownTable([rows[0]!, ...actionable])}\n`
|
||||
|
||||
+186
-30
@@ -1,19 +1,24 @@
|
||||
#!/usr/bin/env bun
|
||||
/**
|
||||
* Fuzzy-pick a LeetCode problem and scaffold it via leetcode-cli.
|
||||
* Fuzzy-pick a problem and scaffold it via leetcode-cli, in one of the three
|
||||
* work/ buckets (see work.ts): a first solve under work/1, or the 3-day and
|
||||
* 7-day blind re-solves under work/3 and work/7. Tab cycles the sections.
|
||||
*
|
||||
* The problem index lives in the local SQLite cache (see db.ts), refreshed at
|
||||
* most once per 24h; campaign problem descriptions from README.md are
|
||||
* backfilled into the same db on the way. Problems that already have a
|
||||
* numbered file under work/ are excluded from the picker — re-picking them
|
||||
* would only clobber the existing scaffold.
|
||||
* backfilled into the same db on the way. The new-problem section hides
|
||||
* anything that already has a numbered file under work/1 — re-picking it would
|
||||
* only clobber the existing scaffold — and each review section hides whatever
|
||||
* its own bucket already holds, so a finished re-solve leaves the list.
|
||||
*/
|
||||
import { autocomplete, cancel, isCancel, spinner } from "@clack/prompts";
|
||||
import { basename, join } from "node:path";
|
||||
import { fetchDescription, problemDb, readmeSlugs, type Problem } from "./db";
|
||||
|
||||
const ROOT = join(import.meta.dir, "..", "..");
|
||||
const WORK_DIR = join(ROOT, "work");
|
||||
import { autocomplete, cancel, isCancel, log, spinner } from "@clack/prompts";
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { styleText } from "node:util";
|
||||
import { etDate } from "../api/src/srs.ts";
|
||||
import { fetchDescription, problemDb, readmeSlugs } from "./db";
|
||||
import { ROOT, WINDOWS, bucketDir, reviewQueues, scanBucket, type Bucket } from "./work";
|
||||
|
||||
const db = problemDb();
|
||||
|
||||
@@ -57,26 +62,110 @@ if (missing.length > 0) {
|
||||
s.stop(failed ? `Cached ${fetched} descriptions (${failed} failed, will retry next run)` : `Cached ${fetched} problem descriptions`);
|
||||
}
|
||||
|
||||
// ── exclude problems already picked or solved under work/ ────────
|
||||
// ── the three sections ───────────────────────────────────────────
|
||||
|
||||
const done = new Set<number>();
|
||||
for (const rel of new Bun.Glob("**/*.*").scanSync({ cwd: WORK_DIR })) {
|
||||
const m = basename(rel).match(/^(\d+)\./);
|
||||
if (m) done.add(Number(m[1]));
|
||||
/** What Enter scaffolds: this problem, into this bucket. */
|
||||
interface Choice {
|
||||
bucket: Bucket;
|
||||
lc: number;
|
||||
slug: string;
|
||||
}
|
||||
|
||||
const problems = db.all().filter((p) => !done.has(p.id));
|
||||
interface Section {
|
||||
label: string;
|
||||
options: { value: Choice; label: string; hint: string }[];
|
||||
}
|
||||
|
||||
const first = scanBucket(1);
|
||||
const problems = db.all();
|
||||
const titles = new Map(problems.map((p) => [p.id, p.title] as const));
|
||||
db.close();
|
||||
|
||||
const picked = await autocomplete<Problem>({
|
||||
message: "Pick a problem",
|
||||
placeholder: "Type to search by number or title...",
|
||||
maxItems: 12,
|
||||
options: problems.map((p) => ({
|
||||
value: p,
|
||||
label: `${p.id}. ${p.title}`,
|
||||
hint: p.paidOnly ? `${p.difficulty} 🔒 premium` : p.difficulty,
|
||||
const queues = reviewQueues(etDate(new Date()));
|
||||
|
||||
const sections: Section[] = [
|
||||
{
|
||||
label: "new",
|
||||
options: problems
|
||||
.filter((p) => !first.has(p.id))
|
||||
.map((p) => ({
|
||||
value: { bucket: 1 as Bucket, lc: p.id, slug: p.slug },
|
||||
label: `${p.id}. ${p.title}`,
|
||||
hint: p.paidOnly ? `${p.difficulty} 🔒 premium` : p.difficulty,
|
||||
})),
|
||||
},
|
||||
...WINDOWS.map((window) => ({
|
||||
label: `${window}-day`,
|
||||
options: queues.get(window)!.map((owed) => ({
|
||||
value: { bucket: window as Bucket, lc: owed.lc, slug: owed.slug },
|
||||
label: `${owed.lc}. ${titles.get(owed.lc) ?? owed.slug}`,
|
||||
hint: `${owed.difficulty} · ${owed.category} · solved ${owed.solved}, ${owed.days}d ago`,
|
||||
})),
|
||||
})),
|
||||
];
|
||||
|
||||
let active = 0;
|
||||
|
||||
/**
|
||||
* The slice of clack's AutocompletePrompt this picker drives. @clack/prompts
|
||||
* re-exports neither the class nor its type, and apps/cli does not depend on
|
||||
* @clack/core directly, so the contract is spelled out structurally.
|
||||
*/
|
||||
interface Autocomplete {
|
||||
userInput: string;
|
||||
on(event: "key", cb: (char: string | undefined, key: { name?: string }) => void): void;
|
||||
emit(event: "userInput", input: string): void;
|
||||
}
|
||||
|
||||
/** Search text that cannot match any option — see refresh() below. */
|
||||
const NO_MATCH = "\u0000";
|
||||
|
||||
let hooked = false;
|
||||
|
||||
/**
|
||||
* Bind Tab to the section switch, once per prompt.
|
||||
*
|
||||
* clack has no hook for extra keys, but it calls `options` with the prompt as
|
||||
* `this`, which is all a subscription needs. Switching sections also has to
|
||||
* re-filter the list, and the prompt only recomputes `filteredOptions` when
|
||||
* the search text *changes* — hence the pair of userInput events: an
|
||||
* unmatchable string, then the real one, which recomputes against the new
|
||||
* section, resets the cursor onto its first match and leaves the typed query
|
||||
* on screen untouched. clack repaints as soon as the key handlers return.
|
||||
*
|
||||
* No `placeholder` is passed to the prompt on purpose: clack's own Tab binding
|
||||
* (fill the input with the placeholder) is inert without one.
|
||||
*/
|
||||
function hookTab(prompt: Autocomplete): void {
|
||||
if (hooked) return;
|
||||
hooked = true;
|
||||
prompt.on("key", (_char, key) => {
|
||||
if (key.name !== "tab") return;
|
||||
active = (active + 1) % sections.length;
|
||||
prompt.emit("userInput", NO_MATCH);
|
||||
prompt.emit("userInput", prompt.userInput);
|
||||
});
|
||||
}
|
||||
|
||||
// Widened, not asserted: clack resolves `undefined` when Enter lands on an
|
||||
// empty list, which its own types do not admit.
|
||||
const picked: Choice | symbol | undefined = await autocomplete<Choice>({
|
||||
// Getter, not a string: clack reads `message` on every repaint, so the tab
|
||||
// bar tracks the active section.
|
||||
get message(): string {
|
||||
const bar = sections
|
||||
.map((section, i) => {
|
||||
const text = `${section.label} (${section.options.length})`;
|
||||
return i === active ? styleText("cyan", `▸ ${text}`) : styleText("dim", text);
|
||||
})
|
||||
.join(styleText("dim", " · "));
|
||||
return `Pick a problem ${bar} ${styleText("dim", "Tab: next section")}`;
|
||||
},
|
||||
maxItems: 12,
|
||||
options(this: Autocomplete) {
|
||||
hookTab(this);
|
||||
return sections[active]!.options;
|
||||
},
|
||||
filter: (search, option) => {
|
||||
const haystack = option.label!.toLowerCase();
|
||||
return search
|
||||
@@ -90,10 +179,77 @@ if (isCancel(picked)) {
|
||||
cancel("Nothing picked.");
|
||||
process.exit(0);
|
||||
}
|
||||
if (picked === undefined) {
|
||||
// Enter on an empty section: nothing was focused, so there is nothing to do.
|
||||
cancel(`Nothing owed in the ${sections[active]!.label} section.`);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const proc = Bun.spawn(
|
||||
// bun installs workspace-dep bins into this package's node_modules, not the root's
|
||||
[join(import.meta.dir, "node_modules", ".bin", "leetcode"), "pick", picked.slug],
|
||||
{ cwd: ROOT, stdio: ["inherit", "inherit", "inherit"] },
|
||||
);
|
||||
process.exit(await proc.exited);
|
||||
// ── scaffold into the picked bucket ──────────────────────────────
|
||||
|
||||
// The active workspace names the config file; everything else about it belongs
|
||||
// to leetcode-cli.
|
||||
const registry = join(homedir(), ".leetcode", "workspaces.json");
|
||||
let workspace = "default";
|
||||
if (existsSync(registry)) {
|
||||
const parsed: unknown = JSON.parse(readFileSync(registry, "utf8"));
|
||||
if (parsed && typeof parsed === "object" && "active" in parsed && typeof parsed.active === "string") {
|
||||
workspace = parsed.active || workspace;
|
||||
}
|
||||
}
|
||||
const configPath = join(homedir(), ".leetcode", "workspaces", workspace, "config.json");
|
||||
if (!existsSync(configPath)) {
|
||||
log.error(`No leetcode-cli config at ${configPath} — run \`leetcode config -i\` once.`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Point leetcode-cli at one bucket. It reads its output directory from the
|
||||
* active workspace config and from nowhere else — no flag, no environment
|
||||
* override — so `workDir` is the whole handover.
|
||||
*
|
||||
* Each write MERGES the file as it is on disk at that moment; a saved copy is
|
||||
* never played back. The CLI owns this file too (theme, language, whatever a
|
||||
* `leetcode login` adds), and replaying stale bytes over it would silently
|
||||
* undo what it wrote while the child ran. After the pick, `workDir` is set to
|
||||
* work/1 instead of to whatever it was before: the first-solve bucket is the
|
||||
* one resting value that is always right, so even a killed run leaves a bare
|
||||
* `leetcode pick` on-layout.
|
||||
*/
|
||||
function setWorkDir(target: string): void {
|
||||
const raw: unknown = JSON.parse(readFileSync(configPath, "utf8"));
|
||||
if (raw === null || typeof raw !== "object") {
|
||||
log.error(`${configPath} holds no JSON object — run \`leetcode config -i\` to rewrite it.`);
|
||||
process.exit(1);
|
||||
}
|
||||
// 2-space JSON with a trailing newline: leetcode-cli's own format.
|
||||
writeFileSync(configPath, `${JSON.stringify({ ...raw, workDir: target }, null, 2)}\n`);
|
||||
}
|
||||
|
||||
const dir = bucketDir(picked.bucket);
|
||||
mkdirSync(dir, { recursive: true });
|
||||
setWorkDir(dir);
|
||||
|
||||
let code: number;
|
||||
try {
|
||||
const proc = Bun.spawn(
|
||||
// bun installs workspace-dep bins into this package's node_modules, not the root's
|
||||
[join(import.meta.dir, "node_modules", ".bin", "leetcode"), "pick", picked.slug],
|
||||
{ cwd: ROOT, stdio: ["inherit", "inherit", "inherit"] },
|
||||
);
|
||||
code = await proc.exited;
|
||||
} finally {
|
||||
setWorkDir(bucketDir(1));
|
||||
}
|
||||
|
||||
// leetcode-cli exits 0 even when it wrote nothing (an expired session only
|
||||
// prints a warning), so the scaffold itself is the acceptance test: without a
|
||||
// file for this problem in the bucket, the pick failed.
|
||||
if (!scanBucket(picked.bucket).has(picked.lc)) {
|
||||
log.error(
|
||||
`leetcode-cli scaffolded nothing for LC ${picked.lc} under work/${picked.bucket}/.\n` +
|
||||
"If it printed “Session expired”, run `leetcode login` and pick again.",
|
||||
);
|
||||
process.exit(code === 0 ? 1 : code);
|
||||
}
|
||||
process.exit(code);
|
||||
+10
-7
@@ -2,6 +2,11 @@
|
||||
* Shared work/ solution picker for the test and submit entries: fuzzy-select
|
||||
* a solution file, then hand it to leetcode-cli.
|
||||
*
|
||||
* Every bucket is listed — a 3-day or 7-day re-solve is tested and submitted
|
||||
* exactly like a first solve — and the hint says which one a file belongs to.
|
||||
* The db's per-solution timestamps are keyed by LC number, so the buckets of
|
||||
* one problem share them.
|
||||
*
|
||||
* Every run backfills the db's solutions table with created_at (from the
|
||||
* file's birthtime, mtime when the filesystem has none) so ordering works for
|
||||
* files that predate the db. Ordering is per command — test lists the most
|
||||
@@ -16,9 +21,7 @@ import { autocomplete, cancel, isCancel, log } from "@clack/prompts";
|
||||
import { statSync } from "node:fs";
|
||||
import { basename, join, relative } from "node:path";
|
||||
import { problemDb } from "./db";
|
||||
|
||||
const ROOT = join(import.meta.dir, "..", "..");
|
||||
const WORK_DIR = join(ROOT, "work");
|
||||
import { ROOT, WORK as WORK_DIR, parseWorkPath } from "./work";
|
||||
|
||||
/** Leading LC number of a work/ file, or undefined for unnumbered names. */
|
||||
function lcNumber(rel: string): number | undefined {
|
||||
@@ -70,12 +73,12 @@ export async function runOnSolution(command: "test" | "submit", message: string)
|
||||
placeholder: "Type to search...",
|
||||
maxItems: 12,
|
||||
options: files.map((f) => {
|
||||
// work layout: Difficulty/Category/<id>.<slug>.<ext>
|
||||
const [difficulty, category, name] = f.split("/");
|
||||
const parsed = parseWorkPath(f);
|
||||
const stage = parsed?.bucket === 1 ? "first solve" : `${parsed?.bucket}-day review`;
|
||||
return {
|
||||
value: f,
|
||||
label: name ?? f,
|
||||
hint: category ? `${difficulty} · ${category}` : difficulty,
|
||||
label: basename(f),
|
||||
hint: parsed ? `${stage} · ${parsed.difficulty} · ${parsed.category}` : f,
|
||||
};
|
||||
}),
|
||||
filter: (search, option) => {
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* Is a work/ file a real solution or just a scaffolded stub?
|
||||
*
|
||||
* `bun run pick` writes a statement header plus an empty function body, so
|
||||
* file existence alone means nothing: close-solved.ts must not close an issue
|
||||
* on a stub, and work.ts must not ask for the spaced-repetition re-solve of a
|
||||
* problem that was never solved in the first place.
|
||||
*
|
||||
* sync.ts keeps its own copy of the header split — it runs its whole pipeline
|
||||
* on import, so it cannot be imported from. Don't "deduplicate" that one.
|
||||
*
|
||||
* Library: side-effect-free on import.
|
||||
*/
|
||||
|
||||
/** Placeholder bodies that leetcode-cli / a human leaves behind. */
|
||||
const PLACEHOLDERS: Record<string, true> = { pass: true, "...": true, TODO: true };
|
||||
|
||||
/**
|
||||
* Decide whether a work/ file contains an implementation.
|
||||
*
|
||||
* The header comment is dropped the same way sync.ts splitSource() does it.
|
||||
* Comments must go before any brace analysis: the scaffold's JSDoc carries
|
||||
* `@param {number[]}`, whose braces would otherwise read as a body.
|
||||
*
|
||||
* A brace-language file counts as implemented when at least one *innermost*
|
||||
* brace pair holds real content. That distinguishes a bare stub
|
||||
* (`function(nums) {}`) and a class-shaped design stub (every method body
|
||||
* empty) from any genuine solution, whose innermost block always has code.
|
||||
* Every non-Python language the campaign has ever used is brace-shaped, so
|
||||
* "not .py" is the only branch that matters.
|
||||
*/
|
||||
export function isImplemented(src: string, lang: "js" | "py"): boolean {
|
||||
if (lang === "py") {
|
||||
const open = src.indexOf('"""');
|
||||
const close = src.indexOf('"""', open + 3);
|
||||
const code = open === -1 || close === -1 ? src : src.slice(close + 3);
|
||||
for (const raw of code.split("\n")) {
|
||||
const line = raw.replace(/#.*$/, "").trim();
|
||||
if (!line || PLACEHOLDERS[line]) continue;
|
||||
if (/^(?:@|def\s|class\s)/.test(line)) continue;
|
||||
return true; // a statement inside some def body
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const headerEnd = src.indexOf("*/");
|
||||
const body = headerEnd === -1 ? src : src.slice(headerEnd + 2);
|
||||
const code = body.replace(/\/\*[\s\S]*?\*\//g, " ").replace(/\/\/.*$/gm, " ");
|
||||
|
||||
let innermost = -1;
|
||||
for (let i = 0; i < code.length; i++) {
|
||||
if (code[i] === "{") {
|
||||
innermost = i;
|
||||
} else if (code[i] === "}" && innermost !== -1) {
|
||||
const inner = code.slice(innermost + 1, i).replace(/[\s;]/g, "");
|
||||
if (inner && !PLACEHOLDERS[inner]) return true;
|
||||
innermost = -1; // measured; the enclosing pair is not innermost
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
Executable
+384
@@ -0,0 +1,384 @@
|
||||
#!/usr/bin/env bun
|
||||
/**
|
||||
* Open today's spaced-repetition issue: whatever the SRS ladder has due,
|
||||
* linked straight to LeetCode.
|
||||
*
|
||||
* D1 is the schedule and this script is a renderer. `POST /admin/due` returns
|
||||
* exactly the rows the 8 AM digest mails — reviews standing at the `+3` and
|
||||
* `+7` rungs, oldest first — so the issue and the email can never disagree
|
||||
* about a day, and there is no second scheduler to drift. The rung is also
|
||||
* the `work/<n>` bucket the blind re-solve belongs in, which is the section
|
||||
* `bun run pick` opens on Tab.
|
||||
*
|
||||
* How a problem gets here: closing its issue (a push, a digest tap, a `/done`
|
||||
* comment) enters it on the ladder at `+3` with a concrete next_review, and
|
||||
* passing that review moves it to `+7`. Nothing is "activated" by this script
|
||||
* — it asks what is standing today and writes it down. A day's issue is keyed
|
||||
* by its title (`Spaced Repetition — <Month D, YYYY>`), so re-runs rewrite
|
||||
* that one body instead of stacking duplicates.
|
||||
*
|
||||
* Sunday writes nothing: the ladder never schedules the rest day (WINDOWS of
|
||||
* 3 and 7 exist for exactly that reason, see apps/api/src/srs.ts), so there is
|
||||
* nothing to render. Each rung shows at most WINDOW_CAP problems, with the
|
||||
* overflow listed as optional — the digest's leveller moves that overflow to
|
||||
* later working days the next morning.
|
||||
*
|
||||
* Links: D1 stores titles, not URLs, so each due problem's issue body is read
|
||||
* for the canonical LeetCode link. A body with no URL falls back to a slug
|
||||
* guessed from the title and is flagged in the report, because repo titles are
|
||||
* sometimes abbreviated ("LC 167 · Two Sum II") and a guess can 404.
|
||||
*
|
||||
* bun apps/cli/spaced-repetition.ts # create/update today's issue
|
||||
* bun apps/cli/spaced-repetition.ts --dry-run # print the body, touch nothing
|
||||
* bun apps/cli/spaced-repetition.ts --date=2026-09-02 # pretend it is that ET day
|
||||
*
|
||||
* Auth: GH_TOKEN / GITHUB_TOKEN, else falls back to `gh auth token`.
|
||||
* SRS_ADMIN_KEY reads the due list; SRS_API overrides the Worker URL for
|
||||
* local `wrangler dev` runs.
|
||||
*/
|
||||
import { WINDOWS, etDate, isRestDay } from "../api/src/srs.ts";
|
||||
import { github } from "./github.ts";
|
||||
import { markdownTable, printTable, writeStepSummary } from "./report.ts";
|
||||
|
||||
const DRY =
|
||||
process.argv.includes("--dry-run") ||
|
||||
process.env.DRY_RUN === "1" ||
|
||||
process.env.DRY_RUN === "true";
|
||||
|
||||
/**
|
||||
* Required re-solves per window: 3 + 3 on top of the day's 3 new core problems
|
||||
* is already a 90-minute session. A window that closed more than this (the
|
||||
* catalog backfill closed 19 issues in one day) keeps the rest listed under a
|
||||
* collapsed "optional" block rather than pretending they were never due.
|
||||
*/
|
||||
const WINDOW_CAP = 3;
|
||||
|
||||
const LABEL = "spaced-repetition";
|
||||
|
||||
// ── ET calendar dates ────────────────────────────────────────────
|
||||
|
||||
// Every date here is an ET calendar string (YYYY-MM-DD): the campaign runs on
|
||||
// ET days, and an issue closed at 21:30 ET belongs to that ET day, not to the
|
||||
// next UTC one. The helpers come from the Worker's SRS domain so this script,
|
||||
// the picker and D1 cannot disagree about a date, a window, or the rest day.
|
||||
|
||||
const LONG = new Intl.DateTimeFormat("en-US", {
|
||||
timeZone: "UTC",
|
||||
weekday: "long",
|
||||
month: "long",
|
||||
day: "numeric",
|
||||
year: "numeric",
|
||||
});
|
||||
|
||||
/** `2026-08-26` -> `August 26, 2026`, or with the weekday prefix. */
|
||||
function longDate(date: string, weekday = false): string {
|
||||
// Noon-UTC anchor, like every date in srs.ts: no DST edge can move the day.
|
||||
const text = LONG.format(new Date(`${date}T12:00:00Z`));
|
||||
return weekday ? text : text.slice(text.indexOf(", ") + 2);
|
||||
}
|
||||
|
||||
// ── today ────────────────────────────────────────────────────────
|
||||
|
||||
// `||`, not `??`: the workflow passes SRS_TODAY="" on scheduled runs, where the
|
||||
// input has no value.
|
||||
const override = process.argv.find((a) => a.startsWith("--date="))?.slice(7) || process.env.SRS_TODAY;
|
||||
if (override && !/^\d{4}-\d{2}-\d{2}$/.test(override)) {
|
||||
throw new Error(`--date wants YYYY-MM-DD, got ${override}`);
|
||||
}
|
||||
const today = override || etDate(new Date());
|
||||
|
||||
// Sunday is the campaign's rest day and the reason the windows are 3 and 7:
|
||||
// nothing is ever booked on it, so there is no issue to write. The cron still
|
||||
// fires — the guard lives here, not in the workflow, so a manual run agrees.
|
||||
if (isRestDay(today)) {
|
||||
console.log(`${today} is the rest day — no spaced-repetition issue.`);
|
||||
await writeStepSummary(`### Spaced Repetition — ${longDate(today)}\n\nRest day: nothing scheduled.\n`);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
// ── what is due today (D1, via the Worker) ───────────────────────
|
||||
|
||||
// The ladder is the schedule: `POST /admin/due` returns exactly the rows the
|
||||
// morning digest mails, so the issue and the email can never disagree about a
|
||||
// day. This script adds no scheduling of its own — it renders, caps, and
|
||||
// links.
|
||||
const SRS_API = process.env.SRS_API ?? "https://srs-api.prdlk.workers.dev";
|
||||
|
||||
/** One problem the ladder wants re-solved today, as the Worker reports it. */
|
||||
interface Due {
|
||||
lc: number;
|
||||
issue: number;
|
||||
title: string;
|
||||
difficulty: string;
|
||||
/** The rung being settled: "+3" or "+7". */
|
||||
stage: string;
|
||||
/** The rung's number — also the `work/<n>` bucket the re-solve belongs in. */
|
||||
bucket: number;
|
||||
due: string;
|
||||
late: number;
|
||||
last_seen: string | null;
|
||||
days_since: number | null;
|
||||
}
|
||||
|
||||
function readDue(value: unknown): Due | undefined {
|
||||
if (!value || typeof value !== "object") return;
|
||||
const num = (key: string): number | undefined =>
|
||||
key in value && typeof (value as Record<string, unknown>)[key] === "number"
|
||||
? ((value as Record<string, unknown>)[key] as number)
|
||||
: undefined;
|
||||
const str = (key: string): string | undefined =>
|
||||
key in value && typeof (value as Record<string, unknown>)[key] === "string"
|
||||
? ((value as Record<string, unknown>)[key] as string)
|
||||
: undefined;
|
||||
const lc = num("lc");
|
||||
const issue = num("issue");
|
||||
const bucket = num("bucket");
|
||||
const stage = str("stage");
|
||||
const title = str("title");
|
||||
const dueOn = str("due");
|
||||
if (lc === undefined || issue === undefined || bucket === undefined) return;
|
||||
if (stage === undefined || title === undefined || dueOn === undefined) return;
|
||||
const difficulty = str("difficulty") ?? "unrated";
|
||||
return {
|
||||
lc,
|
||||
issue,
|
||||
title,
|
||||
difficulty: difficulty.charAt(0).toUpperCase() + difficulty.slice(1),
|
||||
stage,
|
||||
bucket,
|
||||
due: dueOn,
|
||||
late: num("late") ?? 0,
|
||||
last_seen: str("last_seen") ?? null,
|
||||
days_since: num("days_since") ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
if (!process.env.SRS_ADMIN_KEY) {
|
||||
// Failing loudly beats writing an issue from a second, guessed schedule:
|
||||
// there is only one schedule now, and it lives in D1.
|
||||
console.error("SRS_ADMIN_KEY unset — cannot read today's due list from the Worker.");
|
||||
process.exit(1);
|
||||
}
|
||||
const res = await fetch(`${SRS_API}/admin/due?date=${today}`, {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${process.env.SRS_ADMIN_KEY}` },
|
||||
});
|
||||
if (!res.ok) throw new Error(`GET due list -> ${res.status} ${await res.text()}`);
|
||||
const payload: unknown = await res.json();
|
||||
const dueRaw: unknown = payload && typeof payload === "object" && "due" in payload ? payload.due : null;
|
||||
const due: Due[] = (Array.isArray(dueRaw) ? dueRaw : []).flatMap((r) => {
|
||||
const row = readDue(r);
|
||||
return row ? [row] : [];
|
||||
});
|
||||
|
||||
// ── repo + auth ──────────────────────────────────────────────────
|
||||
|
||||
const gh = await github();
|
||||
|
||||
// ── canonical LeetCode links ─────────────────────────────────────
|
||||
|
||||
const LC_URL = /https:\/\/leetcode\.com\/problems\/[a-z0-9-]+/;
|
||||
|
||||
/** LeetCode's own slug shape, for bodies that lost their URL line. */
|
||||
function slugify(name: string): string {
|
||||
return name
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-|-$/g, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* D1 stores titles, not URLs, so each due problem's issue body is read for the
|
||||
* canonical LeetCode link written by the campaign-issues convention. That is
|
||||
* one request per due problem — at most REVIEW_CAP per rung — instead of the
|
||||
* old walk over every closed issue in the repo. A body with no URL falls back
|
||||
* to a slug guessed from the title and is flagged in the report, because repo
|
||||
* titles are sometimes abbreviated ("LC 167 · Two Sum II") and a guess can 404.
|
||||
*/
|
||||
interface Linked extends Due {
|
||||
url: string;
|
||||
linked: boolean;
|
||||
}
|
||||
|
||||
async function link(row: Due): Promise<Linked> {
|
||||
let url: string | undefined;
|
||||
try {
|
||||
const issue: unknown = await gh.api(`/repos/${gh.repo}/issues/${row.issue}`);
|
||||
const body =
|
||||
issue && typeof issue === "object" && "body" in issue && typeof issue.body === "string"
|
||||
? issue.body
|
||||
: "";
|
||||
url = LC_URL.exec(body)?.[0];
|
||||
} catch (err) {
|
||||
console.warn(`#${row.issue}: could not read the issue body (${err})`);
|
||||
}
|
||||
return {
|
||||
...row,
|
||||
url: `${url ?? `https://leetcode.com/problems/${slugify(row.title)}`}/`,
|
||||
linked: url !== undefined,
|
||||
};
|
||||
}
|
||||
|
||||
// ── issue body ───────────────────────────────────────────────────
|
||||
|
||||
const title = `Spaced Repetition — ${longDate(today)}`;
|
||||
|
||||
/** The window's due problems, capped, oldest scheduled first. */
|
||||
const byWindow = new Map<number, Linked[]>();
|
||||
for (const days of WINDOWS) {
|
||||
const rows = due.filter((d) => d.bucket === days);
|
||||
byWindow.set(days, await Promise.all(rows.map(link)));
|
||||
}
|
||||
|
||||
function bucket(days: number): Linked[] {
|
||||
return byWindow.get(days) ?? [];
|
||||
}
|
||||
|
||||
/** One checkbox line, straight to LeetCode. */
|
||||
function line(s: Linked, box: boolean): string {
|
||||
const seen = s.days_since === null ? "unlogged" : `last seen ${s.days_since}d ago`;
|
||||
return (
|
||||
`${box ? "- [ ] " : "- "}[LC ${s.lc} · ${s.title}](${s.url}) · ${s.difficulty} · #${s.issue}` +
|
||||
` · ${seen}${s.late > 0 ? ` · ⏰ ${s.late}d late` : ""}` +
|
||||
(s.linked ? "" : " · ⚠️ link guessed from title")
|
||||
);
|
||||
}
|
||||
|
||||
const sections = WINDOWS.map((days) => {
|
||||
const rows = bucket(days);
|
||||
const required = rows.slice(0, WINDOW_CAP);
|
||||
const spill = rows.slice(WINDOW_CAP);
|
||||
return [
|
||||
`### +${days} days — re-solve into \`work/${days}/\``,
|
||||
"",
|
||||
...(required.length
|
||||
? required.map((s) => line(s, true))
|
||||
: [`_Nothing at the +${days} rung today._`]),
|
||||
// Overflow is shown, not dropped: the ladder levels everything past the
|
||||
// cap onto later working days, but until that morning's digest runs this
|
||||
// issue is the only record of what was standing.
|
||||
...(spill.length
|
||||
? [
|
||||
"",
|
||||
`<details><summary>${spill.length} more at this rung — optional</summary>`,
|
||||
"",
|
||||
...spill.map((s) => line(s, false)),
|
||||
"",
|
||||
"</details>",
|
||||
]
|
||||
: []),
|
||||
"",
|
||||
].join("\n");
|
||||
});
|
||||
|
||||
const total = WINDOWS.reduce((n, days) => n + Math.min(bucket(days).length, WINDOW_CAP), 0);
|
||||
|
||||
const body = [
|
||||
`Re-solve from memory, ${longDate(today, true)}. Blind: no notes, no \`work/\` file, no editor history.`,
|
||||
"",
|
||||
"- 15 minutes per problem, then stop and read your own solution.",
|
||||
"- Say the invariant and the complexity out loud before typing.",
|
||||
"- Failed one? Tick it anyway and expect it back at +3.",
|
||||
"- `bun run pick` → Tab to this rung's section scaffolds the blind re-solve.",
|
||||
"",
|
||||
...sections,
|
||||
"<sub>Today's due list straight from the SRS ladder in D1 (`POST /admin/due`), rendered by " +
|
||||
"`.github/workflows/spaced-repetition.yml` — re-runs on the same day rewrite this body. " +
|
||||
"The ladder never schedules a Sunday, so there is no issue on the rest day.</sub>",
|
||||
].join("\n");
|
||||
|
||||
// ── create or refresh today's issue ──────────────────────────────
|
||||
|
||||
interface Existing {
|
||||
number: number;
|
||||
title: string;
|
||||
body: string;
|
||||
}
|
||||
|
||||
function readExisting(value: unknown): Existing | undefined {
|
||||
if (!value || typeof value !== "object") return;
|
||||
if ("pull_request" in value) return;
|
||||
if (!("number" in value) || typeof value.number !== "number") return;
|
||||
if (!("title" in value) || typeof value.title !== "string") return;
|
||||
const text = "body" in value && typeof value.body === "string" ? value.body : "";
|
||||
return { number: value.number, title: value.title, body: text };
|
||||
}
|
||||
|
||||
// state=all: a day's issue that was already closed must not be recreated.
|
||||
let existing: Existing | undefined;
|
||||
for await (const raw of gh.list(`/repos/${gh.repo}/issues?labels=${LABEL}&state=all`)) {
|
||||
const row = readExisting(raw);
|
||||
if (row?.title === title) {
|
||||
existing = row;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let status: string;
|
||||
if (total === 0) {
|
||||
status = existing
|
||||
? `nothing due — left #${existing.number} alone`
|
||||
: "nothing due — no issue created";
|
||||
} else if (existing && existing.body.trim() === body.trim()) {
|
||||
status = `#${existing.number} already current`;
|
||||
} else if (DRY) {
|
||||
status = existing ? `would update #${existing.number}` : "would create";
|
||||
} else if (existing) {
|
||||
await gh.api(`/repos/${gh.repo}/issues/${existing.number}`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify({ body }),
|
||||
});
|
||||
status = `updated #${existing.number}`;
|
||||
} else {
|
||||
// Ensure the label exists before it is used (422 = someone already made it).
|
||||
try {
|
||||
await gh.api(`/repos/${gh.repo}/labels`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
name: LABEL,
|
||||
color: "0E8A16",
|
||||
description: "Daily blind re-solve of whatever the SRS ladder has due",
|
||||
}),
|
||||
});
|
||||
} catch (err) {
|
||||
if (!String(err).includes("422")) throw err;
|
||||
}
|
||||
|
||||
const created = (await gh.api(`/repos/${gh.repo}/issues`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ title, body, labels: [LABEL] }),
|
||||
})) as { number: number };
|
||||
status = `created #${created.number}`;
|
||||
}
|
||||
|
||||
// ── report ───────────────────────────────────────────────────────
|
||||
|
||||
const report = WINDOWS.flatMap((days) =>
|
||||
bucket(days).map((s, i) => [
|
||||
`+${days}d`,
|
||||
String(s.lc),
|
||||
`#${s.issue}`,
|
||||
s.difficulty,
|
||||
s.due + (s.late > 0 ? ` (${s.late}d late)` : ""),
|
||||
i < WINDOW_CAP ? "due" : "optional",
|
||||
s.linked ? s.url : `${s.url} (inferred)`,
|
||||
]),
|
||||
);
|
||||
const rows = [["rung", "lc", "issue", "diff", "scheduled", "state", "leetcode"], ...report];
|
||||
if (report.length) printTable(rows);
|
||||
|
||||
console.log(
|
||||
`\n${title}${DRY ? " (dry run)" : ""}\n` +
|
||||
WINDOWS.map((days) => {
|
||||
const n = bucket(days).length;
|
||||
return `+${days}d: ${Math.min(n, WINDOW_CAP)} due${n > WINDOW_CAP ? ` (+${n - WINDOW_CAP} optional)` : ""}`;
|
||||
}).join(" · ") +
|
||||
`\n${status}`,
|
||||
);
|
||||
if (DRY) console.log(`\n${body}`);
|
||||
|
||||
await writeStepSummary(
|
||||
`### ${title}${DRY ? " (dry run)" : ""}\n\n` +
|
||||
`${total} problem${total === 1 ? "" : "s"} due · ${status}\n\n` +
|
||||
(report.length ? `${markdownTable(rows)}\n` : "The ladder has nothing due today.\n"),
|
||||
);
|
||||
+7
-3
@@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env bun
|
||||
/**
|
||||
* Sync work/ leetcode solutions into apps/docs/content/ pages.
|
||||
* Sync work/1 leetcode solutions into apps/docs/content/ pages.
|
||||
*
|
||||
* - New problems get a full page (frontmatter, badge, warning, examples,
|
||||
* constraints, solution) in the gold-standard format.
|
||||
@@ -9,12 +9,16 @@
|
||||
* - When a problem is solved in both JavaScript and Python the solution
|
||||
* renders as a <CodeGroup> (Python first); single-language solutions
|
||||
* render as a plain fence.
|
||||
*
|
||||
* Only the first-solve bucket is read: work/3 and work/7 hold blind re-solves
|
||||
* of problems whose page already exists (see work.ts), and a fresh scaffold
|
||||
* there would otherwise wipe the page's `## Solution`.
|
||||
*/
|
||||
import { mkdir, rename } from "node:fs/promises";
|
||||
import { basename, join } from "node:path";
|
||||
|
||||
const ROOT = join(import.meta.dir, "..", "..");
|
||||
const WORK = join(ROOT, "work");
|
||||
const WORK = join(ROOT, "work", "1");
|
||||
const DOCS = join(ROOT, "apps", "docs", "content");
|
||||
|
||||
type Lang = "js" | "py";
|
||||
@@ -323,7 +327,7 @@ for await (const rel of new Bun.Glob("**/*.{js,py}").scan(WORK)) {
|
||||
const file = basename(rel);
|
||||
const m = file.match(/^(\d+)\.(.+)\.(?:js|py)$/);
|
||||
if (!m) {
|
||||
console.warn(`skip (unrecognized name): work/${rel}`);
|
||||
console.warn(`skip (unrecognized name): work/1/${rel}`);
|
||||
continue;
|
||||
}
|
||||
const num = Number(m[1]);
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
/**
|
||||
* The work/ layout: one directory per spaced-repetition window.
|
||||
*
|
||||
* work/1/<Difficulty>/<Category>/<num>.<slug>.<ext> first solve
|
||||
* work/3/<Difficulty>/<Category>/<num>.<slug>.<ext> 3-day blind re-solve
|
||||
* work/7/<Difficulty>/<Category>/<num>.<slug>.<ext> 7-day blind re-solve
|
||||
*
|
||||
* The bucket name is the review window in days — the same +3/+7 windows the
|
||||
* campaign's `Spaced Repetition — <date>` issues use (WINDOWS in
|
||||
* spaced-repetition.ts). Below the bucket the layout is leetcode-cli's own
|
||||
* `workDir/Difficulty/Category/` shape, so a re-solve lands beside its first
|
||||
* solve under a different bucket.
|
||||
*
|
||||
* A window is *owed* when the first solve is at least that many days old and
|
||||
* the bucket has no file for that problem yet. Reconciled from the filesystem
|
||||
* on every run the way close-solved.ts reconciles issues: no state file, no
|
||||
* bookkeeping, and a re-solve closes its window just by existing — presence,
|
||||
* not content, so a stub in work/3 counts as done the same way `bun run pick`
|
||||
* treats a scaffold under work/1 as picked. The first solve is the one place
|
||||
* content is read: an empty scaffold in work/1 owes nothing, it is simply
|
||||
* unsolved (isImplemented() in source.ts, the same gate close-solved.ts uses
|
||||
* before it closes an issue).
|
||||
*
|
||||
* "First solve" is the ET date of the commit that first added the problem's
|
||||
* work/ file — the same push that closes its problem issue and therefore
|
||||
* starts the campaign's +3/+7 windows. An uncommitted solution has no date and
|
||||
* is never owed a review yet: you just solved it. ET dates and the date
|
||||
* arithmetic come from apps/api/src/srs.ts so the local picker and D1 cannot
|
||||
* disagree about what day it is.
|
||||
*
|
||||
* Library: side-effect-free on import — nothing scans or shells out until a
|
||||
* function is called.
|
||||
*/
|
||||
import { readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { WINDOWS, type Window, daysBetween } from "../api/src/srs.ts";
|
||||
import { isImplemented } from "./source.ts";
|
||||
|
||||
export const ROOT = join(import.meta.dir, "..", "..");
|
||||
export const WORK = join(ROOT, "work");
|
||||
|
||||
// The windows are the SRS ladder's rungs: srs.ts defines them once and the
|
||||
// bucket directories are named after them. Re-exported so the picker needs
|
||||
// only this module to know the work/ layout.
|
||||
export { WINDOWS, type Window };
|
||||
|
||||
/** work/1 is the first solve, the rest are the review windows. */
|
||||
export const BUCKETS = [1, ...WINDOWS] as const;
|
||||
export type Bucket = (typeof BUCKETS)[number];
|
||||
const BUCKET_BY_DIR: Record<string, Bucket> = { "1": 1, "3": 3, "7": 7 };
|
||||
|
||||
export function bucketDir(bucket: Bucket): string {
|
||||
return join(WORK, String(bucket));
|
||||
}
|
||||
|
||||
export interface WorkFile {
|
||||
lc: number;
|
||||
slug: string;
|
||||
bucket: Bucket;
|
||||
/** Path relative to work/, bucket included. */
|
||||
rel: string;
|
||||
difficulty: string;
|
||||
category: string;
|
||||
}
|
||||
|
||||
/** `<num>.<slug>.<ext>` — the only file name the campaign scripts parse. */
|
||||
function parseName(name: string): { lc: number; slug: string } | null {
|
||||
const m = name.match(/^(\d+)\.(.+)\.[A-Za-z0-9]+$/);
|
||||
return m ? { lc: Number(m[1]), slug: m[2]! } : null;
|
||||
}
|
||||
|
||||
/** Parse `1/Medium/Array/15.3sum.py` — null for anything off-layout. */
|
||||
export function parseWorkPath(rel: string): WorkFile | null {
|
||||
const parts = rel.split("/");
|
||||
const name = parts.pop();
|
||||
const bucket = BUCKET_BY_DIR[parts[0] ?? ""];
|
||||
if (name === undefined || bucket === undefined) return null;
|
||||
const parsed = parseName(name);
|
||||
if (!parsed) return null;
|
||||
return { ...parsed, bucket, rel, difficulty: parts[1] ?? "", category: parts[2] ?? "" };
|
||||
}
|
||||
|
||||
/** LC number -> its files in that bucket (a problem may have both js and py). */
|
||||
export function scanBucket(bucket: Bucket): Map<number, WorkFile[]> {
|
||||
const files = new Map<number, WorkFile[]>();
|
||||
for (const name of new Bun.Glob("**/*.*").scanSync({ cwd: bucketDir(bucket) })) {
|
||||
const file = parseWorkPath(`${bucket}/${name}`);
|
||||
if (!file) continue;
|
||||
const found = files.get(file.lc);
|
||||
if (found) found.push(file);
|
||||
else files.set(file.lc, [file]);
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
/**
|
||||
* LC number -> ET date of the commit that first added a work/ file for it.
|
||||
*
|
||||
* One `git log` over the whole of work/, oldest commit first, so the first
|
||||
* date seen for a problem wins. Keyed by LC number rather than by path, which
|
||||
* makes every past reshuffle of the directory layout — including the move into
|
||||
* work/1 — irrelevant: the original add still counts. TZ + `format-local`
|
||||
* put the dates on the ET calendar srs.ts speaks.
|
||||
*/
|
||||
export function firstSolved(): Map<number, string> {
|
||||
const git = Bun.spawnSync(
|
||||
[
|
||||
"git",
|
||||
"log",
|
||||
"--reverse",
|
||||
"--no-merges",
|
||||
"--diff-filter=A",
|
||||
"--date=format-local:%Y-%m-%d",
|
||||
"--format=%ad",
|
||||
"--name-only",
|
||||
"--",
|
||||
"work",
|
||||
],
|
||||
{ cwd: ROOT, env: { ...process.env, TZ: "America/New_York" } },
|
||||
);
|
||||
if (git.exitCode !== 0) {
|
||||
throw new Error(`git log failed: ${git.stderr.toString().trim()}`);
|
||||
}
|
||||
|
||||
const dates = new Map<number, string>();
|
||||
let date = "";
|
||||
for (const line of git.stdout.toString().split("\n")) {
|
||||
if (/^\d{4}-\d{2}-\d{2}$/.test(line)) {
|
||||
date = line;
|
||||
continue;
|
||||
}
|
||||
const parsed = line === "" ? null : parseName(line.slice(line.lastIndexOf("/") + 1));
|
||||
if (parsed && !dates.has(parsed.lc)) dates.set(parsed.lc, date);
|
||||
}
|
||||
return dates;
|
||||
}
|
||||
|
||||
export interface Owed extends WorkFile {
|
||||
/** ET date of the first solve. */
|
||||
solved: string;
|
||||
/** Days since the first solve — at least the window. */
|
||||
days: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Both review windows for `today`, oldest solve first.
|
||||
*
|
||||
* Uncapped, unlike the review issue's WINDOW_CAP: the issue is one day's
|
||||
* assignment, this is everything still owed. A window skipped for a day stays
|
||||
* on the list until its file exists.
|
||||
*/
|
||||
export function reviewQueues(today: string): Map<Window, Owed[]> {
|
||||
const dates = firstSolved();
|
||||
|
||||
// An empty scaffold under work/1 is a problem still unsolved, not one owing
|
||||
// a review — the same call close-solved.ts makes before it closes an issue.
|
||||
const solved: { file: WorkFile; date: string }[] = [];
|
||||
for (const files of scanBucket(1).values()) {
|
||||
const date = dates.get(files[0]!.lc);
|
||||
if (date === undefined) continue; // uncommitted: you only just solved it
|
||||
const file = files.find((f) =>
|
||||
isImplemented(readFileSync(join(WORK, f.rel), "utf8"), f.rel.endsWith(".py") ? "py" : "js"),
|
||||
);
|
||||
if (file) solved.push({ file, date });
|
||||
}
|
||||
|
||||
const queues = new Map<Window, Owed[]>();
|
||||
for (const window of WINDOWS) {
|
||||
const done = scanBucket(window);
|
||||
const owed: Owed[] = [];
|
||||
for (const { file, date } of solved) {
|
||||
if (done.has(file.lc)) continue;
|
||||
const days = daysBetween(date, today);
|
||||
if (days >= window) owed.push({ ...file, solved: date, days });
|
||||
}
|
||||
owed.sort((a, b) => b.days - a.days || a.lc - b.lc);
|
||||
queues.set(window, owed);
|
||||
}
|
||||
return queues;
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
---
|
||||
title: '141. Linked List Cycle'
|
||||
description: Given head, the head of a linked list, determine if the linked list has a cycle in it
|
||||
sidebar:
|
||||
label: 'Linked List Cycle'
|
||||
badge: 'Easy'
|
||||
---
|
||||
|
||||
<Badge variant="accent">Linked List</Badge>
|
||||
|
||||
::::warning
|
||||
Can you solve it using O(1) (i.e. constant) memory?
|
||||
::::
|
||||
|
||||
### Example 1:
|
||||
- Input: `head = [3,2,0,-4], pos = 1`
|
||||
- Output: `true`
|
||||
- Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
|
||||
|
||||
### Example 2:
|
||||
- Input: `head = [1,2], pos = 0`
|
||||
- Output: `true`
|
||||
- Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.
|
||||
|
||||
### Example 3:
|
||||
- Input: `head = [1], pos = -1`
|
||||
- Output: `false`
|
||||
- Explanation: There is no cycle in the linked list.
|
||||
|
||||
### Constraints:
|
||||
|
||||
- The number of the nodes in the list is in the range [0, 10^4].
|
||||
- `-10^5 <= Node.val <= 10^5`
|
||||
- pos is -1 or a valid index in the linked-list.
|
||||
|
||||
## Solution
|
||||
|
||||
```py
|
||||
# Definition for singly-linked list.
|
||||
# class ListNode:
|
||||
# def __init__(self, x):
|
||||
# self.val = x
|
||||
# self.next = None
|
||||
|
||||
|
||||
class Solution:
|
||||
def hasCycle(self, head: Optional[ListNode]) -> bool:
|
||||
fast = slow = head
|
||||
|
||||
while fast and fast.next:
|
||||
fast = fast.next.next
|
||||
slow = slow.next
|
||||
if fast is slow:
|
||||
return True
|
||||
return False
|
||||
```
|
||||
@@ -0,0 +1,50 @@
|
||||
---
|
||||
title: '206. Reverse Linked List'
|
||||
description: Given the head of a singly linked list, reverse the list, and return the reversed list
|
||||
sidebar:
|
||||
label: 'Reverse Linked List'
|
||||
badge: 'Easy'
|
||||
---
|
||||
|
||||
<Badge variant="accent">Linked List</Badge>
|
||||
|
||||
::::warning
|
||||
A linked list can be reversed either iteratively or recursively. Could you implement both?
|
||||
::::
|
||||
|
||||
### Example 1:
|
||||
- Input: `head = [1,2,3,4,5]`
|
||||
- Output: `[5,4,3,2,1]`
|
||||
|
||||
### Example 2:
|
||||
- Input: `head = [1,2]`
|
||||
- Output: `[2,1]`
|
||||
|
||||
### Example 3:
|
||||
- Input: `head = []`
|
||||
- Output: `[]`
|
||||
|
||||
### Constraints:
|
||||
|
||||
- The number of nodes in the list is the range [0, 5000].
|
||||
- `-5000 <= Node.val <= 5000`
|
||||
|
||||
## Solution
|
||||
|
||||
```py
|
||||
# Definition for singly-linked list.
|
||||
# class ListNode:
|
||||
# def __init__(self, val=0, next=None):
|
||||
# self.val = val
|
||||
# self.next = next
|
||||
class Solution:
|
||||
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
|
||||
prev = None
|
||||
curr = head
|
||||
while curr:
|
||||
next_ = curr.next
|
||||
curr.next = prev
|
||||
prev = curr
|
||||
curr = next_
|
||||
return prev
|
||||
```
|
||||
@@ -0,0 +1,66 @@
|
||||
---
|
||||
title: '21. Merge Two Sorted Lists'
|
||||
description: You are given the heads of two sorted linked lists list1 and list2
|
||||
sidebar:
|
||||
label: 'Merge Two Sorted Lists'
|
||||
badge: 'Easy'
|
||||
---
|
||||
|
||||
<Badge variant="accent">Linked List</Badge>
|
||||
|
||||
### Example 1:
|
||||
- Input: `list1 = [1,2,4], list2 = [1,3,4]`
|
||||
- Output: `[1,1,2,3,4,4]`
|
||||
|
||||
### Example 2:
|
||||
- Input: `list1 = [], list2 = []`
|
||||
- Output: `[]`
|
||||
|
||||
### Example 3:
|
||||
- Input: `list1 = [], list2 = [0]`
|
||||
- Output: `[0]`
|
||||
|
||||
### Constraints:
|
||||
|
||||
- The number of nodes in both lists is in the range [0, 50].
|
||||
- `-100 <= Node.val <= 100`
|
||||
- Both list1 and list2 are sorted in non-decreasing order.
|
||||
|
||||
## Solution
|
||||
|
||||
```py
|
||||
# Definition for singly-linked list.
|
||||
# class ListNode:
|
||||
# def __init__(self, val=0, next=None):
|
||||
# self.val = val
|
||||
# self.next = next
|
||||
class Solution:
|
||||
def mergeTwoLists(
|
||||
self, list1: Optional[ListNode], list2: Optional[ListNode]
|
||||
) -> Optional[ListNode]:
|
||||
|
||||
if not list1:
|
||||
return list2
|
||||
if not list2:
|
||||
return list1
|
||||
|
||||
if list1.val < list2.val:
|
||||
head = list1
|
||||
list1 = list1.next
|
||||
else:
|
||||
head = list2
|
||||
list2 = list2.next
|
||||
|
||||
current = head
|
||||
while list1 and list2:
|
||||
if list1.val < list2.val:
|
||||
current.next = list1
|
||||
list1 = list1.next
|
||||
else:
|
||||
current.next = list2
|
||||
list2 = list2.next
|
||||
current = current.next
|
||||
|
||||
current.next = list1 or list2
|
||||
return head
|
||||
```
|
||||
@@ -17,7 +17,9 @@ const API_BASE = "https://srs-api.prdlk.workers.dev";
|
||||
|
||||
// ── /api/stats response shape ────────────────────────────────────
|
||||
|
||||
const STAGES = ["new", "+2", "+5", "+10", "retired"] as const;
|
||||
// Mirrors STAGES in apps/api/src/srs.ts — the ladder rungs, in order. The
|
||||
// Worker ships every rung in `ladder`, zeros included.
|
||||
const STAGES = ["new", "+3", "+7", "retired"] as const;
|
||||
|
||||
type Stage = (typeof STAGES)[number];
|
||||
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
[2026-08-26T19:15:12.457Z] [SHUTDOWN] before-quit fired
|
||||
[2026-08-26T19:15:12.458Z] [SHUTDOWN] shutdown started
|
||||
[2026-08-26T19:15:12.458Z] [SHUTDOWN] Stopping local daemon server early
|
||||
[2026-08-26T19:15:12.458Z] [SHUTDOWN] Phase 1: sending Ctrl+C to all terminals
|
||||
[2026-08-26T19:15:12.459Z] [SHUTDOWN] Signaled 1 terminals: __pane_chat_terminal__
|
||||
[2026-08-26T19:15:12.659Z] [SHUTDOWN] Sent second Ctrl+C, waiting 2s...
|
||||
[2026-08-26T19:15:14.660Z] [SHUTDOWN] 2s wait complete
|
||||
[2026-08-26T19:15:14.660Z] [SHUTDOWN] Phase 2: saving terminal states
|
||||
[2026-08-26T19:15:14.670Z] [SHUTDOWN] ERROR during shutdown: BoundaryDecodeError: input.wasInterrupted: expected JSON value
|
||||
[2026-08-26T19:15:14.671Z] [SHUTDOWN] Calling app.exit(0)
|
||||
@@ -10,6 +10,7 @@
|
||||
"close-solved": "bun apps/cli/close-solved.ts",
|
||||
"close-topics": "bun apps/cli/close-topics.ts",
|
||||
"sync-project-fields": "bun apps/cli/sync-project-fields.ts",
|
||||
"spaced-repetition": "bun apps/cli/spaced-repetition.ts",
|
||||
"api:dev": "cd apps/api && bun run dev",
|
||||
"api:deploy": "cd apps/api && bun run deploy",
|
||||
"api:test": "cd apps/api && bun test src",
|
||||
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,73 @@
|
||||
"""
|
||||
141. Linked List Cycle
|
||||
Difficulty: Easy
|
||||
https://leetcode.com/problems/linked-list-cycle/
|
||||
|
||||
──────────────────────────────────────────────────
|
||||
|
||||
Given head, the head of a linked list, determine if the linked list
|
||||
has a cycle in it.
|
||||
|
||||
There is a cycle in a linked list if there is some node in the list
|
||||
that can be reached again by continuously following the next pointer.
|
||||
Internally, pos is used to denote the index of the node that tail's
|
||||
next pointer is connected to. Note that pos is not passed as a
|
||||
parameter.
|
||||
|
||||
Return true if there is a cycle in the linked list. Otherwise, return
|
||||
false.
|
||||
|
||||
|
||||
|
||||
Example 1:
|
||||
|
||||
Input: head = [3,2,0,-4], pos = 1
|
||||
Output: true
|
||||
Explanation: There is a cycle in the linked list, where the tail
|
||||
connects to the 1st node (0-indexed).
|
||||
|
||||
Example 2:
|
||||
|
||||
Input: head = [1,2], pos = 0
|
||||
Output: true
|
||||
Explanation: There is a cycle in the linked list, where the tail
|
||||
connects to the 0th node.
|
||||
|
||||
Example 3:
|
||||
|
||||
Input: head = [1], pos = -1
|
||||
Output: false
|
||||
Explanation: There is no cycle in the linked list.
|
||||
|
||||
|
||||
|
||||
Constraints:
|
||||
|
||||
• The number of the nodes in the list is in the range [0, 10^4].
|
||||
|
||||
• -10^5 <= Node.val <= 10^5
|
||||
|
||||
• pos is -1 or a valid index in the linked-list.
|
||||
|
||||
|
||||
|
||||
Follow up: Can you solve it using O(1) (i.e. constant) memory?
|
||||
"""
|
||||
|
||||
# Definition for singly-linked list.
|
||||
# class ListNode:
|
||||
# def __init__(self, x):
|
||||
# self.val = x
|
||||
# self.next = None
|
||||
|
||||
|
||||
class Solution:
|
||||
def hasCycle(self, head: Optional[ListNode]) -> bool:
|
||||
fast = slow = head
|
||||
|
||||
while fast and fast.next:
|
||||
fast = fast.next.next
|
||||
slow = slow.next
|
||||
if fast is slow:
|
||||
return True
|
||||
return False
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,57 @@
|
||||
"""
|
||||
206. Reverse Linked List
|
||||
Difficulty: Easy
|
||||
https://leetcode.com/problems/reverse-linked-list/
|
||||
|
||||
──────────────────────────────────────────────────
|
||||
|
||||
Given the head of a singly linked list, reverse the list, and return
|
||||
the reversed list.
|
||||
|
||||
|
||||
|
||||
Example 1:
|
||||
|
||||
Input: head = [1,2,3,4,5]
|
||||
Output: [5,4,3,2,1]
|
||||
|
||||
Example 2:
|
||||
|
||||
Input: head = [1,2]
|
||||
Output: [2,1]
|
||||
|
||||
Example 3:
|
||||
|
||||
Input: head = []
|
||||
Output: []
|
||||
|
||||
|
||||
|
||||
Constraints:
|
||||
|
||||
• The number of nodes in the list is the range [0, 5000].
|
||||
|
||||
• -5000 <= Node.val <= 5000
|
||||
|
||||
|
||||
|
||||
Follow up: A linked list can be reversed either iteratively or
|
||||
recursively. Could you implement both?
|
||||
"""
|
||||
|
||||
|
||||
# Definition for singly-linked list.
|
||||
# class ListNode:
|
||||
# def __init__(self, val=0, next=None):
|
||||
# self.val = val
|
||||
# self.next = next
|
||||
class Solution:
|
||||
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
|
||||
prev = None
|
||||
curr = head
|
||||
while curr:
|
||||
next_ = curr.next
|
||||
curr.next = prev
|
||||
prev = curr
|
||||
curr = next_
|
||||
return prev
|
||||
@@ -0,0 +1,77 @@
|
||||
"""
|
||||
21. Merge Two Sorted Lists
|
||||
Difficulty: Easy
|
||||
https://leetcode.com/problems/merge-two-sorted-lists/
|
||||
|
||||
──────────────────────────────────────────────────
|
||||
|
||||
You are given the heads of two sorted linked lists list1 and list2.
|
||||
|
||||
Merge the two lists into one sorted list. The list should be made by
|
||||
splicing together the nodes of the first two lists.
|
||||
|
||||
Return the head of the merged linked list.
|
||||
|
||||
|
||||
|
||||
Example 1:
|
||||
|
||||
Input: list1 = [1,2,4], list2 = [1,3,4]
|
||||
Output: [1,1,2,3,4,4]
|
||||
|
||||
Example 2:
|
||||
|
||||
Input: list1 = [], list2 = []
|
||||
Output: []
|
||||
|
||||
Example 3:
|
||||
|
||||
Input: list1 = [], list2 = [0]
|
||||
Output: [0]
|
||||
|
||||
|
||||
|
||||
Constraints:
|
||||
|
||||
• The number of nodes in both lists is in the range [0, 50].
|
||||
|
||||
• -100 <= Node.val <= 100
|
||||
|
||||
• Both list1 and list2 are sorted in non-decreasing order.
|
||||
"""
|
||||
|
||||
|
||||
# Definition for singly-linked list.
|
||||
# class ListNode:
|
||||
# def __init__(self, val=0, next=None):
|
||||
# self.val = val
|
||||
# self.next = next
|
||||
class Solution:
|
||||
def mergeTwoLists(
|
||||
self, list1: Optional[ListNode], list2: Optional[ListNode]
|
||||
) -> Optional[ListNode]:
|
||||
|
||||
if not list1:
|
||||
return list2
|
||||
if not list2:
|
||||
return list1
|
||||
|
||||
if list1.val < list2.val:
|
||||
head = list1
|
||||
list1 = list1.next
|
||||
else:
|
||||
head = list2
|
||||
list2 = list2.next
|
||||
|
||||
current = head
|
||||
while list1 and list2:
|
||||
if list1.val < list2.val:
|
||||
current.next = list1
|
||||
list1 = list1.next
|
||||
else:
|
||||
current.next = list2
|
||||
list2 = list2.next
|
||||
current = current.next
|
||||
|
||||
current.next = list1 or list2
|
||||
return head
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Whitespace-only changes.
Whitespace-only changes.
Reference in new issue
Block a user