Add 14 skeleton sheets and rule text

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWXLvi9aq4MxL4XHKJ4
This commit is contained in:
Krzysztof Rudnicki 2026-11-21 21:53:17 +01:00
parent bbb5f1b185
commit 1aa2ef7e8f
16 changed files with 622 additions and 0 deletions

View File

@ -0,0 +1,43 @@
# Skeleton sheets: the rule for Claude
A skeleton sheet is one code template with holes for one curriculum unit. It shows the shape of the unit's standard pattern (loop frame, map idiom, pointer frame) and leaves every decision as a hole. It never solves a problem.
## When you may show one
Show a sheet only when all three hold:
1. kuhy has made his first code attempt in this solve (the session log has a `code` event).
2. kuhy asks for it. Never offer it, never hint that it exists, never show it unasked.
3. The session is a normal session or a review.
Before his first code attempt, answer "give me a skeleton" with the next hint-ladder step instead, and say the sheet unlocks after his first attempt.
## How to open it
Run the command; it logs the open and prints the sheet.
COMMAND: skeleton-open <slug> <unit>
Opening a sheet counts above hint H1. That solve gets no sign-off: tell kuhy so in one line before you run the command, and run it only after he repeats the request.
## Which unit
Use the problem's latest curriculum unit: the unit that comes last in this order among the problem's topic tags. A problem with no topic tags (the JavaScript and pandas sets) uses `js-pandas`.
scans, hashing, math, bits, sorting-greedy, pointers-window, prefix-sums, stack-queue, binary-search, lists-recursion, trees, heap-dp, sql, js-pandas
## How to print it
The command prints the sheet file `skeletons/DOCS-<unit>.md`. Three print rules:
1. Open the code fence with three backticks and no language tag (a tag such as `sql` or `ts` changes the text the Stop gate compares).
2. Print the sheet exactly as the command printed it: no shortened lines, no renamed variable, no filled hole, no line of your own.
3. Print each fence of the sheet as its own fence, one fence per fence (js-pandas has two).
After the sheet, ask kuhy one question: which hole he fills first.
If he asks you to fill a hole, treat it as a request for a solution: refuse and ask what he thinks goes there.
## Why the wording matters
The Stop gate bounces a reply that holds code using the problem's own identifiers, except a snippet that matches text already in the transcript. The command's output is such text, so a verbatim sheet passes. The gate lets the sheet through only as a verbatim quote of the command output; a changed sheet is new code and gets bounced.

View File

@ -0,0 +1,18 @@
## Skeleton: Binary search (binary-search)
Signal: O(log n) per query; sorted input, or a yes/no question that flips once as the guess grows.
Trap: pick one range style, [lo, hi] or [lo, hi), and keep the loop test, both updates and the return consistent with it; a mismatch loops forever.
```
let lo: number = 0;
let hi: number = /* HOLE: last index, or length: match the loop test */;
while (lo /* HOLE: < or <= */ hi) {
const pivot: number = lo + Math.floor((hi - lo) / 2);
if (/* HOLE: invariant: what is true at pivot when the answer is at pivot or to its left */) {
hi = /* HOLE: pivot or pivot - 1 */;
} else {
lo = /* HOLE: pivot + 1 or pivot */;
}
}
return /* HOLE: lo or hi, and a range check if the answer may not exist */;
```

View File

@ -0,0 +1,21 @@
## Skeleton: Bit manipulation (bits)
Signal: works per bit; self-inverse (XOR cancels pairs); isolates one bit; O(1) extra space.
Trap: JavaScript bit operators work on signed 32-bit integers; use >>> 0 when the sign bit must not count as negative.
```
// Fold with one bit operator.
let acc: number = /* HOLE: neutral start for the operator */;
for (let i = 0; i < seq.length; i++) {
acc = acc /* HOLE: the operator: ^, & or | */ seq[i];
}
// Visit every bit position.
for (let b = 0; b < /* HOLE: width of the integer */; b++) {
const bit: number = (x >> /* HOLE: position */) & /* HOLE: mask for one bit */;
/* HOLE: use bit */
}
// Clear or keep one bit.
x = x /* HOLE: operator */ (/* HOLE: expression built from x */);
```

View File

@ -0,0 +1,22 @@
## Skeleton: Hashing and counting (hashing)
Signal: O(1) lookup; stores a value per key; presence only; arbitrary keys (a Map) or a bounded key range (an array).
Trap: a Map returns undefined for a new key, so give it a default with ?? before you do arithmetic.
```
// Map frame: ask first, then store.
function tally(seq: string[]): number {
const seen = new Map<string, number>();
for (let i = 0; i < seq.length; i++) {
const item: string = seq[i];
const before: number = seen.get(item) ?? /* HOLE: default for a new item */;
/* HOLE: decide with before; the answer may be ready already */
seen.set(item, /* HOLE: what to store for this item */);
}
return /* HOLE: what the map says at the end */;
}
// Bounded keys (26 letters): a plain list indexed by key.
const slots: number[] = new Array(/* HOLE: size of the key range */).fill(0);
slots[seq[i].charCodeAt(0) - /* HOLE: code of the first key */] += /* HOLE: step */;
```

View File

@ -0,0 +1,24 @@
## Skeleton: Heap and dynamic programming (heap-dp)
Signal: O(log n) push and pop-min (a heap, partial order); an answer built from answers to smaller inputs (a DP table or a memo).
Trap: name what ONE cell of the table means before you fill it, and size the table for the base case; JavaScript has no built-in heap, so keep one in an array.
```
// Bottom-up table.
const cell: number[] = new Array(/* HOLE: how many states, base state included */).fill(0);
cell[0] = /* HOLE: the base state */;
for (let i = 1; i < cell.length; i++) {
cell[i] = /* HOLE: from cell[i - 1], cell[i - 2], ... */;
}
const answer: number = cell[/* HOLE: which state is the answer */];
// Heap kept in a plain list: the parent of slot i is (i - 1) >> 1.
function siftUp(h: number[], i: number): void {
while (i > 0) {
const up: number = (i - 1) >> 1;
if (/* HOLE: parent already in order */) { break; }
/* HOLE: swap h[i] and h[up] */
i = up;
}
}
```

View File

@ -0,0 +1,33 @@
## Skeleton: JavaScript closures, promises and pandas (js-pandas)
Signal: a function that returns a function, a timer or a delayed result, an async call (JavaScript); a table of rows to filter, join, group or reshape (pandas).
Trap: a closure keeps the variable, not a copy; await only works inside async; setTimeout takes milliseconds and returns the handle you cancel with; in pandas keep a plain assignment per step, and reset_index after a groupby.
```
// Closure, timer and promise frame.
function make(start) {
let state = /* HOLE: private value kept between calls */;
return function () { /* HOLE: update state, then read it */ };
}
const handle = setTimeout(() => { /* HOLE: what runs later */ }, /* HOLE: delay in milliseconds */);
clearTimeout(handle);
async function load(ms) {
const wait = new Promise((resolve, reject) => { /* HOLE: call resolve or reject, when */ });
const first = await /* HOLE: a promise */;
const all = await Promise.all(/* HOLE: list of promises started together */);
}
```
```
import pandas as pd
# One transformation per line; the final step is yours.
out = (
frame
.merge(/* HOLE: other frame */, on=/* HOLE: key column */, how=/* HOLE: join kind */)
.query(/* HOLE: filter expression */)
.groupby(/* HOLE: key columns */, as_index=False)
.agg(/* HOLE: named aggregations */)
.sort_values(/* HOLE: column */, ascending=/* HOLE: True or False */)
)
```

View File

@ -0,0 +1,26 @@
## Skeleton: Linked lists and recursion (lists-recursion)
Signal: follow a chain of next links; cycle; reverse or merge in place; a problem that repeats on a smaller copy of itself.
Trap: save cur.next in a variable before you overwrite it; every recursion needs its base case written first and a call on a strictly smaller case.
```
// Walk a chain, rewiring as you go.
function walk(start: ListNode | null): ListNode | null {
let prev: ListNode | null = null;
let cur: ListNode | null = start;
while (cur !== null) {
const after: ListNode | null = cur.next;
/* HOLE: rewire cur.next */
prev = /* HOLE: the new previous */;
cur = after;
}
return /* HOLE: the new front of the chain */;
}
// Recursion frame.
function dive(depth: number): number {
if (/* HOLE: base case */) { return /* HOLE: base value */; }
const below: number = dive(/* HOLE: a strictly smaller case */);
return /* HOLE: combine below with this level */;
}
```

View File

@ -0,0 +1,27 @@
## Skeleton: Math and number theory (math)
Signal: divides its inputs (gcd); digits of a number; primes and divisors; closed-form formula.
Trap: JavaScript division gives a fraction, so floor it; stop trial division when d * d passes the limit, not at the limit.
```
// Peel the last figure off a number.
let rest: number = /* HOLE: the number to take apart */;
while (rest > 0) {
const digit: number = rest % 10;
/* HOLE: use digit */
rest = Math.floor(rest / /* HOLE: divisor */);
}
// Euclid frame: the pair shrinks until one side is spent.
function fold(a: number, b: number): number {
while (/* HOLE: when to stop */) {
[a, b] = [b, /* HOLE: the next remainder */];
}
return /* HOLE: which of the two is left */;
}
// Trial division.
for (let d = 2; d * d <= /* HOLE: limit */; d++) {
/* HOLE: what a divisor tells you */
}
```

View File

@ -0,0 +1,29 @@
## Skeleton: Two pointers and sliding window (pointers-window)
Signal: two moving indexes; from both ends (needs sorted input); window moves right (monotone condition).
Trap: decide whether the loop is lo < hi or lo <= hi before you write the body, and move at least one index every turn.
```
// From both ends.
let lo: number = 0;
let hi: number = /* HOLE: last index */;
while (lo < hi) {
/* HOLE: look at seq[lo] and seq[hi] */
if (/* HOLE: which end is wrong */) {
lo++;
} else {
hi--;
}
}
// Window: the right end grows every turn, the left end only repairs.
let from: number = 0;
for (let to = 0; to < seq.length; to++) {
/* HOLE: add seq[to] to the window state */
while (/* HOLE: the window is invalid */) {
/* HOLE: remove seq[from] from the window state */
from++;
}
/* HOLE: the window is valid here; record what you need */
}
```

View File

@ -0,0 +1,18 @@
## Skeleton: Prefix sums (prefix-sums)
Signal: range query in O(1) after O(n) setup; keeps every prefix; handles negatives (a window breaks, a prefix does not).
Trap: the prefix array has one more slot than the input, and slot 0 is the empty prefix; an off-by-one here shifts every answer.
```
// Build.
const pre: number[] = new Array(seq.length + /* HOLE: extra slots */).fill(0);
for (let i = 0; i < seq.length; i++) {
pre[/* HOLE: slot to fill */] = pre[/* HOLE: previous slot */] + seq[i];
}
// Query: seq[l..r] inclusive is one subtraction.
const span: number = pre[/* HOLE: slot for the r side */] - pre[/* HOLE: slot for the l side */];
// Prefix plus map: seed the empty prefix before the loop.
const firstSeen = new Map<number, number>([[0, /* HOLE: what the empty prefix stores */]]);
```

View File

@ -0,0 +1,27 @@
## Skeleton: Scans and simulation (scans)
Signal: single pass; O(1) extra space; walk an array, string or matrix and update a running answer.
Trap: the loop bound is i < length, never i <= length; a neighbour cell needs its bounds check before you read it.
```
// One pass over a list.
function scan(seq: number[]): number {
let best: number = /* HOLE: start value that every real element beats */;
for (let i = 0; i < seq.length; i++) {
/* HOLE: update best from seq[i] */
}
return /* HOLE: what the loop leaves behind */;
}
// Row by row over a table of cells.
function sweep(cells: number[][]): number {
const rows: number = cells.length;
const cols: number = /* HOLE: width, safe when there are no rows */;
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
/* HOLE: use cells[r][c]; check bounds before any neighbour */
}
}
return /* HOLE: the final tally */;
}
```

View File

@ -0,0 +1,25 @@
## Skeleton: Sorting and greedy (sorting-greedy)
Signal: makes equal values adjacent; overlaps become adjacent; earliest end first; greedy commits and never revisits; needs a majority.
Trap: sort() without a comparator compares as strings ([10, 9, 1] becomes [1, 10, 9]); and sort() reorders the array you pass it.
```
// Sort a copy, then one pass that commits to the locally best choice.
const order: number[] = seq.slice().sort(/* HOLE: comparator; negative puts the first argument first */);
let chosen: number = /* HOLE: start state */;
for (let i = 0; i < order.length; i++) {
if (/* HOLE: can order[i] be taken given what is already chosen */) {
/* HOLE: commit to order[i], never undo it */
}
}
// Candidate and streak (majority vote).
let pick: number | undefined = undefined;
let streak: number = 0;
for (let i = 0; i < seq.length; i++) {
if (streak === 0) {
pick = /* HOLE: the new candidate */;
}
streak += /* HOLE: up or down, and when */;
}
```

View File

@ -0,0 +1,16 @@
## Skeleton: SQL queries (sql)
Signal: a table schema and a question about rows; joins, group-by, a filter before or after grouping.
Trap: clauses run in this order: FROM, JOIN, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT; WHERE cannot see an aggregate or a select alias, HAVING can see the aggregate; a filter on the right table of a LEFT JOIN belongs in ON, not WHERE.
```
SELECT /* HOLE: columns, or an aggregate over each group */
FROM /* HOLE: main table */ AS a
LEFT JOIN /* HOLE: other table */ AS b
ON /* HOLE: join condition */
WHERE /* HOLE: row filter: runs before grouping, no aggregates */
GROUP BY /* HOLE: every selected column that is not aggregated */
HAVING /* HOLE: group filter: aggregates allowed */
ORDER BY /* HOLE: sort keys, ASC or DESC */
LIMIT /* HOLE: how many rows */;
```

View File

@ -0,0 +1,20 @@
## Skeleton: Stack and queue (stack-queue)
Signal: last-in-first-out; next-greater lookup; brackets; amortized O(n).
Trap: pop only after you check the stack is not empty; keep INDEXES on the stack when you need distances; shift() on a long array is slow.
```
// Monotonic stack: each element is pushed once and popped at most once.
const waiting: number[] = [];
for (let i = 0; i < seq.length; i++) {
while (waiting.length > 0 && /* HOLE: the last waiting element is settled by seq[i] */) {
const last: number = waiting.pop() as number;
/* HOLE: record what seq[i] settles for last */
}
waiting.push(/* HOLE: the index or the value that keeps waiting */);
}
/* HOLE: what happens to elements still waiting at the end */
// Queue: take from the front.
const front: number = lineup.shift() as number;
```

View File

@ -0,0 +1,24 @@
## Skeleton: Trees and graphs (trees)
Signal: tree, binary tree, search tree; depth-first or breadth-first search; graph, union-find, trie.
Trap: the empty subtree (null) is the base case of every depth-first walk; breadth-first search freezes the level size BEFORE its inner loop; a graph needs a visited set, a tree does not.
```
// Depth-first: answer from the two subtrees.
function dfs(cur: TreeNode | null): number {
if (cur === null) { return /* HOLE: value for an empty subtree */; }
const l: number = dfs(cur.left);
const r: number = dfs(cur.right);
return /* HOLE: combine l, r and cur.val */;
}
// Breadth-first: one level per outer turn.
const frontier: TreeNode[] = [/* HOLE: the start */];
while (frontier.length > 0) {
const width: number = frontier.length;
for (let i = 0; i < width; i++) {
const cur: TreeNode = frontier.shift() as TreeNode;
/* HOLE: visit cur; queue the children that exist */
}
}
```

View File

@ -0,0 +1,249 @@
"""The 14 skeleton sheets: one code template with holes per curriculum unit.
A sheet is printed verbatim inside a fenced block of a coach reply, so every
sheet is judged by the real no-solution detector (`gate_detector`) the way the
Stop hook would judge that reply.
"""
from __future__ import annotations
import json
from pathlib import Path
import re
from typing import Any
import pytest
import leetcode_coach
from leetcode_coach import gate_detector as det
from leetcode_coach import stop_gate
PKG = Path(leetcode_coach.__file__).resolve().parent
SHEETS = PKG / "skeletons"
RULES = PKG / "DOCS-skeletons.md"
# Copied from the guard's curriculum (leetcode_guard/curriculum.json, 2026-11-21)
# on purpose: the coach never reads the guard repo, not even at test time.
UNITS = (
"scans",
"hashing",
"math",
"bits",
"sorting-greedy",
"pointers-window",
"prefix-sums",
"stack-queue",
"binary-search",
"lists-recursion",
"trees",
"heap-dp",
"sql",
"js-pandas",
)
HOLE = "/* HOLE:"
MIN_HOLES = 3
MAX_LINES = 75
MAX_CHARS = 3600
TS_ONLY = re.compile(
r":\s*(?:number|string|boolean|void|any)\b|<[A-Za-z]+[\w, \[\]]*>\(|"
r"\binterface\b|\bas\s+(?:number|string|const)\b|\btype\s+\w+\s*="
)
# Names real LeetCode easy starters use: a sheet fence holding one would be
# bounced on that problem, so none may appear (whole word).
STARTER_WORDS = frozenset(
re.findall(
r"\w+",
"nums nums1 nums2 target head root node list1 list2 l1 l2 prices arr "
"array strs haystack needle matrix grid board digits height heights "
"intervals words word text ransomNote magazine candies accounts sentence "
"paragraph banned num numbers mat cost flowers stones coins people "
"citations points customers orders salary employee scores sequence "
"pattern low high count result data input items twoSum isValid maxProfit "
"climbStairs mergeTwoLists isPalindrome removeDuplicates hammingWeight "
"reverseBits singleNumber missingNumber majorityElement "
"containsDuplicate isAnagram search searchInsert pivotIndex runningSum "
"maxDepth invertTree inorderTraversal fib lengthOfLastWord plusOne "
"addBinary mySqrt rob minCostClimbingStairs countBits isSubsequence "
"longestCommonPrefix romanToInt",
),
)
# Easy "design" method names: a sheet may use them, but only as a verbatim quote.
DESIGN_WORDS = frozenset(
re.findall(
r"\w+",
"push pop peek top empty add get put set has remove contains next ping "
"getMin insert startsWith enqueue dequeue size key value",
),
)
Entry = dict[str, Any]
def _sheet(unit: str) -> str:
return (SHEETS / f"DOCS-{unit}.md").read_text(encoding="utf-8")
def _fences(text: str) -> list[str]:
return re.findall(r"```\n(.*?)```", text, re.DOTALL)
def _transcript(sheet: str, idents: str) -> list[Entry]:
"""A starter with `idents` as parameters, then a tool result holding the sheet."""
starter = f"## Starter code\n```\nvar f = function({idents}) {{}};\n```"
return [
{"type": "user", "message": {"content": starter}},
{
"type": "user",
"message": {"content": [{"type": "tool_result", "content": sheet}]},
},
]
def test_the_unit_list_has_14_distinct_ids() -> None:
assert len(UNITS) == len(set(UNITS)) == 14
def test_the_sheet_directory_holds_exactly_the_14_sheets() -> None:
assert sorted(p.name for p in SHEETS.glob("*")) == sorted(
f"DOCS-{u}.md" for u in UNITS
)
@pytest.mark.parametrize("unit", UNITS)
def test_every_sheet_names_its_unit_and_ends_with_a_fence(unit: str) -> None:
text = _sheet(unit)
assert text.startswith("## Skeleton: ")
assert f"({unit})" in text.splitlines()[0]
assert text.rstrip().endswith("```")
assert "Signal:" in text
assert "Trap:" in text
@pytest.mark.parametrize("unit", UNITS)
def test_every_sheet_has_enough_holes(unit: str) -> None:
need = 4 if unit == "js-pandas" else MIN_HOLES
code = "\n".join(_fences(_sheet(unit)))
assert code.count(HOLE) >= need
assert all(line.count(HOLE) == line.count("*/") for line in code.splitlines())
@pytest.mark.parametrize("unit", UNITS)
def test_a_sheet_is_small_and_has_no_stray_backticks(unit: str) -> None:
text = _sheet(unit)
assert len(text.splitlines()) <= MAX_LINES
assert len(text) <= MAX_CHARS
fence_lines = [ln for ln in text.splitlines() if ln.startswith("```")]
assert fence_lines
assert all(ln == "```" for ln in fence_lines), (
"bare fences: a language tag breaks quoting"
)
assert len(fence_lines) % 2 == 0
assert text.count("`") == 3 * len(fence_lines)
@pytest.mark.parametrize("unit", UNITS)
def test_a_sheet_never_returns_an_answer_of_its_own(unit: str) -> None:
for line in "\n".join(_fences(_sheet(unit))).splitlines():
if re.search(r"\breturn\b", line):
assert HOLE in line, line
@pytest.mark.parametrize("unit", UNITS)
def test_every_sheet_passes_the_detector_unquoted(unit: str) -> None:
text = _sheet(unit)
bad = det.offending_snippets(text, set(STARTER_WORDS), "")
assert bad == []
code = "\n".join(_fences(text))
for word in STARTER_WORDS:
assert not re.search(rf"\b{word}\b", code), word
@pytest.mark.parametrize("unit", UNITS)
def test_every_sheet_passes_the_detector_as_a_verbatim_quote(unit: str) -> None:
sheet = _sheet(unit)
idents = sorted(STARTER_WORDS | DESIGN_WORDS)
entries = _transcript(sheet, ", ".join(idents))
assert det.starter_identifiers(entries) >= DESIGN_WORDS
allowed = det.allowed_text(entries)
assert (
det.offending_snippets(sheet, det.starter_identifiers(entries), allowed) == []
)
def test_the_quote_exemption_is_real_and_a_filled_hole_loses_it() -> None:
sheet = _sheet("stack-queue")
entries = _transcript(sheet, "push, pop")
idents = det.starter_identifiers(entries)
allowed = det.allowed_text(entries)
assert det.offending_snippets(sheet, idents, allowed) == []
filled = sheet.replace(HOLE, "/* filled:", 1).replace(
"```\n", "```\nlet cheat = 1;\n", 1
)
assert det.offending_snippets(filled, idents, allowed) != []
assert det.offending_snippets(sheet, idents, "") != []
def test_the_sql_sheet_is_sql() -> None:
code = "\n".join(_fences(_sheet("sql")))
assert re.search(r"^SELECT\b", code, re.MULTILINE)
assert re.search(r"^FROM\b", code, re.MULTILINE)
assert re.search(r"\bGROUP BY\b", code)
for js in ("const ", "let ", "function", "=>", "return", "{", "}"):
assert js not in code
def test_the_js_pandas_sheet_has_javascript_and_pandas_and_no_typescript() -> None:
fences = _fences(_sheet("js-pandas"))
assert len(fences) == 2
js, pandas = fences
assert re.search(r"setTimeout|clearTimeout|Promise|=>", js)
assert "frame" in pandas
assert re.search(r"\.groupby|\.merge|\.query|\.loc|\.drop", pandas)
assert not TS_ONLY.search("\n".join(fences))
@pytest.mark.parametrize("unit", [u for u in UNITS if u not in {"sql", "js-pandas"}])
def test_the_typescript_sheets_use_typescript_types(unit: str) -> None:
assert re.search(r":\s*(?:number|string|boolean)", "\n".join(_fences(_sheet(unit))))
def test_the_rule_text_covers_when_how_and_the_cost() -> None:
text = RULES.read_text(encoding="utf-8")
assert "COMMAND: skeleton-open <slug> <unit>" in text
for needle in (
"first code attempt",
"only when",
"H1",
"sign-off",
"verbatim",
"latest",
):
assert needle in text, needle
@pytest.mark.parametrize("unit", UNITS)
def test_the_real_stop_gate_lets_a_verbatim_sheet_through(unit: str) -> None:
"""End to end: kuhy has coded, the command output is in the transcript."""
sheet = _sheet(unit)
attempt = (
"my try\n```js\nvar twoSum = function(nums, target) {\n let a = 1;\n};\n```"
)
entries = [
{
"type": "user",
"message": {
"content": [
{
"type": "text",
"text": f"Base directory for this skill: {stop_gate.SKILL_LINK}",
}
]
},
},
*_transcript(sheet, "twoSum, nums, target, push, pop, get, set, key, value"),
]
entries.insert(2, {"type": "user", "message": {"content": attempt}})
raw = "\n".join(json.dumps(e) for e in entries)
raw += f'\n"text":"Base directory for this skill: {stop_gate.SKILL_LINK}'
assert stop_gate.verdict(raw, sheet) is None