Spaces:
Paused

brianbellx commited on
Commit
5c265c1
·
verified ·
1 Parent(s): bdd6188

Upgrade to codehygiene v0.6.1, Bonsai 1.7B WebGPU + ZeroGPU refiner, and Data Retention page

Browse files
Dockerfile CHANGED
@@ -1,4 +1,4 @@
1
- ARG CODEHYGIENE_REF=0221af718b51a56b6ee0fbea52f0bf42afa381bb
2
 
3
  FROM node:22-slim AS web
4
  ARG CODEHYGIENE_REF
@@ -6,13 +6,16 @@ WORKDIR /build
6
  COPY web/package.json web/package-lock.json web/
7
  RUN cd web && npm ci
8
  COPY web/ web/
9
- ADD https://raw.githubusercontent.com/brianbell-x/codehygiene/${CODEHYGIENE_REF}/docs/engine.js web/vendor/engine.js
10
- ADD https://raw.githubusercontent.com/brianbell-x/codehygiene/${CODEHYGIENE_REF}/docs/presets.json web/vendor/presets.json
11
- ADD https://raw.githubusercontent.com/brianbell-x/codehygiene/${CODEHYGIENE_REF}/docs/weights.npz web/vendor/weights.npz
12
  RUN cd web && npm run build
13
 
14
  FROM python:3.12-slim
15
  ARG CODEHYGIENE_REF
 
 
 
16
  ARG REFINER_REPO=Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF
17
  ARG REFINER_FILE=qwen2.5-coder-1.5b-instruct-q4_k_m.gguf
18
 
@@ -29,19 +32,25 @@ WORKDIR /home/user/app
29
 
30
  COPY --chown=user requirements.txt .
31
  RUN pip install --no-cache-dir --user \
32
- --extra-index-url https://abetlen.github.io/llama-cpp-python/whl/cpu \
33
- --only-binary=llama-cpp-python \
34
  -r requirements.txt \
35
  "codehygiene @ git+https://github.com/brianbell-x/codehygiene@${CODEHYGIENE_REF}"
36
 
37
- RUN python -c "import sys; from huggingface_hub import hf_hub_download; hf_hub_download(sys.argv[1], sys.argv[2], local_dir='/home/user/models')" \
38
- "${REFINER_REPO}" "${REFINER_FILE}"
 
 
 
 
 
 
39
 
40
  COPY --chown=user server/ server/
41
  COPY --from=web --chown=user /build/web/dist web/dist
42
  COPY --from=web --chown=user /build/web/vendor/presets.json web/vendor/presets.json
43
 
44
- ENV REFINER_BACKEND=llama \
 
 
45
  REFINER_REPO=${REFINER_REPO} \
46
  REFINER_FILE=${REFINER_FILE} \
47
  REFINER_MODEL_PATH=/home/user/models/${REFINER_FILE}
 
1
+ ARG CODEHYGIENE_REF=2ec03172f47f14655c1490540c2f593b77095807
2
 
3
  FROM node:22-slim AS web
4
  ARG CODEHYGIENE_REF
 
6
  COPY web/package.json web/package-lock.json web/
7
  RUN cd web && npm ci
8
  COPY web/ web/
9
+ COPY presets.json web/vendor/presets.json
10
+ ADD https://raw.githubusercontent.com/brianbell-x/codehygiene/${CODEHYGIENE_REF}/codehygiene/engine.js web/vendor/engine.js
11
+ ADD https://raw.githubusercontent.com/brianbell-x/codehygiene/${CODEHYGIENE_REF}/codehygiene/weights.npz web/vendor/weights.npz
12
  RUN cd web && npm run build
13
 
14
  FROM python:3.12-slim
15
  ARG CODEHYGIENE_REF
16
+ ARG REFINER_BACKEND=zerogpu
17
+ ARG ZEROGPU_SPACE=brianbellx/codehygiene-zerogpu
18
+ ARG REFINER_MODEL_ID=brianbellx/codehygiene-bonsai-1.7b
19
  ARG REFINER_REPO=Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF
20
  ARG REFINER_FILE=qwen2.5-coder-1.5b-instruct-q4_k_m.gguf
21
 
 
32
 
33
  COPY --chown=user requirements.txt .
34
  RUN pip install --no-cache-dir --user \
 
 
35
  -r requirements.txt \
36
  "codehygiene @ git+https://github.com/brianbell-x/codehygiene@${CODEHYGIENE_REF}"
37
 
38
+ RUN if [ "${REFINER_BACKEND}" = "llama" ]; then \
39
+ pip install --no-cache-dir --user \
40
+ --extra-index-url https://abetlen.github.io/llama-cpp-python/whl/cpu \
41
+ --only-binary=llama-cpp-python \
42
+ llama-cpp-python==0.3.36 && \
43
+ python -c "import sys; from huggingface_hub import hf_hub_download; hf_hub_download(sys.argv[1], sys.argv[2], local_dir='/home/user/models')" \
44
+ "${REFINER_REPO}" "${REFINER_FILE}"; \
45
+ fi
46
 
47
  COPY --chown=user server/ server/
48
  COPY --from=web --chown=user /build/web/dist web/dist
49
  COPY --from=web --chown=user /build/web/vendor/presets.json web/vendor/presets.json
50
 
51
+ ENV REFINER_BACKEND=${REFINER_BACKEND} \
52
+ ZEROGPU_SPACE=${ZEROGPU_SPACE} \
53
+ REFINER_MODEL_ID=${REFINER_MODEL_ID} \
54
  REFINER_REPO=${REFINER_REPO} \
55
  REFINER_FILE=${REFINER_FILE} \
56
  REFINER_MODEL_PATH=/home/user/models/${REFINER_FILE}
README.md CHANGED
@@ -14,13 +14,15 @@ suggested_hardware: cpu-basic
14
 
15
  Paste a GitHub link. The page finds the hardest-to-read files and a small model rewrites them while you watch.
16
 
17
- The scorer runs in the browser. The refiner runs here on the CPU. A patch is kept only if it parses, keeps the code, and leaves fewer issues.
18
 
19
  ## Settings
20
 
21
  | Variable | Default | What it does |
22
  |---|---|---|
23
- | `REFINER_BACKEND` | `llama` | `llama` runs the GGUF model. `mock` replays recorded patches. |
 
 
24
  | `REFINER_REPO` | `Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF` | Build arg. Hub repo of the GGUF. |
25
  | `REFINER_FILE` | `qwen2.5-coder-1.5b-instruct-q4_k_m.gguf` | Build arg. GGUF file name. |
26
  | `REFINER_MODEL_PATH` | set by the Dockerfile | Path of the GGUF inside the image. |
 
14
 
15
  Paste a GitHub link. The page finds the hardest-to-read files and a small model rewrites them while you watch.
16
 
17
+ The scorer runs in the browser (`codehygiene` v0.6.0). Cleanup runs in the browser via WebGPU (`brianbellx/codehygiene-bonsai-1.7b`) and falls back to Hugging Face ZeroGPU when WebGPU is unavailable. A patch is kept only if it parses, keeps the code, and leaves fewer issues.
18
 
19
  ## Settings
20
 
21
  | Variable | Default | What it does |
22
  |---|---|---|
23
+ | `REFINER_BACKEND` | `zerogpu` | `zerogpu` streams from ZeroGPU, `llama` runs a GGUF model, `mock` replays recorded patches. |
24
+ | `ZEROGPU_SPACE` | `brianbellx/codehygiene-zerogpu` | ZeroGPU Space ID used when `REFINER_BACKEND=zerogpu`. |
25
+ | `REFINER_MODEL_ID` | `brianbellx/codehygiene-bonsai-1.7b` | Public model identifier reported by `/api/health`. |
26
  | `REFINER_REPO` | `Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF` | Build arg. Hub repo of the GGUF. |
27
  | `REFINER_FILE` | `qwen2.5-coder-1.5b-instruct-q4_k_m.gguf` | Build arg. GGUF file name. |
28
  | `REFINER_MODEL_PATH` | set by the Dockerfile | Path of the GGUF inside the image. |
TELEMETRY.md CHANGED
@@ -9,8 +9,8 @@ Every number is public at the Space's `/api/stats` route, and the leaderboard at
9
  | Counter | Counted by | When it goes up |
10
  |---|---|---|
11
  | `files_scored` | Browser report, checked by the server | A file from a repo, folder or snippet is scored for the first time. |
12
- | `files_cleaned` | Server only | The refiner finishes an accepted fix of a file for the first time. |
13
- | `fix_runs` | Server only | Every accepted refiner run, repeats included. |
14
  | `avg_score_before`, `avg_score_after` | Server only | Mean score out of 100 of cleaned files, before and after. |
15
  | `issues_fixed` | Derived | Sum of `squiggles_resolved_by_kind`. |
16
  | `median_score` | Browser report | Median score out of 100 of scored files, from a 101-bin histogram. |
@@ -34,9 +34,12 @@ Nothing is counted for the bundled examples, on the page or on the server. The s
34
  | PRs merged | `prs_decided` ≥ 20 |
35
  | Time per file | `score_ms_samples` ≥ 1,000 |
36
  | Leaderboard link | `leaderboard_entries` ≥ 5 |
 
37
 
38
  The Stats tab of the leaderboard page shows every number from the first count, with its sample size.
39
 
 
 
40
  ## What the browser sends
41
 
42
  After a repo, folder or snippet is scored, one request goes to `POST /api/telemetry/scan`. It can be read in the browser's network tab:
 
9
  | Counter | Counted by | When it goes up |
10
  |---|---|---|
11
  | `files_scored` | Browser report, checked by the server | A file from a repo, folder or snippet is scored for the first time. |
12
+ | `files_cleaned` | Server only | The server refiner finishes an accepted fix of a file for the first time (ZeroGPU fallback runs). |
13
+ | `fix_runs` | Server only | Every accepted server refiner run, repeats included. |
14
  | `avg_score_before`, `avg_score_after` | Server only | Mean score out of 100 of cleaned files, before and after. |
15
  | `issues_fixed` | Derived | Sum of `squiggles_resolved_by_kind`. |
16
  | `median_score` | Browser report | Median score out of 100 of scored files, from a 101-bin histogram. |
 
34
  | PRs merged | `prs_decided` ≥ 20 |
35
  | Time per file | `score_ms_samples` ≥ 1,000 |
36
  | Leaderboard link | `leaderboard_entries` ≥ 5 |
37
+ | Data Retention link | Always |
38
 
39
  The Stats tab of the leaderboard page shows every number from the first count, with its sample size.
40
 
41
+ The Data Retention link opens `/privacy/` ([`web/src/privacy.html`](web/src/privacy.html)), a plain-language summary of this file for visitors. It names no routes, limits or validation rules. Any change to what is collected or kept must be reflected there.
42
+
43
  ## What the browser sends
44
 
45
  After a repo, folder or snippet is scored, one request goes to `POST /api/telemetry/scan`. It can be read in the browser's network tab:
presets.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "id": "python-receipt",
4
+ "filename": "send_receipt.py",
5
+ "before": "def send_receipt(order: Order) -> None:\n try:\n if order is not None:\n if order.paid and not order.refunded:\n # Extract email address from order\n email = order.email\n if email is not None:\n if len(email.strip()) > 0:\n mailer.send(email, order.id)\n except Exception:\n pass",
6
+ "after": "def send_receipt(order: Order) -> None:\n if not order.paid or order.refunded:\n return\n\n if not order.email or not order.email.strip():\n return\n\n mailer.send(order.email, order.id)"
7
+ },
8
+ {
9
+ "id": "ts-ceremony",
10
+ "filename": "pricing.ts",
11
+ "before": "export class DiscountStrategyFactoryManager {\n public computeTotalAmount(cartItems: CartItem[], promoRate: number): number {\n try {\n // Step 1: Compute discounted subtotal from cart items\n const total = cartItems.filter((item) => item.active && item.qty > 0).map((item) => item.price * item.qty * (promoRate > 0 ? (promoRate > 0.5 ? 0.5 : 1 - promoRate) : 1)).reduce((acc, val) => acc + val, 0);\n return total;\n } catch (err) {\n console.log(err);\n return 0.0;\n }\n }\n}",
12
+ "after": "export function computeOrderTotal(items: CartItem[], promoRate: number): number {\n const cappedRate = Math.min(Math.max(promoRate, 0), 0.5);\n const multiplier = 1 - cappedRate;\n\n let subtotal = 0;\n for (const item of items) {\n if (item.active && item.qty > 0) {\n subtotal += item.price * item.qty * multiplier;\n }\n }\n\n return subtotal;\n}"
13
+ },
14
+ {
15
+ "id": "rust-golf",
16
+ "filename": "frame.rs",
17
+ "before": "#[allow(clippy::many_single_char_names)]\npub fn decode_frame(buf: &[u8]) -> Option<(u32, u16, u8)> {\n let mut hd = [0u8; 16];\n hd[0] = buf[12] ^ buf[28];\n hd[1] = buf[14] ^ buf[30];\n hd[2] = buf[18] ^ buf[34];\n hd[3] = buf[22] ^ buf[38];\n let mg = u16::from_be_bytes([buf[10], buf[11]]);\n let sq = u32::from_be_bytes([buf[16], buf[17], buf[18], buf[19]]);\n let ln = u16::from_be_bytes([buf[24], buf[25]]);\n let fl = buf[36] ^ buf[42];\n let ck = buf[44] ^ buf[47];\n let vr = hd[0].wrapping_add(hd[1]).wrapping_add(hd[2]);\n let ok = mg == 23112 && vr > 0 && (fl & 4) != 0 && ck != 0;\n if !ok { return None; }\n Some((sq, ln, ck))\n}",
18
+ "after": "const HEADER_LEN: usize = 48;\nconst FRAME_MAGIC: u16 = 0x5A48;\nconst FLAG_VERIFIED: u8 = 0x04;\n\npub struct FrameHeader {\n pub sequence: u32,\n pub payload_len: u16,\n pub checksum: u8,\n}\n\npub fn decode_header(bytes: &[u8]) -> Result<FrameHeader, FrameError> {\n if bytes.len() < HEADER_LEN {\n return Err(FrameError::TruncatedHeader);\n }\n\n let magic = u16::from_be_bytes([bytes[0], bytes[1]]);\n if magic != FRAME_MAGIC {\n return Err(FrameError::InvalidMagic);\n }\n\n let flags = bytes[2];\n if flags & FLAG_VERIFIED == 0 {\n return Err(FrameError::UnverifiedPayload);\n }\n\n let sequence = u32::from_be_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]);\n let payload_len = u16::from_be_bytes([bytes[8], bytes[9]]);\n Ok(FrameHeader {\n sequence,\n payload_len,\n checksum: bytes[3],\n })\n}"
19
+ },
20
+ {
21
+ "id": "go-clones",
22
+ "filename": "webhook.go",
23
+ "before": "func resolveEndpoint(region string) string {\n if region == \"us-east-1\" { return \"https://east.hooks.internal\" }\n if region == \"us-west-2\" { return \"https://west.hooks.internal\" }\n if region == \"eu-central-1\" { return \"https://eu.hooks.internal\" }\n if region == \"ap-northeast-1\" { return \"https://ap.hooks.internal\" }\n if region == \"sa-east-1\" { return \"https://sa.hooks.internal\" }\n return \"https://default.hooks.internal\"\n}\n\nfunc publishAuditEvent(httpClient *Client, region string, auditItem Event) {\n targetUrl := resolveEndpoint(region)\n bodyBytes := serializeJsonBody(auditItem)\n authToken := computeHmacSignature(bodyBytes, httpClient.signingSecret)\n statusCode := transmitHttpPost(httpClient, targetUrl, bodyBytes, authToken)\n recordTelemetryCounter(statusCode, region)\n}\n\nfunc publishBillingEvent(httpClient *Client, region string, billingItem Event) {\n targetUrl := resolveEndpoint(region)\n bodyBytes := serializeJsonBody(billingItem)\n authToken := computeHmacSignature(bodyBytes, httpClient.signingSecret)\n statusCode := transmitHttpPost(httpClient, targetUrl, bodyBytes, authToken)\n recordTelemetryCounter(statusCode, region)\n}",
24
+ "after": "var regionEndpoints = map[string]string{\n \"us-east-1\": \"https://east.hooks.internal\",\n \"us-west-2\": \"https://west.hooks.internal\",\n \"eu-central-1\": \"https://eu.hooks.internal\",\n \"ap-northeast-1\": \"https://ap.hooks.internal\",\n \"sa-east-1\": \"https://sa.hooks.internal\",\n}\n\nfunc resolveEndpoint(region string) string {\n if endpoint, ok := regionEndpoints[region]; ok {\n return endpoint\n }\n return \"https://default.hooks.internal\"\n}\n\nfunc postStreamEvent(\n ctx context.Context,\n client *http.Client,\n endpoint string,\n stream string,\n event Event,\n) error {\n payload, err := json.Marshal(event)\n if err != nil {\n return fmt.Errorf(\"marshal %s: %w\", stream, err)\n }\n\n req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(payload))\n if err != nil {\n return fmt.Errorf(\"build %s request: %w\", stream, err)\n }\n req.Header.Set(\"Content-Type\", \"application/json\")\n req.Header.Set(\"X-Event-Stream\", stream)\n\n resp, err := client.Do(req)\n if err != nil {\n return fmt.Errorf(\"send %s webhook: %w\", stream, err)\n }\n defer resp.Body.Close()\n return nil\n}"
25
+ },
26
+ {
27
+ "id": "self-engine",
28
+ "filename": "engine.js",
29
+ "before": "export function unpack(tb, vb, ms) {\n let sp, ft, bo, vo, bv, ds;\n // TODO: clean up golfed trit unpacking\n sp = ms.split(\"|\");\n ft = new Int8Array(tb.length * 5);\n bo = 0;\n vo = 0;\n for (let i = 0; i < tb.length; i++) {\n bv = tb[i];\n ds = i * 5;\n ft[ds] = (((bv % 3) + 1) % 3) - 1;\n ft[ds + 1] = (((Math.floor(bv / 3) % 3) + 1) % 3) - 1;\n ft[ds + 2] = (((Math.floor(bv / 9) % 3) + 1) % 3) - 1;\n ft[ds + 3] = (((Math.floor(bv / 27) % 3) + 1) % 3) - 1;\n ft[ds + 4] = (((Math.floor(bv / 81) % 3) + 1) % 3) - 1;\n }\n try {\n return sp[0].length > 0 && bo >= vo ? ft : (vb || []);\n } catch (e) {}\n}",
30
+ "after": "__LOAD_LIVE_ENGINE__"
31
+ }
32
+ ]
requirements.txt CHANGED
@@ -1,7 +1,6 @@
1
  fastapi==0.115.12
2
  uvicorn==0.34.2
3
  numpy>=1.26,<3
4
- llama-cpp-python==0.3.36
5
  httpx==0.28.1
6
  PyJWT[crypto]==2.10.1
7
  huggingface_hub>=0.24
 
1
  fastapi==0.115.12
2
  uvicorn==0.34.2
3
  numpy>=1.26,<3
 
4
  httpx==0.28.1
5
  PyJWT[crypto]==2.10.1
6
  huggingface_hub>=0.24
server/app.py CHANGED
@@ -15,7 +15,7 @@ from fastapi.responses import HTMLResponse, JSONResponse, PlainTextResponse, Red
15
  from fastapi.staticfiles import StaticFiles
16
  from pydantic import BaseModel, Field
17
 
18
- from .backends import Refiner, make_refiner
19
  from .config import Settings, load_settings
20
  from .fix_loop import Cancelled, Emit, FixRequest, RefinerUnavailable
21
  from .fix_queue import QueueFull
@@ -162,7 +162,7 @@ def create_app(
162
  for file in synced:
163
  await file.load()
164
  tasks = [asyncio.create_task(sync_files())]
165
- if settings.backend == "llama" or settings.warmup:
166
  tasks.append(asyncio.create_task(warm_up()))
167
  if settings.leaderboard_seed:
168
  tasks.append(asyncio.create_task(board.maintain(SEED_REPOS, settings.leaderboard_seed_pause)))
@@ -302,7 +302,8 @@ def create_app(
302
  return score_dict(body.content, body.threshold)
303
 
304
  @app.post("/api/fix")
305
- async def fix(body: FixBody) -> dict[str, Any]:
 
306
  collected: dict[str, dict[str, Any]] = {}
307
  produce = producer_for(body, paced=False)
308
  await guarded(produce, lambda name, data: collected.__setitem__(name, data))
@@ -312,7 +313,8 @@ def create_app(
312
  raise HTTPException(status_code=ERROR_STATUS.get(failure["code"], 500), detail=failure)
313
 
314
  @app.post("/api/fix/stream")
315
- async def fix_stream(body: FixBody) -> StreamingResponse:
 
316
  produce = producer_for(body, paced=True)
317
  return StreamingResponse(sse_events(produce), media_type="text/event-stream", headers=SSE_HEADERS)
318
 
 
15
  from fastapi.staticfiles import StaticFiles
16
  from pydantic import BaseModel, Field
17
 
18
+ from .backends import VISITOR_IP_TOKEN, Refiner, make_refiner
19
  from .config import Settings, load_settings
20
  from .fix_loop import Cancelled, Emit, FixRequest, RefinerUnavailable
21
  from .fix_queue import QueueFull
 
162
  for file in synced:
163
  await file.load()
164
  tasks = [asyncio.create_task(sync_files())]
165
+ if settings.backend in ("llama", "zerogpu") or settings.warmup:
166
  tasks.append(asyncio.create_task(warm_up()))
167
  if settings.leaderboard_seed:
168
  tasks.append(asyncio.create_task(board.maintain(SEED_REPOS, settings.leaderboard_seed_pause)))
 
302
  return score_dict(body.content, body.threshold)
303
 
304
  @app.post("/api/fix")
305
+ async def fix(body: FixBody, request: Request) -> dict[str, Any]:
306
+ VISITOR_IP_TOKEN.set(request.headers.get("x-ip-token", "").strip())
307
  collected: dict[str, dict[str, Any]] = {}
308
  produce = producer_for(body, paced=False)
309
  await guarded(produce, lambda name, data: collected.__setitem__(name, data))
 
313
  raise HTTPException(status_code=ERROR_STATUS.get(failure["code"], 500), detail=failure)
314
 
315
  @app.post("/api/fix/stream")
316
+ async def fix_stream(body: FixBody, request: Request) -> StreamingResponse:
317
+ VISITOR_IP_TOKEN.set(request.headers.get("x-ip-token", "").strip())
318
  produce = producer_for(body, paced=True)
319
  return StreamingResponse(sse_events(produce), media_type="text/event-stream", headers=SSE_HEADERS)
320
 
server/backends.py CHANGED
@@ -1,5 +1,6 @@
1
  from __future__ import annotations
2
 
 
3
  import json
4
  import logging
5
  import re
@@ -9,11 +10,15 @@ from collections.abc import Callable, Iterator, Sequence
9
  from pathlib import Path
10
  from typing import Any, Protocol
11
 
 
 
12
  from .config import Settings
13
  from .prompt import content_key
14
 
15
  log = logging.getLogger("space.refiner")
16
 
 
 
17
  STOP = "<|im_end|>"
18
  PREFILL_CHUNK = 128
19
  MOCK_PROGRESS_STEP = 0.2
@@ -153,7 +158,8 @@ class MockRefiner:
153
  def __init__(self, settings: Settings) -> None:
154
  self.model_id = settings.model_id or "mock"
155
  self._prompt_delay = settings.mock_prompt_delay
156
- self._interval = 1.0 / settings.mock_pieces_per_second if settings.mock_pieces_per_second > 0 else 0.0
 
157
  self._prompt_budget = settings.n_ctx - settings.max_new_tokens
158
  fixtures = json.loads(Path(settings.fixtures_path).read_text(encoding="utf-8"))["fixtures"]
159
  self._replies = {fixture["key"]: fixture["reply"] for fixture in fixtures}
@@ -199,7 +205,125 @@ class MockRefiner:
199
  yield piece
200
 
201
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
  def make_refiner(settings: Settings) -> Refiner:
203
  if settings.backend == "mock":
204
  return MockRefiner(settings)
 
 
205
  return LlamaRefiner(settings)
 
1
  from __future__ import annotations
2
 
3
+ import contextvars
4
  import json
5
  import logging
6
  import re
 
10
  from pathlib import Path
11
  from typing import Any, Protocol
12
 
13
+ import httpx
14
+
15
  from .config import Settings
16
  from .prompt import content_key
17
 
18
  log = logging.getLogger("space.refiner")
19
 
20
+ VISITOR_IP_TOKEN: contextvars.ContextVar[str] = contextvars.ContextVar("visitor_ip_token", default="")
21
+
22
  STOP = "<|im_end|>"
23
  PREFILL_CHUNK = 128
24
  MOCK_PROGRESS_STEP = 0.2
 
158
  def __init__(self, settings: Settings) -> None:
159
  self.model_id = settings.model_id or "mock"
160
  self._prompt_delay = settings.mock_prompt_delay
161
+ rate = settings.mock_pieces_per_second
162
+ self._interval = 1.0 / rate if rate > 0 else 0.0
163
  self._prompt_budget = settings.n_ctx - settings.max_new_tokens
164
  fixtures = json.loads(Path(settings.fixtures_path).read_text(encoding="utf-8"))["fixtures"]
165
  self._replies = {fixture["key"]: fixture["reply"] for fixture in fixtures}
 
205
  yield piece
206
 
207
 
208
+ class ZeroGpuRefiner:
209
+ def __init__(
210
+ self,
211
+ settings: Settings,
212
+ transport: httpx.BaseTransport | None = None,
213
+ ) -> None:
214
+ self.model_id = settings.model_id or settings.zerogpu_space
215
+ self._space_id = settings.zerogpu_space
216
+ self._n_ctx = settings.n_ctx
217
+ self._max_new_tokens = settings.max_new_tokens
218
+ self._transport = transport
219
+ self._http: httpx.Client | None = None
220
+ self._load_lock = threading.Lock()
221
+
222
+ @property
223
+ def loaded(self) -> bool:
224
+ return self._http is not None
225
+
226
+ def _base_url(self) -> str:
227
+ if self._space_id.startswith(("http://", "https://")):
228
+ return self._space_id.rstrip("/")
229
+ if "/" in self._space_id:
230
+ owner, name = self._space_id.split("/", 1)
231
+ subdomain = f"{owner}-{name}".lower().replace("_", "-").replace(".", "-")
232
+ return f"https://{subdomain}.hf.space"
233
+ return f"https://{self._space_id}.hf.space"
234
+
235
+ def load(self) -> None:
236
+ with self._load_lock:
237
+ if self._http is not None:
238
+ return
239
+ transport = self._transport or httpx.HTTPTransport(local_address="0.0.0.0", retries=3)
240
+ self._http = httpx.Client(
241
+ base_url=self._base_url(),
242
+ transport=transport,
243
+ timeout=httpx.Timeout(90.0, connect=15.0),
244
+ follow_redirects=True,
245
+ )
246
+
247
+ def prompt_fits(self, prompt: str) -> bool:
248
+ return len(prompt) // 3 <= self._n_ctx - self._max_new_tokens
249
+
250
+ def _iter_sse_cumulative(
251
+ self,
252
+ event_id: str,
253
+ headers: dict[str, str],
254
+ cancel: threading.Event,
255
+ ) -> Iterator[str]:
256
+ assert self._http is not None
257
+ sse_headers = {**headers, "Accept": "text/event-stream"}
258
+ url = f"/gradio_api/call/stream_patch/{event_id}"
259
+ with self._http.stream("GET", url, headers=sse_headers) as response:
260
+ response.raise_for_status()
261
+ event_name = ""
262
+ for raw_line in response.iter_lines():
263
+ if cancel.is_set():
264
+ return
265
+ if not raw_line:
266
+ continue
267
+ if raw_line.startswith("event:"):
268
+ event_name = raw_line[6:].strip()
269
+ continue
270
+ if not raw_line.startswith("data:"):
271
+ continue
272
+ payload_text = raw_line[5:].strip()
273
+ if event_name == "error":
274
+ raise RuntimeError(f"ZeroGPU error: {payload_text}")
275
+ if payload_text == "null":
276
+ continue
277
+ parsed = json.loads(payload_text)
278
+ if isinstance(parsed, list) and parsed:
279
+ yield str(parsed[0] or "")
280
+ if event_name == "complete":
281
+ return
282
+
283
+ def stream(
284
+ self,
285
+ prompt: str,
286
+ content: str,
287
+ temperature: float,
288
+ top_p: float,
289
+ cancel: threading.Event,
290
+ on_progress: Progress,
291
+ ) -> Iterator[str]:
292
+ self.load()
293
+ assert self._http is not None
294
+ total = max(1, len(prompt) // 3)
295
+ on_progress(0, total)
296
+ if cancel.is_set():
297
+ return
298
+ ip_token = VISITOR_IP_TOKEN.get()
299
+ headers = {"X-IP-Token": ip_token} if ip_token else {}
300
+ start_res = self._http.post(
301
+ "/gradio_api/call/stream_patch",
302
+ json={"data": [prompt, self._max_new_tokens, temperature, top_p]},
303
+ headers=headers,
304
+ )
305
+ start_res.raise_for_status()
306
+ event_id = start_res.json()["event_id"]
307
+
308
+ sent = 0
309
+ progress_done = False
310
+ for cumulative in self._iter_sse_cumulative(event_id, headers, cancel):
311
+ if not progress_done:
312
+ on_progress(total, total)
313
+ progress_done = True
314
+ if len(cumulative) <= sent:
315
+ continue
316
+ delta = cumulative[sent:].split(STOP, 1)[0]
317
+ sent = len(cumulative)
318
+ for piece in split_pieces(delta):
319
+ if cancel.is_set():
320
+ return
321
+ yield piece
322
+
323
+
324
  def make_refiner(settings: Settings) -> Refiner:
325
  if settings.backend == "mock":
326
  return MockRefiner(settings)
327
+ if settings.backend == "zerogpu":
328
+ return ZeroGpuRefiner(settings)
329
  return LlamaRefiner(settings)
server/config.py CHANGED
@@ -5,7 +5,10 @@ from dataclasses import dataclass, field
5
  from pathlib import Path
6
 
7
  SPACE_DIR = Path(__file__).resolve().parents[1]
8
- REPO_ROOT = SPACE_DIR.parent
 
 
 
9
 
10
 
11
  def _env_float(env: dict[str, str], name: str, default: float) -> float:
@@ -34,6 +37,7 @@ class Settings:
34
  backend: str = "llama"
35
  model_path: str = ""
36
  model_id: str = ""
 
37
  n_ctx: int = 8192
38
  n_threads: int = 2
39
  max_new_tokens: int = 1280
@@ -91,19 +95,25 @@ def _env_text(env: dict[str, str], name: str) -> str:
91
  def load_settings(env: dict[str, str] | None = None) -> Settings:
92
  env = dict(os.environ if env is None else env)
93
  backend = env.get("REFINER_BACKEND", "llama").strip().lower() or "llama"
94
- if backend not in ("llama", "mock"):
95
- raise ValueError(f"REFINER_BACKEND must be 'llama' or 'mock', got {backend!r}")
96
 
97
  repo_id = env.get("REFINER_REPO", "").strip()
98
  file_name = env.get("REFINER_FILE", "").strip()
99
  model_path = env.get("REFINER_MODEL_PATH", "").strip()
100
- default_id = f"{repo_id}/{file_name}" if repo_id and file_name else Path(model_path).name
 
 
 
 
 
101
  model_id = env.get("REFINER_MODEL_ID", "").strip() or ("mock" if backend == "mock" else default_id)
102
 
103
  presets_env = env.get("PRESETS_PATH", "").strip()
104
  presets_path = _first_existing(
105
  *([Path(presets_env)] if presets_env else []),
106
  SPACE_DIR / "web" / "vendor" / "presets.json",
 
107
  REPO_ROOT / "docs" / "presets.json",
108
  )
109
  defaults = Settings()
@@ -111,6 +121,7 @@ def load_settings(env: dict[str, str] | None = None) -> Settings:
111
  backend=backend,
112
  model_path=model_path,
113
  model_id=model_id,
 
114
  n_threads=_env_int(env, "REFINER_THREADS", defaults.n_threads),
115
  max_file_chars=_env_int(env, "MAX_FILE_CHARS", defaults.max_file_chars),
116
  fixtures_path=Path(env.get("MOCK_FIXTURES", "").strip() or defaults.fixtures_path),
@@ -135,6 +146,6 @@ def load_settings(env: dict[str, str] | None = None) -> Settings:
135
  github_webhook_secret=_env_text(env, "GITHUB_WEBHOOK_SECRET"),
136
  github_token=_env_text(env, "GITHUB_TOKEN"),
137
  leaderboard_path=Path(_env_text(env, "LEADERBOARD_PATH") or defaults.leaderboard_path),
138
- leaderboard_seed=_env_flag(env, "LEADERBOARD_SEED", backend == "llama"),
139
  leaderboard_seed_pause=_env_float(env, "LEADERBOARD_SEED_PAUSE", defaults.leaderboard_seed_pause),
140
  )
 
5
  from pathlib import Path
6
 
7
  SPACE_DIR = Path(__file__).resolve().parents[1]
8
+ REPO_ROOT = next(
9
+ (p for p in SPACE_DIR.parents if (p / "compile.py").is_file()),
10
+ SPACE_DIR.parent,
11
+ )
12
 
13
 
14
  def _env_float(env: dict[str, str], name: str, default: float) -> float:
 
37
  backend: str = "llama"
38
  model_path: str = ""
39
  model_id: str = ""
40
+ zerogpu_space: str = "brianbellx/codehygiene-zerogpu"
41
  n_ctx: int = 8192
42
  n_threads: int = 2
43
  max_new_tokens: int = 1280
 
95
  def load_settings(env: dict[str, str] | None = None) -> Settings:
96
  env = dict(os.environ if env is None else env)
97
  backend = env.get("REFINER_BACKEND", "llama").strip().lower() or "llama"
98
+ if backend not in ("llama", "zerogpu", "mock"):
99
+ raise ValueError(f"REFINER_BACKEND must be 'llama', 'zerogpu' or 'mock', got {backend!r}")
100
 
101
  repo_id = env.get("REFINER_REPO", "").strip()
102
  file_name = env.get("REFINER_FILE", "").strip()
103
  model_path = env.get("REFINER_MODEL_PATH", "").strip()
104
+ zerogpu_space = env.get("ZEROGPU_SPACE", "brianbellx/codehygiene-zerogpu").strip()
105
+ default_id = (
106
+ zerogpu_space if backend == "zerogpu"
107
+ else f"{repo_id}/{file_name}" if repo_id and file_name
108
+ else Path(model_path).name
109
+ )
110
  model_id = env.get("REFINER_MODEL_ID", "").strip() or ("mock" if backend == "mock" else default_id)
111
 
112
  presets_env = env.get("PRESETS_PATH", "").strip()
113
  presets_path = _first_existing(
114
  *([Path(presets_env)] if presets_env else []),
115
  SPACE_DIR / "web" / "vendor" / "presets.json",
116
+ SPACE_DIR / "presets.json",
117
  REPO_ROOT / "docs" / "presets.json",
118
  )
119
  defaults = Settings()
 
121
  backend=backend,
122
  model_path=model_path,
123
  model_id=model_id,
124
+ zerogpu_space=zerogpu_space,
125
  n_threads=_env_int(env, "REFINER_THREADS", defaults.n_threads),
126
  max_file_chars=_env_int(env, "MAX_FILE_CHARS", defaults.max_file_chars),
127
  fixtures_path=Path(env.get("MOCK_FIXTURES", "").strip() or defaults.fixtures_path),
 
146
  github_webhook_secret=_env_text(env, "GITHUB_WEBHOOK_SECRET"),
147
  github_token=_env_text(env, "GITHUB_TOKEN"),
148
  leaderboard_path=Path(_env_text(env, "LEADERBOARD_PATH") or defaults.leaderboard_path),
149
+ leaderboard_seed=_env_flag(env, "LEADERBOARD_SEED", backend != "mock"),
150
  leaderboard_seed_pause=_env_float(env, "LEADERBOARD_SEED_PAUSE", defaults.leaderboard_seed_pause),
151
  )
server/fixtures/mock_patches.json CHANGED
@@ -1,103 +1,103 @@
1
- {
2
- "fixtures": [
3
- {
4
- "key": "603901a66c358a271f8bea8305951afa99fa1fec4581a303fbd3d3cd392e8ab0",
5
- "filename": "send_receipt.py",
6
- "pass": 1,
7
- "source": "handwritten",
8
- "origin": "docs/presets.json before",
9
- "squiggles_before": 3,
10
- "squiggles_after": 0,
11
- "content": "def send_receipt(order: Order) -> None:\n try:\n if order is not None:\n if order.paid and not order.refunded:\n # Extract email address from order\n email = order.email\n if email is not None:\n if len(email.strip()) > 0:\n mailer.send(email, order.id)\n except Exception:\n pass",
12
- "reply": "<<<<<<< SEARCH\ndef send_receipt(order: Order) -> None:\n try:\n if order is not None:\n if order.paid and not order.refunded:\n # Extract email address from order\n email = order.email\n if email is not None:\n if len(email.strip()) > 0:\n mailer.send(email, order.id)\n except Exception:\n pass\n=======\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\ndef send_receipt(order: Order) -> None:\n if order is None or not order.paid or order.refunded:\n return\n email = order.email\n if not email or not email.strip():\n return\n try:\n mailer.send(email, order.id)\n except Exception:\n logger.exception(\"Could not send receipt for order %s\", order.id)\n>>>>>>> REPLACE\n"
13
- },
14
- {
15
- "key": "fb26a694b102dfe43772450032b23dd08ecc96f56672ea4be0f7bad66322a32d",
16
- "filename": "pricing.ts",
17
- "pass": 1,
18
- "source": "handwritten",
19
- "origin": "docs/presets.json before",
20
- "squiggles_before": 4,
21
- "squiggles_after": 2,
22
- "content": "export class DiscountStrategyFactoryManager {\n public computeTotalAmount(cartItems: CartItem[], promoRate: number): number {\n try {\n // Step 1: Compute discounted subtotal from cart items\n const total = cartItems.filter((item) => item.active && item.qty > 0).map((item) => item.price * item.qty * (promoRate > 0 ? (promoRate > 0.5 ? 0.5 : 1 - promoRate) : 1)).reduce((acc, val) => acc + val, 0);\n return total;\n } catch (err) {\n console.log(err);\n return 0.0;\n }\n }\n}",
23
- "reply": "<<<<<<< SEARCH\n // Step 1: Compute discounted subtotal from cart items\n const total = cartItems.filter((item) => item.active && item.qty > 0).map((item) => item.price * item.qty * (promoRate > 0 ? (promoRate > 0.5 ? 0.5 : 1 - promoRate) : 1)).reduce((acc, val) => acc + val, 0);\n return total;\n=======\n const multiplier = promoRate > 0 ? 1 - Math.min(promoRate, 0.5) : 1;\n const activeItems = cartItems.filter((item) => item.active && item.qty > 0);\n return activeItems.reduce((acc, item) => acc + item.price * item.qty * multiplier, 0);\n>>>>>>> REPLACE\n"
24
- },
25
- {
26
- "key": "1b7c59b3968bb5426ae5916be0eea950aa72d7a36f610efe3d3d555c064c02ff",
27
- "filename": "frame.rs",
28
- "pass": 1,
29
- "source": "handwritten",
30
- "origin": "docs/presets.json before",
31
- "squiggles_before": 12,
32
- "squiggles_after": 10,
33
- "content": "#[allow(clippy::many_single_char_names)]\npub fn decode_frame(buf: &[u8]) -> Option<(u32, u16, u8)> {\n let mut hd = [0u8; 16];\n hd[0] = buf[12] ^ buf[28];\n hd[1] = buf[14] ^ buf[30];\n hd[2] = buf[18] ^ buf[34];\n hd[3] = buf[22] ^ buf[38];\n let mg = u16::from_be_bytes([buf[10], buf[11]]);\n let sq = u32::from_be_bytes([buf[16], buf[17], buf[18], buf[19]]);\n let ln = u16::from_be_bytes([buf[24], buf[25]]);\n let fl = buf[36] ^ buf[42];\n let ck = buf[44] ^ buf[47];\n let vr = hd[0].wrapping_add(hd[1]).wrapping_add(hd[2]);\n let ok = mg == 23112 && vr > 0 && (fl & 4) != 0 && ck != 0;\n if !ok { return None; }\n Some((sq, ln, ck))\n}",
34
- "reply": "<<<<<<< SEARCH\n let mg = u16::from_be_bytes([buf[10], buf[11]]);\n let sq = u32::from_be_bytes([buf[16], buf[17], buf[18], buf[19]]);\n let ln = u16::from_be_bytes([buf[24], buf[25]]);\n let fl = buf[36] ^ buf[42];\n let ck = buf[44] ^ buf[47];\n let vr = hd[0].wrapping_add(hd[1]).wrapping_add(hd[2]);\n let ok = mg == 23112 && vr > 0 && (fl & 4) != 0 && ck != 0;\n if !ok { return None; }\n Some((sq, ln, ck))\n=======\n let magic = u16::from_be_bytes([buf[10], buf[11]]);\n let sequence = u32::from_be_bytes([buf[16], buf[17], buf[18], buf[19]]);\n let length = u16::from_be_bytes([buf[24], buf[25]]);\n let flags = buf[36] ^ buf[42];\n let checksum = buf[44] ^ buf[47];\n let header_sum = hd[0].wrapping_add(hd[1]).wrapping_add(hd[2]);\n if magic != 23112 || header_sum == 0 || (flags & 4) == 0 || checksum == 0 {\n return None;\n }\n Some((sequence, length, checksum))\n>>>>>>> REPLACE\n"
35
- },
36
- {
37
- "key": "694945a5f10bdd90dec848e6a12a5b0e6b97158da7ffcf7f6db8a3b9273bd13a",
38
- "filename": "frame.rs",
39
- "pass": 2,
40
- "source": "handwritten",
41
- "origin": "pass-1 output",
42
- "squiggles_before": 10,
43
- "squiggles_after": 8,
44
- "content": "#[allow(clippy::many_single_char_names)]\npub fn decode_frame(buf: &[u8]) -> Option<(u32, u16, u8)> {\n let mut hd = [0u8; 16];\n hd[0] = buf[12] ^ buf[28];\n hd[1] = buf[14] ^ buf[30];\n hd[2] = buf[18] ^ buf[34];\n hd[3] = buf[22] ^ buf[38];\n let magic = u16::from_be_bytes([buf[10], buf[11]]);\n let sequence = u32::from_be_bytes([buf[16], buf[17], buf[18], buf[19]]);\n let length = u16::from_be_bytes([buf[24], buf[25]]);\n let flags = buf[36] ^ buf[42];\n let checksum = buf[44] ^ buf[47];\n let header_sum = hd[0].wrapping_add(hd[1]).wrapping_add(hd[2]);\n if magic != 23112 || header_sum == 0 || (flags & 4) == 0 || checksum == 0 {\n return None;\n }\n Some((sequence, length, checksum))\n}",
45
- "reply": "<<<<<<< SEARCH\n let mut hd = [0u8; 16];\n hd[0] = buf[12] ^ buf[28];\n hd[1] = buf[14] ^ buf[30];\n hd[2] = buf[18] ^ buf[34];\n hd[3] = buf[22] ^ buf[38];\n=======\n let header = [buf[12] ^ buf[28], buf[14] ^ buf[30], buf[18] ^ buf[34], buf[22] ^ buf[38]];\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n let header_sum = hd[0].wrapping_add(hd[1]).wrapping_add(hd[2]);\n=======\n let header_sum = header[0].wrapping_add(header[1]).wrapping_add(header[2]);\n>>>>>>> REPLACE\n"
46
- },
47
- {
48
- "key": "0e8168b89bab1d90bc459c5daaeaffcd14c49fd368aff7099136e17a4d460ad0",
49
- "filename": "webhook.go",
50
- "pass": 1,
51
- "source": "handwritten",
52
- "origin": "docs/presets.json before",
53
- "squiggles_before": 7,
54
- "squiggles_after": 3,
55
- "content": "func resolveEndpoint(region string) string {\n if region == \"us-east-1\" { return \"https://east.hooks.internal\" }\n if region == \"us-west-2\" { return \"https://west.hooks.internal\" }\n if region == \"eu-central-1\" { return \"https://eu.hooks.internal\" }\n if region == \"ap-northeast-1\" { return \"https://ap.hooks.internal\" }\n if region == \"sa-east-1\" { return \"https://sa.hooks.internal\" }\n return \"https://default.hooks.internal\"\n}\n\nfunc publishAuditEvent(httpClient *Client, region string, auditItem Event) {\n targetUrl := resolveEndpoint(region)\n bodyBytes := serializeJsonBody(auditItem)\n authToken := computeHmacSignature(bodyBytes, httpClient.signingSecret)\n statusCode := transmitHttpPost(httpClient, targetUrl, bodyBytes, authToken)\n recordTelemetryCounter(statusCode, region)\n}\n\nfunc publishBillingEvent(httpClient *Client, region string, billingItem Event) {\n targetUrl := resolveEndpoint(region)\n bodyBytes := serializeJsonBody(billingItem)\n authToken := computeHmacSignature(bodyBytes, httpClient.signingSecret)\n statusCode := transmitHttpPost(httpClient, targetUrl, bodyBytes, authToken)\n recordTelemetryCounter(statusCode, region)\n}",
56
- "reply": "<<<<<<< SEARCH\nfunc resolveEndpoint(region string) string {\n if region == \"us-east-1\" { return \"https://east.hooks.internal\" }\n if region == \"us-west-2\" { return \"https://west.hooks.internal\" }\n if region == \"eu-central-1\" { return \"https://eu.hooks.internal\" }\n if region == \"ap-northeast-1\" { return \"https://ap.hooks.internal\" }\n if region == \"sa-east-1\" { return \"https://sa.hooks.internal\" }\n return \"https://default.hooks.internal\"\n}\n=======\nvar regionEndpoints = map[string]string{\n \"us-east-1\": \"https://east.hooks.internal\",\n \"us-west-2\": \"https://west.hooks.internal\",\n \"eu-central-1\": \"https://eu.hooks.internal\",\n \"ap-northeast-1\": \"https://ap.hooks.internal\",\n \"sa-east-1\": \"https://sa.hooks.internal\",\n}\n\nfunc resolveEndpoint(region string) string {\n if endpoint, ok := regionEndpoints[region]; ok {\n return endpoint\n }\n return \"https://default.hooks.internal\"\n}\n>>>>>>> REPLACE\n"
57
- },
58
- {
59
- "key": "def4e6ca446326c5e5e83b5127daff28b28d01d51ecd3b2576bd4e7b3293e5a4",
60
- "filename": "webhook.go",
61
- "pass": 2,
62
- "source": "handwritten",
63
- "origin": "pass-1 output",
64
- "squiggles_before": 3,
65
- "squiggles_after": 0,
66
- "content": "var regionEndpoints = map[string]string{\n \"us-east-1\": \"https://east.hooks.internal\",\n \"us-west-2\": \"https://west.hooks.internal\",\n \"eu-central-1\": \"https://eu.hooks.internal\",\n \"ap-northeast-1\": \"https://ap.hooks.internal\",\n \"sa-east-1\": \"https://sa.hooks.internal\",\n}\n\nfunc resolveEndpoint(region string) string {\n if endpoint, ok := regionEndpoints[region]; ok {\n return endpoint\n }\n return \"https://default.hooks.internal\"\n}\n\nfunc publishAuditEvent(httpClient *Client, region string, auditItem Event) {\n targetUrl := resolveEndpoint(region)\n bodyBytes := serializeJsonBody(auditItem)\n authToken := computeHmacSignature(bodyBytes, httpClient.signingSecret)\n statusCode := transmitHttpPost(httpClient, targetUrl, bodyBytes, authToken)\n recordTelemetryCounter(statusCode, region)\n}\n\nfunc publishBillingEvent(httpClient *Client, region string, billingItem Event) {\n targetUrl := resolveEndpoint(region)\n bodyBytes := serializeJsonBody(billingItem)\n authToken := computeHmacSignature(bodyBytes, httpClient.signingSecret)\n statusCode := transmitHttpPost(httpClient, targetUrl, bodyBytes, authToken)\n recordTelemetryCounter(statusCode, region)\n}",
67
- "reply": "<<<<<<< SEARCH\nfunc publishAuditEvent(httpClient *Client, region string, auditItem Event) {\n targetUrl := resolveEndpoint(region)\n bodyBytes := serializeJsonBody(auditItem)\n authToken := computeHmacSignature(bodyBytes, httpClient.signingSecret)\n statusCode := transmitHttpPost(httpClient, targetUrl, bodyBytes, authToken)\n recordTelemetryCounter(statusCode, region)\n}\n\nfunc publishBillingEvent(httpClient *Client, region string, billingItem Event) {\n targetUrl := resolveEndpoint(region)\n bodyBytes := serializeJsonBody(billingItem)\n authToken := computeHmacSignature(bodyBytes, httpClient.signingSecret)\n statusCode := transmitHttpPost(httpClient, targetUrl, bodyBytes, authToken)\n recordTelemetryCounter(statusCode, region)\n}\n=======\nfunc publishEvent(httpClient *Client, region string, item Event) {\n endpoint := resolveEndpoint(region)\n body := serializeJsonBody(item)\n signature := computeHmacSignature(body, httpClient.signingSecret)\n status := transmitHttpPost(httpClient, endpoint, body, signature)\n recordTelemetryCounter(status, region)\n}\n\nfunc publishAuditEvent(httpClient *Client, region string, auditItem Event) {\n publishEvent(httpClient, region, auditItem)\n}\n\nfunc publishBillingEvent(httpClient *Client, region string, billingItem Event) {\n publishEvent(httpClient, region, billingItem)\n}\n>>>>>>> REPLACE\n"
68
- },
69
- {
70
- "key": "e06eb41fc26eac74527f6145b19c1796c95d167092e4be3202d71ae449601e02",
71
- "filename": "engine.js",
72
- "pass": 1,
73
- "source": "handwritten",
74
- "origin": "docs/presets.json before",
75
- "squiggles_before": 7,
76
- "squiggles_after": 5,
77
- "content": "export function unpack(tb, vb, ms) {\n let sp, ft, bo, vo, bv, ds;\n // TODO: clean up golfed trit unpacking\n sp = ms.split(\"|\");\n ft = new Int8Array(tb.length * 5);\n bo = 0;\n vo = 0;\n for (let i = 0; i < tb.length; i++) {\n bv = tb[i];\n ds = i * 5;\n ft[ds] = (((bv % 3) + 1) % 3) - 1;\n ft[ds + 1] = (((Math.floor(bv / 3) % 3) + 1) % 3) - 1;\n ft[ds + 2] = (((Math.floor(bv / 9) % 3) + 1) % 3) - 1;\n ft[ds + 3] = (((Math.floor(bv / 27) % 3) + 1) % 3) - 1;\n ft[ds + 4] = (((Math.floor(bv / 81) % 3) + 1) % 3) - 1;\n }\n try {\n return sp[0].length > 0 && bo >= vo ? ft : (vb || []);\n } catch (e) {}\n}",
78
- "reply": "<<<<<<< SEARCH\n try {\n return sp[0].length > 0 && bo >= vo ? ft : (vb || []);\n } catch (e) {}\n=======\n if (sp[0].length > 0 && bo >= vo) {\n return ft;\n }\n return vb ? vb : [];\n>>>>>>> REPLACE\n"
79
- },
80
- {
81
- "key": "5026dc2109a6c6eeceb284475e808c2dc1ff30327232235e4296a4fe404b5ce8",
82
- "filename": "engine.js",
83
- "pass": 2,
84
- "source": "handwritten",
85
- "origin": "pass-1 output",
86
- "squiggles_before": 5,
87
- "squiggles_after": 0,
88
- "content": "export function unpack(tb, vb, ms) {\n let sp, ft, bo, vo, bv, ds;\n // TODO: clean up golfed trit unpacking\n sp = ms.split(\"|\");\n ft = new Int8Array(tb.length * 5);\n bo = 0;\n vo = 0;\n for (let i = 0; i < tb.length; i++) {\n bv = tb[i];\n ds = i * 5;\n ft[ds] = (((bv % 3) + 1) % 3) - 1;\n ft[ds + 1] = (((Math.floor(bv / 3) % 3) + 1) % 3) - 1;\n ft[ds + 2] = (((Math.floor(bv / 9) % 3) + 1) % 3) - 1;\n ft[ds + 3] = (((Math.floor(bv / 27) % 3) + 1) % 3) - 1;\n ft[ds + 4] = (((Math.floor(bv / 81) % 3) + 1) % 3) - 1;\n }\n if (sp[0].length > 0 && bo >= vo) {\n return ft;\n }\n return vb ? vb : [];\n}",
89
- "reply": "<<<<<<< SEARCH\nexport function unpack(tb, vb, ms) {\n let sp, ft, bo, vo, bv, ds;\n // TODO: clean up golfed trit unpacking\n sp = ms.split(\"|\");\n ft = new Int8Array(tb.length * 5);\n bo = 0;\n vo = 0;\n for (let i = 0; i < tb.length; i++) {\n bv = tb[i];\n ds = i * 5;\n ft[ds] = (((bv % 3) + 1) % 3) - 1;\n ft[ds + 1] = (((Math.floor(bv / 3) % 3) + 1) % 3) - 1;\n ft[ds + 2] = (((Math.floor(bv / 9) % 3) + 1) % 3) - 1;\n ft[ds + 3] = (((Math.floor(bv / 27) % 3) + 1) % 3) - 1;\n ft[ds + 4] = (((Math.floor(bv / 81) % 3) + 1) % 3) - 1;\n }\n if (sp[0].length > 0 && bo >= vo) {\n return ft;\n }\n return vb ? vb : [];\n=======\nexport function unpack(tritBytes, fallback, manifest) {\n const sections = manifest.split(\"|\");\n const trits = new Int8Array(tritBytes.length * 5);\n for (let i = 0; i < tritBytes.length; i++) {\n const packed = tritBytes[i];\n const base = i * 5;\n trits[base] = (((packed % 3) + 1) % 3) - 1;\n trits[base + 1] = (((Math.floor(packed / 3) % 3) + 1) % 3) - 1;\n trits[base + 2] = (((Math.floor(packed / 9) % 3) + 1) % 3) - 1;\n trits[base + 3] = (((Math.floor(packed / 27) % 3) + 1) % 3) - 1;\n trits[base + 4] = (((Math.floor(packed / 81) % 3) + 1) % 3) - 1;\n }\n if (sections[0].length > 0) {\n return trits;\n }\n return fallback ? fallback : [];\n>>>>>>> REPLACE\n"
90
- },
91
- {
92
- "key": "924c910f843823ebb2889d773d89212f28bb465f7197f360417cac41e8cd2e8e",
93
- "filename": "index.js",
94
- "pass": 1,
95
- "source": "handwritten",
96
- "origin": "github:lukeed/clsx@925494cf31bcd97d3337aacd34e659e80cae7fe2:src/index.js",
97
- "squiggles_before": 2,
98
- "squiggles_after": 0,
99
- "content": "function toVal(mix) {\n\tvar k, y, str='';\n\n\tif (typeof mix === 'string' || typeof mix === 'number') {\n\t\tstr += mix;\n\t} else if (typeof mix === 'object') {\n\t\tif (Array.isArray(mix)) {\n\t\t\tvar len=mix.length;\n\t\t\tfor (k=0; k < len; k++) {\n\t\t\t\tif (mix[k]) {\n\t\t\t\t\tif (y = toVal(mix[k])) {\n\t\t\t\t\t\tstr && (str += ' ');\n\t\t\t\t\t\tstr += y;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tfor (y in mix) {\n\t\t\t\tif (mix[y]) {\n\t\t\t\t\tstr && (str += ' ');\n\t\t\t\t\tstr += y;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn str;\n}\n\nexport function clsx() {\n\tvar i=0, tmp, x, str='', len=arguments.length;\n\tfor (; i < len; i++) {\n\t\tif (tmp = arguments[i]) {\n\t\t\tif (x = toVal(tmp)) {\n\t\t\t\tstr && (str += ' ');\n\t\t\t\tstr += x\n\t\t\t}\n\t\t}\n\t}\n\treturn str;\n}\n\nexport default clsx;\n",
100
- "reply": "<<<<<<< SEARCH\n\t\t\t\tif (mix[k]) {\n\t\t\t\t\tif (y = toVal(mix[k])) {\n\t\t\t\t\t\tstr && (str += ' ');\n\t\t\t\t\t\tstr += y;\n\t\t\t\t\t}\n\t\t\t\t}\n=======\n\t\t\t\tif (mix[k] && (y = toVal(mix[k]))) {\n\t\t\t\t\tstr && (str += ' ');\n\t\t\t\t\tstr += y;\n\t\t\t\t}\n>>>>>>> REPLACE"
101
- }
102
- ]
103
- }
 
1
+ {
2
+ "fixtures": [
3
+ {
4
+ "key": "603901a66c358a271f8bea8305951afa99fa1fec4581a303fbd3d3cd392e8ab0",
5
+ "filename": "send_receipt.py",
6
+ "pass": 1,
7
+ "source": "handwritten",
8
+ "origin": "docs/presets.json before",
9
+ "squiggles_before": 3,
10
+ "squiggles_after": 0,
11
+ "content": "def send_receipt(order: Order) -> None:\n try:\n if order is not None:\n if order.paid and not order.refunded:\n # Extract email address from order\n email = order.email\n if email is not None:\n if len(email.strip()) > 0:\n mailer.send(email, order.id)\n except Exception:\n pass",
12
+ "reply": "<<<<<<< SEARCH\ndef send_receipt(order: Order) -> None:\n try:\n if order is not None:\n if order.paid and not order.refunded:\n # Extract email address from order\n email = order.email\n if email is not None:\n if len(email.strip()) > 0:\n mailer.send(email, order.id)\n except Exception:\n pass\n=======\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\ndef send_receipt(order: Order) -> None:\n if order is None or not order.paid or order.refunded:\n return\n email = order.email\n if not email or not email.strip():\n return\n try:\n mailer.send(email, order.id)\n except Exception:\n logger.exception(\"Could not send receipt for order %s\", order.id)\n>>>>>>> REPLACE\n"
13
+ },
14
+ {
15
+ "key": "fb26a694b102dfe43772450032b23dd08ecc96f56672ea4be0f7bad66322a32d",
16
+ "filename": "pricing.ts",
17
+ "pass": 1,
18
+ "source": "handwritten",
19
+ "origin": "docs/presets.json before",
20
+ "squiggles_before": 4,
21
+ "squiggles_after": 2,
22
+ "content": "export class DiscountStrategyFactoryManager {\n public computeTotalAmount(cartItems: CartItem[], promoRate: number): number {\n try {\n // Step 1: Compute discounted subtotal from cart items\n const total = cartItems.filter((item) => item.active && item.qty > 0).map((item) => item.price * item.qty * (promoRate > 0 ? (promoRate > 0.5 ? 0.5 : 1 - promoRate) : 1)).reduce((acc, val) => acc + val, 0);\n return total;\n } catch (err) {\n console.log(err);\n return 0.0;\n }\n }\n}",
23
+ "reply": "<<<<<<< SEARCH\n // Step 1: Compute discounted subtotal from cart items\n const total = cartItems.filter((item) => item.active && item.qty > 0).map((item) => item.price * item.qty * (promoRate > 0 ? (promoRate > 0.5 ? 0.5 : 1 - promoRate) : 1)).reduce((acc, val) => acc + val, 0);\n return total;\n=======\n const multiplier = promoRate > 0 ? 1 - Math.min(promoRate, 0.5) : 1;\n const activeItems = cartItems.filter((item) => item.active && item.qty > 0);\n return activeItems.reduce((acc, item) => acc + item.price * item.qty * multiplier, 0);\n>>>>>>> REPLACE\n"
24
+ },
25
+ {
26
+ "key": "1b7c59b3968bb5426ae5916be0eea950aa72d7a36f610efe3d3d555c064c02ff",
27
+ "filename": "frame.rs",
28
+ "pass": 1,
29
+ "source": "handwritten",
30
+ "origin": "docs/presets.json before",
31
+ "squiggles_before": 10,
32
+ "squiggles_after": 8,
33
+ "content": "#[allow(clippy::many_single_char_names)]\npub fn decode_frame(buf: &[u8]) -> Option<(u32, u16, u8)> {\n let mut hd = [0u8; 16];\n hd[0] = buf[12] ^ buf[28];\n hd[1] = buf[14] ^ buf[30];\n hd[2] = buf[18] ^ buf[34];\n hd[3] = buf[22] ^ buf[38];\n let mg = u16::from_be_bytes([buf[10], buf[11]]);\n let sq = u32::from_be_bytes([buf[16], buf[17], buf[18], buf[19]]);\n let ln = u16::from_be_bytes([buf[24], buf[25]]);\n let fl = buf[36] ^ buf[42];\n let ck = buf[44] ^ buf[47];\n let vr = hd[0].wrapping_add(hd[1]).wrapping_add(hd[2]);\n let ok = mg == 23112 && vr > 0 && (fl & 4) != 0 && ck != 0;\n if !ok { return None; }\n Some((sq, ln, ck))\n}",
34
+ "reply": "<<<<<<< SEARCH\n let mg = u16::from_be_bytes([buf[10], buf[11]]);\n let sq = u32::from_be_bytes([buf[16], buf[17], buf[18], buf[19]]);\n let ln = u16::from_be_bytes([buf[24], buf[25]]);\n let fl = buf[36] ^ buf[42];\n let ck = buf[44] ^ buf[47];\n let vr = hd[0].wrapping_add(hd[1]).wrapping_add(hd[2]);\n let ok = mg == 23112 && vr > 0 && (fl & 4) != 0 && ck != 0;\n if !ok { return None; }\n Some((sq, ln, ck))\n=======\n const MAGIC_POS: usize = 10;\n const SEQ_POS: usize = 16;\n const LEN_POS: usize = 24;\n const FLAGS_POS: (usize, usize) = (36, 42);\n const CHECK_POS: (usize, usize) = (44, 47);\n let magic = u16::from_be_bytes([buf[MAGIC_POS], buf[MAGIC_POS + 1]]);\n let sequence = u32::from_be_bytes(buf[SEQ_POS..SEQ_POS + 4].try_into().unwrap());\n let length = u16::from_be_bytes([buf[LEN_POS], buf[LEN_POS + 1]]);\n let flags = buf[FLAGS_POS.0] ^ buf[FLAGS_POS.1];\n let checksum = buf[CHECK_POS.0] ^ buf[CHECK_POS.1];\n let header_sum = hd[0].wrapping_add(hd[1]).wrapping_add(hd[2]);\n if magic != 23112 || header_sum == 0 || (flags & 4) == 0 || checksum == 0 {\n return None;\n }\n Some((sequence, length, checksum))\n>>>>>>> REPLACE\n"
35
+ },
36
+ {
37
+ "key": "c18b0b04d282fac62340e8c4c5eb3556972dc80047bacd887ccdfa76a4e9a7ba",
38
+ "filename": "frame.rs",
39
+ "pass": 2,
40
+ "source": "handwritten",
41
+ "origin": "pass-1 output",
42
+ "squiggles_before": 8,
43
+ "squiggles_after": 1,
44
+ "content": "#[allow(clippy::many_single_char_names)]\npub fn decode_frame(buf: &[u8]) -> Option<(u32, u16, u8)> {\n let mut hd = [0u8; 16];\n hd[0] = buf[12] ^ buf[28];\n hd[1] = buf[14] ^ buf[30];\n hd[2] = buf[18] ^ buf[34];\n hd[3] = buf[22] ^ buf[38];\n const MAGIC_POS: usize = 10;\n const SEQ_POS: usize = 16;\n const LEN_POS: usize = 24;\n const FLAGS_POS: (usize, usize) = (36, 42);\n const CHECK_POS: (usize, usize) = (44, 47);\n let magic = u16::from_be_bytes([buf[MAGIC_POS], buf[MAGIC_POS + 1]]);\n let sequence = u32::from_be_bytes(buf[SEQ_POS..SEQ_POS + 4].try_into().unwrap());\n let length = u16::from_be_bytes([buf[LEN_POS], buf[LEN_POS + 1]]);\n let flags = buf[FLAGS_POS.0] ^ buf[FLAGS_POS.1];\n let checksum = buf[CHECK_POS.0] ^ buf[CHECK_POS.1];\n let header_sum = hd[0].wrapping_add(hd[1]).wrapping_add(hd[2]);\n if magic != 23112 || header_sum == 0 || (flags & 4) == 0 || checksum == 0 {\n return None;\n }\n Some((sequence, length, checksum))\n}",
45
+ "reply": "<<<<<<< SEARCH\n#[allow(clippy::many_single_char_names)]\npub fn decode_frame(buf: &[u8]) -> Option<(u32, u16, u8)> {\n let mut hd = [0u8; 16];\n hd[0] = buf[12] ^ buf[28];\n hd[1] = buf[14] ^ buf[30];\n hd[2] = buf[18] ^ buf[34];\n hd[3] = buf[22] ^ buf[38];\n=======\npub fn decode_frame(buf: &[u8]) -> Option<(u32, u16, u8)> {\n const HEADER_PAIRS: [(usize, usize); 4] = [(12, 28), (14, 30), (18, 34), (22, 38)];\n let mut header = [0u8; 16];\n for (idx, &(left, right)) in HEADER_PAIRS.iter().enumerate() {\n header[idx] = buf[left] ^ buf[right];\n }\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n let header_sum = hd[0].wrapping_add(hd[1]).wrapping_add(hd[2]);\n=======\n let header_sum = header.iter().take(3).copied().fold(0u8, u8::wrapping_add);\n>>>>>>> REPLACE\n"
46
+ },
47
+ {
48
+ "key": "0e8168b89bab1d90bc459c5daaeaffcd14c49fd368aff7099136e17a4d460ad0",
49
+ "filename": "webhook.go",
50
+ "pass": 1,
51
+ "source": "handwritten",
52
+ "origin": "docs/presets.json before",
53
+ "squiggles_before": 7,
54
+ "squiggles_after": 2,
55
+ "content": "func resolveEndpoint(region string) string {\n if region == \"us-east-1\" { return \"https://east.hooks.internal\" }\n if region == \"us-west-2\" { return \"https://west.hooks.internal\" }\n if region == \"eu-central-1\" { return \"https://eu.hooks.internal\" }\n if region == \"ap-northeast-1\" { return \"https://ap.hooks.internal\" }\n if region == \"sa-east-1\" { return \"https://sa.hooks.internal\" }\n return \"https://default.hooks.internal\"\n}\n\nfunc publishAuditEvent(httpClient *Client, region string, auditItem Event) {\n targetUrl := resolveEndpoint(region)\n bodyBytes := serializeJsonBody(auditItem)\n authToken := computeHmacSignature(bodyBytes, httpClient.signingSecret)\n statusCode := transmitHttpPost(httpClient, targetUrl, bodyBytes, authToken)\n recordTelemetryCounter(statusCode, region)\n}\n\nfunc publishBillingEvent(httpClient *Client, region string, billingItem Event) {\n targetUrl := resolveEndpoint(region)\n bodyBytes := serializeJsonBody(billingItem)\n authToken := computeHmacSignature(bodyBytes, httpClient.signingSecret)\n statusCode := transmitHttpPost(httpClient, targetUrl, bodyBytes, authToken)\n recordTelemetryCounter(statusCode, region)\n}",
56
+ "reply": "<<<<<<< SEARCH\nfunc resolveEndpoint(region string) string {\n if region == \"us-east-1\" { return \"https://east.hooks.internal\" }\n if region == \"us-west-2\" { return \"https://west.hooks.internal\" }\n if region == \"eu-central-1\" { return \"https://eu.hooks.internal\" }\n if region == \"ap-northeast-1\" { return \"https://ap.hooks.internal\" }\n if region == \"sa-east-1\" { return \"https://sa.hooks.internal\" }\n return \"https://default.hooks.internal\"\n}\n=======\nvar regionEndpoints = map[string]string{\n \"us-east-1\": \"https://east.hooks.internal\",\n \"us-west-2\": \"https://west.hooks.internal\",\n \"eu-central-1\": \"https://eu.hooks.internal\",\n \"ap-northeast-1\": \"https://ap.hooks.internal\",\n \"sa-east-1\": \"https://sa.hooks.internal\",\n}\n\nfunc resolveEndpoint(region string) string {\n if endpoint, ok := regionEndpoints[region]; ok {\n return endpoint\n }\n return \"https://default.hooks.internal\"\n}\n>>>>>>> REPLACE\n"
57
+ },
58
+ {
59
+ "key": "def4e6ca446326c5e5e83b5127daff28b28d01d51ecd3b2576bd4e7b3293e5a4",
60
+ "filename": "webhook.go",
61
+ "pass": 2,
62
+ "source": "handwritten",
63
+ "origin": "pass-1 output",
64
+ "squiggles_before": 2,
65
+ "squiggles_after": 0,
66
+ "content": "var regionEndpoints = map[string]string{\n \"us-east-1\": \"https://east.hooks.internal\",\n \"us-west-2\": \"https://west.hooks.internal\",\n \"eu-central-1\": \"https://eu.hooks.internal\",\n \"ap-northeast-1\": \"https://ap.hooks.internal\",\n \"sa-east-1\": \"https://sa.hooks.internal\",\n}\n\nfunc resolveEndpoint(region string) string {\n if endpoint, ok := regionEndpoints[region]; ok {\n return endpoint\n }\n return \"https://default.hooks.internal\"\n}\n\nfunc publishAuditEvent(httpClient *Client, region string, auditItem Event) {\n targetUrl := resolveEndpoint(region)\n bodyBytes := serializeJsonBody(auditItem)\n authToken := computeHmacSignature(bodyBytes, httpClient.signingSecret)\n statusCode := transmitHttpPost(httpClient, targetUrl, bodyBytes, authToken)\n recordTelemetryCounter(statusCode, region)\n}\n\nfunc publishBillingEvent(httpClient *Client, region string, billingItem Event) {\n targetUrl := resolveEndpoint(region)\n bodyBytes := serializeJsonBody(billingItem)\n authToken := computeHmacSignature(bodyBytes, httpClient.signingSecret)\n statusCode := transmitHttpPost(httpClient, targetUrl, bodyBytes, authToken)\n recordTelemetryCounter(statusCode, region)\n}",
67
+ "reply": "<<<<<<< SEARCH\nfunc publishAuditEvent(httpClient *Client, region string, auditItem Event) {\n targetUrl := resolveEndpoint(region)\n bodyBytes := serializeJsonBody(auditItem)\n authToken := computeHmacSignature(bodyBytes, httpClient.signingSecret)\n statusCode := transmitHttpPost(httpClient, targetUrl, bodyBytes, authToken)\n recordTelemetryCounter(statusCode, region)\n}\n\nfunc publishBillingEvent(httpClient *Client, region string, billingItem Event) {\n targetUrl := resolveEndpoint(region)\n bodyBytes := serializeJsonBody(billingItem)\n authToken := computeHmacSignature(bodyBytes, httpClient.signingSecret)\n statusCode := transmitHttpPost(httpClient, targetUrl, bodyBytes, authToken)\n recordTelemetryCounter(statusCode, region)\n}\n=======\nfunc publishEvent(httpClient *Client, region string, item Event) {\n endpoint := resolveEndpoint(region)\n body := serializeJsonBody(item)\n signature := computeHmacSignature(body, httpClient.signingSecret)\n status := transmitHttpPost(httpClient, endpoint, body, signature)\n recordTelemetryCounter(status, region)\n}\n\nfunc publishAuditEvent(httpClient *Client, region string, auditItem Event) {\n publishEvent(httpClient, region, auditItem)\n}\n\nfunc publishBillingEvent(httpClient *Client, region string, billingItem Event) {\n publishEvent(httpClient, region, billingItem)\n}\n>>>>>>> REPLACE\n"
68
+ },
69
+ {
70
+ "key": "e06eb41fc26eac74527f6145b19c1796c95d167092e4be3202d71ae449601e02",
71
+ "filename": "engine.js",
72
+ "pass": 1,
73
+ "source": "handwritten",
74
+ "origin": "docs/presets.json before",
75
+ "squiggles_before": 7,
76
+ "squiggles_after": 5,
77
+ "content": "export function unpack(tb, vb, ms) {\n let sp, ft, bo, vo, bv, ds;\n // TODO: clean up golfed trit unpacking\n sp = ms.split(\"|\");\n ft = new Int8Array(tb.length * 5);\n bo = 0;\n vo = 0;\n for (let i = 0; i < tb.length; i++) {\n bv = tb[i];\n ds = i * 5;\n ft[ds] = (((bv % 3) + 1) % 3) - 1;\n ft[ds + 1] = (((Math.floor(bv / 3) % 3) + 1) % 3) - 1;\n ft[ds + 2] = (((Math.floor(bv / 9) % 3) + 1) % 3) - 1;\n ft[ds + 3] = (((Math.floor(bv / 27) % 3) + 1) % 3) - 1;\n ft[ds + 4] = (((Math.floor(bv / 81) % 3) + 1) % 3) - 1;\n }\n try {\n return sp[0].length > 0 && bo >= vo ? ft : (vb || []);\n } catch (e) {}\n}",
78
+ "reply": "<<<<<<< SEARCH\n try {\n return sp[0].length > 0 && bo >= vo ? ft : (vb || []);\n } catch (e) {}\n=======\n if (sp[0].length > 0 && bo >= vo) {\n return ft;\n }\n return vb ? vb : [];\n>>>>>>> REPLACE\n"
79
+ },
80
+ {
81
+ "key": "5026dc2109a6c6eeceb284475e808c2dc1ff30327232235e4296a4fe404b5ce8",
82
+ "filename": "engine.js",
83
+ "pass": 2,
84
+ "source": "handwritten",
85
+ "origin": "pass-1 output",
86
+ "squiggles_before": 5,
87
+ "squiggles_after": 0,
88
+ "content": "export function unpack(tb, vb, ms) {\n let sp, ft, bo, vo, bv, ds;\n // TODO: clean up golfed trit unpacking\n sp = ms.split(\"|\");\n ft = new Int8Array(tb.length * 5);\n bo = 0;\n vo = 0;\n for (let i = 0; i < tb.length; i++) {\n bv = tb[i];\n ds = i * 5;\n ft[ds] = (((bv % 3) + 1) % 3) - 1;\n ft[ds + 1] = (((Math.floor(bv / 3) % 3) + 1) % 3) - 1;\n ft[ds + 2] = (((Math.floor(bv / 9) % 3) + 1) % 3) - 1;\n ft[ds + 3] = (((Math.floor(bv / 27) % 3) + 1) % 3) - 1;\n ft[ds + 4] = (((Math.floor(bv / 81) % 3) + 1) % 3) - 1;\n }\n if (sp[0].length > 0 && bo >= vo) {\n return ft;\n }\n return vb ? vb : [];\n}",
89
+ "reply": "<<<<<<< SEARCH\nexport function unpack(tb, vb, ms) {\n let sp, ft, bo, vo, bv, ds;\n // TODO: clean up golfed trit unpacking\n sp = ms.split(\"|\");\n ft = new Int8Array(tb.length * 5);\n bo = 0;\n vo = 0;\n for (let i = 0; i < tb.length; i++) {\n bv = tb[i];\n ds = i * 5;\n ft[ds] = (((bv % 3) + 1) % 3) - 1;\n ft[ds + 1] = (((Math.floor(bv / 3) % 3) + 1) % 3) - 1;\n ft[ds + 2] = (((Math.floor(bv / 9) % 3) + 1) % 3) - 1;\n ft[ds + 3] = (((Math.floor(bv / 27) % 3) + 1) % 3) - 1;\n ft[ds + 4] = (((Math.floor(bv / 81) % 3) + 1) % 3) - 1;\n }\n if (sp[0].length > 0 && bo >= vo) {\n return ft;\n }\n return vb ? vb : [];\n=======\nexport function unpack(tritBytes, fallback, manifest) {\n const sections = manifest.split(\"|\");\n const trits = new Int8Array(tritBytes.length * 5);\n for (let i = 0; i < tritBytes.length; i++) {\n const packed = tritBytes[i];\n const base = i * 5;\n trits[base] = (((packed % 3) + 1) % 3) - 1;\n trits[base + 1] = (((Math.floor(packed / 3) % 3) + 1) % 3) - 1;\n trits[base + 2] = (((Math.floor(packed / 9) % 3) + 1) % 3) - 1;\n trits[base + 3] = (((Math.floor(packed / 27) % 3) + 1) % 3) - 1;\n trits[base + 4] = (((Math.floor(packed / 81) % 3) + 1) % 3) - 1;\n }\n if (sections[0].length > 0) {\n return trits;\n }\n return fallback ? fallback : [];\n>>>>>>> REPLACE\n"
90
+ },
91
+ {
92
+ "key": "924c910f843823ebb2889d773d89212f28bb465f7197f360417cac41e8cd2e8e",
93
+ "filename": "index.js",
94
+ "pass": 1,
95
+ "source": "handwritten",
96
+ "origin": "github:lukeed/clsx@925494cf31bcd97d3337aacd34e659e80cae7fe2:src/index.js",
97
+ "squiggles_before": 2,
98
+ "squiggles_after": 0,
99
+ "content": "function toVal(mix) {\n\tvar k, y, str='';\n\n\tif (typeof mix === 'string' || typeof mix === 'number') {\n\t\tstr += mix;\n\t} else if (typeof mix === 'object') {\n\t\tif (Array.isArray(mix)) {\n\t\t\tvar len=mix.length;\n\t\t\tfor (k=0; k < len; k++) {\n\t\t\t\tif (mix[k]) {\n\t\t\t\t\tif (y = toVal(mix[k])) {\n\t\t\t\t\t\tstr && (str += ' ');\n\t\t\t\t\t\tstr += y;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tfor (y in mix) {\n\t\t\t\tif (mix[y]) {\n\t\t\t\t\tstr && (str += ' ');\n\t\t\t\t\tstr += y;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn str;\n}\n\nexport function clsx() {\n\tvar i=0, tmp, x, str='', len=arguments.length;\n\tfor (; i < len; i++) {\n\t\tif (tmp = arguments[i]) {\n\t\t\tif (x = toVal(tmp)) {\n\t\t\t\tstr && (str += ' ');\n\t\t\t\tstr += x\n\t\t\t}\n\t\t}\n\t}\n\treturn str;\n}\n\nexport default clsx;\n",
100
+ "reply": "<<<<<<< SEARCH\n\t\t\t\tif (mix[k]) {\n\t\t\t\t\tif (y = toVal(mix[k])) {\n\t\t\t\t\t\tstr && (str += ' ');\n\t\t\t\t\t\tstr += y;\n\t\t\t\t\t}\n\t\t\t\t}\n=======\n\t\t\t\tif (mix[k] && (y = toVal(mix[k]))) {\n\t\t\t\t\tstr && (str += ' ');\n\t\t\t\t\tstr += y;\n\t\t\t\t}\n>>>>>>> REPLACE"
101
+ }
102
+ ]
103
+ }
server/hygiene.py CHANGED
@@ -6,7 +6,10 @@ import sys
6
  from pathlib import Path
7
  from typing import Any
8
 
9
- REPO_ROOT = Path(__file__).resolve().parents[2]
 
 
 
10
  LOCAL_PACKAGE = REPO_ROOT / "codehygiene" / "__init__.py"
11
 
12
  if importlib.util.find_spec("codehygiene") is None and LOCAL_PACKAGE.is_file():
 
6
  from pathlib import Path
7
  from typing import Any
8
 
9
+ REPO_ROOT = next(
10
+ (p for p in Path(__file__).resolve().parents if (p / "codehygiene" / "__init__.py").is_file()),
11
+ Path(__file__).resolve().parents[2],
12
+ )
13
  LOCAL_PACKAGE = REPO_ROOT / "codehygiene" / "__init__.py"
14
 
15
  if importlib.util.find_spec("codehygiene") is None and LOCAL_PACKAGE.is_file():
server/prompt.py CHANGED
@@ -11,7 +11,7 @@ def render_chatml(messages: list[dict[str, str]]) -> str:
11
  return (
12
  f"<|im_start|>system\n{system['content']}<|im_end|>\n"
13
  f"<|im_start|>user\n{user['content']}<|im_end|>\n"
14
- "<|im_start|>assistant\n"
15
  )
16
 
17
 
 
11
  return (
12
  f"<|im_start|>system\n{system['content']}<|im_end|>\n"
13
  f"<|im_start|>user\n{user['content']}<|im_end|>\n"
14
+ "<|im_start|>assistant\n<think>\n\n</think>\n\n"
15
  )
16
 
17
 
server/service.py CHANGED
@@ -1,6 +1,7 @@
1
  from __future__ import annotations
2
 
3
  import asyncio
 
4
  import json
5
  import logging
6
  import time
@@ -89,7 +90,8 @@ class FixService:
89
  try:
90
  await self.queue.wait_turn(ticket, lambda position: emit("queue", {"position": position}))
91
  run = FixRun(self.refiner, request, ticket.cancel, thread_emit, self.settings.max_file_chars)
92
- future = self._executor.submit(run.run)
 
93
  future.add_done_callback(lambda _: loop.call_soon_threadsafe(self.queue.release, ticket))
94
  await asyncio.wrap_future(future)
95
  finally:
 
1
  from __future__ import annotations
2
 
3
  import asyncio
4
+ import contextvars
5
  import json
6
  import logging
7
  import time
 
90
  try:
91
  await self.queue.wait_turn(ticket, lambda position: emit("queue", {"position": position}))
92
  run = FixRun(self.refiner, request, ticket.cancel, thread_emit, self.settings.max_file_chars)
93
+ ctx = contextvars.copy_context()
94
+ future = self._executor.submit(ctx.run, run.run)
95
  future.add_done_callback(lambda _: loop.call_soon_threadsafe(self.queue.release, ticket))
96
  await asyncio.wrap_future(future)
97
  finally:
server/telemetry.py CHANGED
@@ -263,13 +263,13 @@ class Telemetry:
263
 
264
  def record_clean(self, filename: str, content: str, done: Mapping[str, Any]) -> bool:
265
  """Count one accepted refiner run; the file counts once however often it is cleaned."""
266
- if not done.get("accepted"):
 
 
267
  return False
268
  self.stats["fix_runs"] += 1
269
  self.dirty = True
270
- ext = extension_of(filename)
271
- digest = content_digest(ext, content)
272
- if digest in self.excluded or not self.seen_cleaned.add(digest):
273
  return False
274
  before, after = done["before_hygiene"], done["after_hygiene"]
275
  self.stats["files_cleaned"] += 1
 
263
 
264
  def record_clean(self, filename: str, content: str, done: Mapping[str, Any]) -> bool:
265
  """Count one accepted refiner run; the file counts once however often it is cleaned."""
266
+ ext = extension_of(filename)
267
+ digest = content_digest(ext, content)
268
+ if not done.get("accepted") or digest in self.excluded:
269
  return False
270
  self.stats["fix_runs"] += 1
271
  self.dirty = True
272
+ if not self.seen_cleaned.add(digest):
 
 
273
  return False
274
  before, after = done["before_hygiene"], done["after_hygiene"]
275
  self.stats["files_cleaned"] += 1
web/build.mjs CHANGED
@@ -8,19 +8,30 @@ const webDir = path.dirname(fileURLToPath(import.meta.url));
8
  const srcDir = path.join(webDir, "src");
9
  const distDir = path.join(webDir, "dist");
10
  const vendorDir = path.join(webDir, "vendor");
11
- const docsDir = path.resolve(webDir, "../../docs");
 
12
  const SHARED_FILES = ["engine.js", "presets.json", "weights.npz"];
13
  const watch = process.argv.includes("--watch");
14
 
15
- function sharedDir() {
16
- const vendored = SHARED_FILES.every((name) => existsSync(path.join(vendorDir, name)));
17
- return vendored ? vendorDir : docsDir;
 
 
 
 
 
 
 
 
 
 
18
  }
19
 
20
- function sharedFilesPlugin(sourceDir) {
21
  const targets = {
22
- "shared:engine": path.join(sourceDir, "engine.js"),
23
- "shared:presets": path.join(sourceDir, "presets.json"),
24
  };
25
  return {
26
  name: "shared-files",
@@ -33,27 +44,30 @@ function sharedFilesPlugin(sourceDir) {
33
  };
34
  }
35
 
36
- async function copyStatic(sourceDir) {
37
- const boardDir = path.join(distDir, "leaderboard");
38
- await mkdir(boardDir, { recursive: true });
39
  await copyFile(path.join(srcDir, "index.html"), path.join(distDir, "index.html"));
40
- await copyFile(path.join(srcDir, "board.html"), path.join(boardDir, "index.html"));
41
- await copyFile(path.join(sourceDir, "weights.npz"), path.join(distDir, "weights.npz"));
 
 
 
42
  }
43
 
44
- const copyStaticPlugin = (sourceDir) => ({
45
  name: "copy-static",
46
  setup(build) {
47
  build.onEnd(async (result) => {
48
  if (result.errors.length === 0) {
49
- await copyStatic(sourceDir);
50
  }
51
  });
52
  },
53
  });
54
 
55
  async function main() {
56
- const sourceDir = sharedDir();
57
  await rm(distDir, { recursive: true, force: true });
58
  await mkdir(distDir, { recursive: true });
59
 
@@ -62,7 +76,9 @@ async function main() {
62
  app: path.join(srcDir, "main.js"),
63
  board: path.join(srcDir, "board.js"),
64
  "score-worker": path.join(srcDir, "score-worker.js"),
 
65
  styles: path.join(srcDir, "styles.css"),
 
66
  },
67
  outdir: distDir,
68
  entryNames: "[name]",
@@ -75,7 +91,7 @@ async function main() {
75
  legalComments: "none",
76
  loader: { ".woff2": "file" },
77
  logLevel: "info",
78
- plugins: [sharedFilesPlugin(sourceDir), copyStaticPlugin(sourceDir)],
79
  });
80
 
81
  if (watch) {
 
8
  const srcDir = path.join(webDir, "src");
9
  const distDir = path.join(webDir, "dist");
10
  const vendorDir = path.join(webDir, "vendor");
11
+ const repoRoot = [path.resolve(webDir, "../.."), path.resolve(webDir, "../../..")]
12
+ .find((dir) => existsSync(path.join(dir, "compile.py"))) ?? path.resolve(webDir, "../../..");
13
  const SHARED_FILES = ["engine.js", "presets.json", "weights.npz"];
14
  const watch = process.argv.includes("--watch");
15
 
16
+ function sharedPaths() {
17
+ if (SHARED_FILES.every((name) => existsSync(path.join(vendorDir, name)))) {
18
+ return {
19
+ engine: path.join(vendorDir, "engine.js"),
20
+ presets: path.join(vendorDir, "presets.json"),
21
+ weights: path.join(vendorDir, "weights.npz"),
22
+ };
23
+ }
24
+ return {
25
+ engine: path.join(repoRoot, "codehygiene", "engine.js"),
26
+ presets: path.resolve(webDir, "../presets.json"),
27
+ weights: path.join(repoRoot, "codehygiene", "weights.npz"),
28
+ };
29
  }
30
 
31
+ function sharedFilesPlugin(shared) {
32
  const targets = {
33
+ "shared:engine": shared.engine,
34
+ "shared:presets": shared.presets,
35
  };
36
  return {
37
  name: "shared-files",
 
44
  };
45
  }
46
 
47
+ const PAGES = { "board.html": "leaderboard", "privacy.html": "privacy" };
48
+
49
+ async function copyStatic(shared) {
50
  await copyFile(path.join(srcDir, "index.html"), path.join(distDir, "index.html"));
51
+ for (const [page, folder] of Object.entries(PAGES)) {
52
+ await mkdir(path.join(distDir, folder), { recursive: true });
53
+ await copyFile(path.join(srcDir, page), path.join(distDir, folder, "index.html"));
54
+ }
55
+ await copyFile(shared.weights, path.join(distDir, "weights.npz"));
56
  }
57
 
58
+ const copyStaticPlugin = (shared) => ({
59
  name: "copy-static",
60
  setup(build) {
61
  build.onEnd(async (result) => {
62
  if (result.errors.length === 0) {
63
+ await copyStatic(shared);
64
  }
65
  });
66
  },
67
  });
68
 
69
  async function main() {
70
+ const shared = sharedPaths();
71
  await rm(distDir, { recursive: true, force: true });
72
  await mkdir(distDir, { recursive: true });
73
 
 
76
  app: path.join(srcDir, "main.js"),
77
  board: path.join(srcDir, "board.js"),
78
  "score-worker": path.join(srcDir, "score-worker.js"),
79
+ "bonsai-worker": path.join(srcDir, "bonsai-worker.js"),
80
  styles: path.join(srcDir, "styles.css"),
81
+ privacy: path.join(srcDir, "privacy.css"),
82
  },
83
  outdir: distDir,
84
  entryNames: "[name]",
 
91
  legalComments: "none",
92
  loader: { ".woff2": "file" },
93
  logLevel: "info",
94
+ plugins: [sharedFilesPlugin(shared), copyStaticPlugin(shared)],
95
  });
96
 
97
  if (watch) {
web/src/bonsai-guards.js ADDED
@@ -0,0 +1,459 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Browser-side prompt builder, SEARCH/REPLACE patcher, and hygiene guards matching server/guards.py.
2
+ import { formatJsonResult, scoreCode } from "shared:engine";
3
+
4
+ export const TASK_INSTRUCTIONS = [
5
+ "Refactor the file to resolve every squiggle in the codehygiene response while preserving exact runtime behavior and non-squiggled public/exported function, class, and method names.",
6
+ "Keep edits minimal and idiomatic; do not add redundant comments, wrapper ceremony, or line bloat.",
7
+ "Wrap dense lines under 88 columns and rename cryptic 1-2 character identifiers, ceremonial *Helper/*Manager/*Factory names, or magic-index expressions flagged by poor_naming into clear domain names across their scope.",
8
+ "Return ONLY one or more SEARCH/REPLACE blocks in this exact format (no prose outside blocks):",
9
+ "",
10
+ "<<<<<<< SEARCH",
11
+ "exact existing lines from the file",
12
+ "=======",
13
+ "replacement lines",
14
+ ">>>>>>> REPLACE",
15
+ ].join("\n");
16
+
17
+ const PATCH_BLOCK_RE = /<<<<<<< SEARCH\r?\n([\s\S]*?)\r?\n=======\r?\n([\s\S]*?)>>>>>>> REPLACE/g;
18
+ const OPEN_MARKER = "<<<<<<< SEARCH";
19
+ const PARTIAL_MARKERS = ["=======", ">>>>>>> REPLACE"];
20
+ const CLOSE_BLOCK = "\n>>>>>>> REPLACE";
21
+
22
+ const JS_METHOD_SKIP = new Set([
23
+ "if", "for", "while", "switch", "catch", "with", "return", "function", "constructor", "super",
24
+ ]);
25
+ const LOCAL_DECL_RE = new RegExp(
26
+ [
27
+ "^\\s*(?:export\\s+)?(?:async\\s+)?(?:function|class|fn|struct)\\s+([A-Za-z_$][A-Za-z0-9_$]*)\\b",
28
+ "^\\s*func\\s+(?:\\([^)\\n]+\\)\\s*)?([A-Za-z_$][A-Za-z0-9_$]*)\\b",
29
+ "^\\s{2,8}(?:private\\s+|public\\s+|protected\\s+|readonly\\s+|static\\s+|async\\s+|pub\\s+)*(?:fn\\s+)?([A-Za-z_$][A-Za-z0-9_$]*)(?:<[^>(]+>)?\\s*\\(",
30
+ ].join("|"),
31
+ "gm",
32
+ );
33
+ const RECEIVER_CALL_RE = /\b(?:this|self)\.([A-Za-z_$][A-Za-z0-9_$]*)\s*\(/g;
34
+ const PY_DEF_RE = /^\s*(?:async\s+)?def\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(/gm;
35
+
36
+ export function scoreHygieneDict(content, weights, threshold = 0.55) {
37
+ return formatJsonResult(scoreCode(content, weights, threshold));
38
+ }
39
+
40
+ export function enrichHygieneWithSourceLines(content, hygiene) {
41
+ const srcLines = content.replace(/\r\n/g, "\n").split("\n");
42
+ const enrichedSq = (hygiene.squiggles ?? []).map((sq) => {
43
+ const lineNo = Number(sq.line ?? 1);
44
+ const srcLine = lineNo >= 1 && lineNo <= srcLines.length ? srcLines[lineNo - 1] : "";
45
+ return {
46
+ line: lineNo,
47
+ source_line: srcLine,
48
+ col_start: sq.col_start ?? 0,
49
+ col_end: sq.col_end ?? srcLine.length,
50
+ probability: sq.probability ?? 1.0,
51
+ kind: sq.kind ?? "",
52
+ message: sq.message ?? "",
53
+ };
54
+ });
55
+ return {
56
+ score: hygiene.score ?? 0.0,
57
+ rl_hygiene: hygiene.rl_hygiene ?? 0.0,
58
+ scores: hygiene.scores ?? {},
59
+ archetype: hygiene.archetype ?? "",
60
+ squiggles: enrichedSq,
61
+ };
62
+ }
63
+
64
+ export function buildPrompt(content, hygiene, filename = "") {
65
+ const filePrefix = filename ? `File: ${filename}\n\n` : "";
66
+ const enriched = enrichHygieneWithSourceLines(content, hygiene);
67
+ const userBody = [
68
+ `${filePrefix}<file_content>`,
69
+ content,
70
+ "</file_content>",
71
+ "",
72
+ "<codehygiene_response>",
73
+ JSON.stringify(enriched, null, 2),
74
+ "</codehygiene_response>",
75
+ ].join("\n");
76
+ return (
77
+ `<|im_start|>system\n${TASK_INSTRUCTIONS}<|im_end|>\n` +
78
+ `<|im_start|>user\n${userBody}<|im_end|>\n` +
79
+ "<|im_start|>assistant\n<think>\n\n</think>\n\n"
80
+ );
81
+ }
82
+
83
+ function stripSingleTrailingNewline(text) {
84
+ if (text.endsWith("\r\n")) return text.slice(0, -2);
85
+ if (text.endsWith("\n")) return text.slice(0, -1);
86
+ return text;
87
+ }
88
+
89
+ export function parseChanges(responseText) {
90
+ const blocks = [];
91
+ PATCH_BLOCK_RE.lastIndex = 0;
92
+ let match = PATCH_BLOCK_RE.exec(responseText);
93
+ while (match !== null) {
94
+ const searchPart = match[1].replace(/\r\n/g, "\n");
95
+ const replacePart = stripSingleTrailingNewline(match[2]).replace(/\r\n/g, "\n");
96
+ blocks.push([searchPart, replacePart]);
97
+ match = PATCH_BLOCK_RE.exec(responseText);
98
+ }
99
+ return blocks;
100
+ }
101
+
102
+ function leadingSpaces(line) {
103
+ let count = 0;
104
+ while (count < line.length && line[count] === " ") count += 1;
105
+ return count;
106
+ }
107
+
108
+ function shiftIndent(text, delta) {
109
+ if (!text || delta === 0) return text;
110
+ const prefix = delta > 0 ? " ".repeat(delta) : "";
111
+ return text.split("\n").map((raw) => {
112
+ if (!raw.trim()) return "";
113
+ if (delta > 0) return prefix + raw;
114
+ return raw.slice(Math.min(-delta, leadingSpaces(raw)));
115
+ }).join("\n");
116
+ }
117
+
118
+ function replaceRstripLines(source, search, replace) {
119
+ const srcLines = source.split("\n");
120
+ const needle = search.split("\n").map((ln) => ln.trimEnd());
121
+ const span = needle.length;
122
+ if (span === 0 || span > srcLines.length) return null;
123
+
124
+ let foundPos = -1;
125
+ for (let idx = 0; idx <= srcLines.length - span; idx += 1) {
126
+ let ok = true;
127
+ for (let k = 0; k < span; k += 1) {
128
+ if (srcLines[idx + k].trimEnd() !== needle[k]) {
129
+ ok = false;
130
+ break;
131
+ }
132
+ }
133
+ if (ok) {
134
+ if (foundPos !== -1) return null;
135
+ foundPos = idx;
136
+ }
137
+ }
138
+ if (foundPos === -1) return null;
139
+ const replLines = replace ? replace.split("\n") : [];
140
+ return [...srcLines.slice(0, foundPos), ...replLines, ...srcLines.slice(foundPos + span)].join("\n");
141
+ }
142
+
143
+ function replaceStrippedUnique(source, search, replace) {
144
+ const srcLines = source.split("\n");
145
+ const searchLines = search.split("\n");
146
+ const needle = searchLines.map((ln) => ln.trim());
147
+ const span = needle.length;
148
+ if (span === 0 || span > srcLines.length || !needle.some(Boolean)) return null;
149
+ if (span === 1 && needle[0].length < 14) return null;
150
+
151
+ let foundPos = -1;
152
+ for (let idx = 0; idx <= srcLines.length - span; idx += 1) {
153
+ let ok = true;
154
+ for (let k = 0; k < span; k += 1) {
155
+ if (srcLines[idx + k].trim() !== needle[k]) {
156
+ ok = false;
157
+ break;
158
+ }
159
+ }
160
+ if (ok) {
161
+ if (foundPos !== -1) return null;
162
+ foundPos = idx;
163
+ }
164
+ }
165
+ if (foundPos === -1) return null;
166
+
167
+ let delta = 0;
168
+ for (let k = 0; k < span; k += 1) {
169
+ const sLine = srcLines[foundPos + k];
170
+ const qLine = searchLines[k];
171
+ if (sLine.trim() && qLine.trim() && !sLine.includes("\t") && !qLine.includes("\t")) {
172
+ delta = leadingSpaces(sLine) - leadingSpaces(qLine);
173
+ break;
174
+ }
175
+ }
176
+ const adjusted = shiftIndent(replace, delta);
177
+ const replLines = adjusted ? adjusted.split("\n") : [];
178
+ return [...srcLines.slice(0, foundPos), ...replLines, ...srcLines.slice(foundPos + span)].join("\n");
179
+ }
180
+
181
+ export function applyChanges(content, responseText) {
182
+ const blocks = parseChanges(responseText);
183
+ if (blocks.length === 0) return { content, applied: 0 };
184
+
185
+ const hasCrLf = content.includes("\r\n");
186
+ let working = content.replace(/\r\n/g, "\n");
187
+ let applied = 0;
188
+ let firstMiss = null;
189
+
190
+ for (const [search, replace] of blocks) {
191
+ if (!search || search === replace) continue;
192
+ if (replace === "" && working.includes(`${search}\n`)) {
193
+ working = working.replace(`${search}\n`, "");
194
+ applied += 1;
195
+ continue;
196
+ }
197
+ if (working.includes(search)) {
198
+ working = working.replace(search, () => replace);
199
+ applied += 1;
200
+ continue;
201
+ }
202
+ let fallback = replaceRstripLines(working, search, replace);
203
+ if (fallback === null) {
204
+ fallback = replaceStrippedUnique(working, search, replace);
205
+ }
206
+ if (fallback !== null) {
207
+ working = fallback;
208
+ applied += 1;
209
+ } else if (firstMiss === null) {
210
+ firstMiss = search.split("\n")[0].slice(0, 60);
211
+ }
212
+ }
213
+ if (applied === 0 && firstMiss !== null) {
214
+ throw new Error(`SEARCH block did not match file content: ${firstMiss}`);
215
+ }
216
+ return { content: hasCrLf ? working.replace(/\n/g, "\r\n") : working, applied };
217
+ }
218
+
219
+ export function previewContent(base, raw) {
220
+ const openAt = raw.lastIndexOf(OPEN_MARKER);
221
+ let patchedRaw = raw;
222
+ if (openAt !== -1 && !raw.slice(openAt).includes(">>>>>>> REPLACE")) {
223
+ let text = raw.endsWith("\n") ? raw.slice(0, -1) : raw;
224
+ const nl = text.lastIndexOf("\n");
225
+ if (nl >= 0) {
226
+ const tail = text.slice(nl + 1);
227
+ if (tail !== "=======" && PARTIAL_MARKERS.some((m) => m.startsWith(tail))) {
228
+ text = text.slice(0, nl);
229
+ }
230
+ }
231
+ patchedRaw = text + CLOSE_BLOCK;
232
+ }
233
+ try {
234
+ const { content, applied } = applyChanges(base, patchedRaw);
235
+ return applied > 0 ? { content, applied } : null;
236
+ } catch {
237
+ return null;
238
+ }
239
+ }
240
+
241
+ function inferLang(filename) {
242
+ const dot = filename.lastIndexOf(".");
243
+ const ext = dot >= 0 ? filename.slice(dot).toLowerCase() : "";
244
+ const map = {
245
+ ".py": "python",
246
+ ".ts": "typescript",
247
+ ".mts": "typescript",
248
+ ".js": "javascript",
249
+ ".mjs": "javascript",
250
+ ".rs": "rust",
251
+ ".go": "go",
252
+ };
253
+ return map[ext] ?? "other";
254
+ }
255
+
256
+ function hasBalancedDelimiters(code, commentPrefix) {
257
+ const stack = [];
258
+ const pairs = { "(": ")", "[": "]", "{": "}" };
259
+ const closers = new Set([")", "]", "}"]);
260
+ let quote = null;
261
+ for (let i = 0; i < code.length; i += 1) {
262
+ const ch = code[i];
263
+ if (quote) {
264
+ if (ch === "\\") {
265
+ i += 1;
266
+ } else if (ch === quote) {
267
+ quote = null;
268
+ }
269
+ continue;
270
+ }
271
+ if (commentPrefix && code.startsWith(commentPrefix, i)) {
272
+ const nl = code.indexOf("\n", i);
273
+ if (nl === -1) break;
274
+ i = nl;
275
+ continue;
276
+ }
277
+ if (ch === '"' || ch === "'" || ch === "`") {
278
+ quote = ch;
279
+ } else if (pairs[ch]) {
280
+ stack.push(pairs[ch]);
281
+ } else if (closers.has(ch) && stack.pop() !== ch) {
282
+ return false;
283
+ }
284
+ }
285
+ return quote === null && stack.length === 0;
286
+ }
287
+
288
+ function checkPythonStructure(code) {
289
+ if (!hasBalancedDelimiters(code, "#")) return false;
290
+ const openTries = [];
291
+ for (const raw of code.split("\n")) {
292
+ const trimmed = raw.trim();
293
+ if (!trimmed || trimmed.startsWith("#")) continue;
294
+ const indent = leadingSpaces(raw);
295
+ while (openTries.length > 0 && indent <= openTries[openTries.length - 1]) {
296
+ const tryIndent = openTries[openTries.length - 1];
297
+ if (indent === tryIndent && /^(?:except\b|finally\s*:)/.test(trimmed)) {
298
+ openTries.pop();
299
+ break;
300
+ }
301
+ if (indent <= tryIndent) {
302
+ return false;
303
+ }
304
+ }
305
+ if (/^try\s*:/.test(trimmed)) {
306
+ openTries.push(indent);
307
+ }
308
+ }
309
+ return openTries.length === 0;
310
+ }
311
+
312
+ const JS_IMPORT_RE = new RegExp(
313
+ "^\\s*import\\s+[\\s\\S]*?from\\s+[\"'][^\"']+[\"'];?",
314
+ "gm",
315
+ );
316
+ const JS_EXPORT_DEFAULT_RE = /^\s*export\s+default\s+/gm;
317
+ const JS_EXPORT_DECL_RE = new RegExp(
318
+ "^\\s*export\\s+(?=(?:async\\s+)?(?:function|class|const|let|var)\\b)",
319
+ "gm",
320
+ );
321
+
322
+ function checkBasicSyntax(code, filename) {
323
+ if (!code.trim()) return false;
324
+ const lang = inferLang(filename);
325
+ if (lang === "python") return checkPythonStructure(code);
326
+ if (lang === "javascript") {
327
+ try {
328
+ let moduleBody = code.replace(JS_IMPORT_RE, "");
329
+ moduleBody = moduleBody.replace(JS_EXPORT_DEFAULT_RE, "const __default = ");
330
+ moduleBody = moduleBody.replace(JS_EXPORT_DECL_RE, "");
331
+ // Syntax-parse only; Function constructor is never invoked.
332
+ new Function(moduleBody);
333
+ return true;
334
+ } catch {
335
+ return false;
336
+ }
337
+ }
338
+ if (lang === "typescript" || lang === "rust" || lang === "go") {
339
+ return hasBalancedDelimiters(code, "//");
340
+ }
341
+ return true;
342
+ }
343
+
344
+ function collectRegexMatches(re, text) {
345
+ const found = new Set();
346
+ re.lastIndex = 0;
347
+ let m = re.exec(text);
348
+ while (m !== null) {
349
+ const sym = m[1] || m[2] || m[3] || "";
350
+ if (sym && !JS_METHOD_SKIP.has(sym)) found.add(sym);
351
+ m = re.exec(text);
352
+ }
353
+ return found;
354
+ }
355
+
356
+ function checkReferenceIntegrity(beforeCode, afterCode, filename) {
357
+ const lang = inferLang(filename);
358
+ if (lang === "python") {
359
+ const defsBefore = collectRegexMatches(PY_DEF_RE, beforeCode);
360
+ const defsAfter = collectRegexMatches(PY_DEF_RE, afterCode);
361
+ const selfBefore = collectRegexMatches(RECEIVER_CALL_RE, beforeCode);
362
+ const selfAfter = collectRegexMatches(RECEIVER_CALL_RE, afterCode);
363
+ for (const sym of selfAfter) {
364
+ if (defsBefore.has(sym) && !defsAfter.has(sym)) return false;
365
+ if (!selfBefore.has(sym) && !defsAfter.has(sym)) return false;
366
+ }
367
+ return true;
368
+ }
369
+ if (lang === "javascript" || lang === "typescript" || lang === "rust" || lang === "go") {
370
+ const defsBefore = collectRegexMatches(LOCAL_DECL_RE, beforeCode);
371
+ const defsAfter = collectRegexMatches(LOCAL_DECL_RE, afterCode);
372
+ for (const dropped of defsBefore) {
373
+ if (!defsAfter.has(dropped)) {
374
+ const callRe = new RegExp(`(?:^|[^.\\w$])${dropped.replace(/\$/g, "\\$")}\\s*\\(`, "m");
375
+ if (callRe.test(afterCode)) return false;
376
+ }
377
+ }
378
+ const recvBefore = collectRegexMatches(RECEIVER_CALL_RE, beforeCode);
379
+ const recvAfter = collectRegexMatches(RECEIVER_CALL_RE, afterCode);
380
+ for (const sym of recvAfter) {
381
+ if (!recvBefore.has(sym) && !defsAfter.has(sym)) return false;
382
+ }
383
+ }
384
+ return true;
385
+ }
386
+
387
+ function countNonCommentLines(code) {
388
+ let total = 0;
389
+ for (const raw of code.split("\n")) {
390
+ const s = raw.trim();
391
+ if (s && !s.startsWith("#") && !s.startsWith("//") && !s.startsWith("/*") && !s.startsWith("*")) {
392
+ total += 1;
393
+ }
394
+ }
395
+ return total;
396
+ }
397
+
398
+ function isGutted(beforeCode, updated) {
399
+ const origN = countNonCommentLines(beforeCode);
400
+ const newN = countNonCommentLines(updated);
401
+ if (origN >= 1 && newN === 0) return true;
402
+ return origN >= 10 && newN < Math.max(5, Math.trunc(origN * 0.55));
403
+ }
404
+
405
+ function isBloated(beforeCode, updated) {
406
+ const beforeN = beforeCode.split("\n").filter((ln) => ln.trim()).length;
407
+ const afterN = updated.split("\n").filter((ln) => ln.trim()).length;
408
+ return afterN > Math.max(40, Math.trunc(beforeN * 1.6));
409
+ }
410
+
411
+ export function verifyPatch(content, reply, filename, threshold, beforeHygiene, weights) {
412
+ const squigglesBefore = beforeHygiene.squiggles.length;
413
+ const reject = (reason, applied = 0) => ({
414
+ accepted: false,
415
+ reason,
416
+ content,
417
+ appliedBlocks: applied,
418
+ squigglesBefore,
419
+ squigglesAfter: null,
420
+ hygiene: {},
421
+ scoreAfter: null,
422
+ reply: "",
423
+ });
424
+
425
+ if (!reply.trim()) return reject("empty_output");
426
+ let patched;
427
+ try {
428
+ patched = applyChanges(content, reply);
429
+ } catch {
430
+ return reject("search_miss");
431
+ }
432
+ if (patched.applied === 0 || patched.content === content) {
433
+ return reject("no_blocks_applied", patched.applied);
434
+ }
435
+ if (filename) {
436
+ const syntaxOk = checkBasicSyntax(patched.content, filename);
437
+ const refsOk = syntaxOk && checkReferenceIntegrity(content, patched.content, filename);
438
+ if (!refsOk) {
439
+ return reject("invalid_syntax", patched.applied);
440
+ }
441
+ }
442
+ if (isGutted(content, patched.content)) return reject("gutted_file", patched.applied);
443
+ if (isBloated(content, patched.content)) return reject("line_bloat", patched.applied);
444
+
445
+ const after = scoreHygieneDict(patched.content, weights, threshold);
446
+ const squigglesAfter = after.squiggles.length;
447
+ const accepted = squigglesAfter < squigglesBefore;
448
+ return {
449
+ accepted,
450
+ reason: accepted ? null : "no_improvement",
451
+ content: accepted ? patched.content : content,
452
+ appliedBlocks: patched.applied,
453
+ squigglesBefore,
454
+ squigglesAfter,
455
+ hygiene: after,
456
+ scoreAfter: after.score ?? null,
457
+ reply,
458
+ };
459
+ }
web/src/bonsai-shaders.js ADDED
@@ -0,0 +1,595 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Baseline WebGPU 1.0 WGSL compute kernels for 2-bit packed ternary Qwen3-1.7B (group_size = 32).
2
+
3
+ const DECODE_HELPER_WGSL = `
4
+ fn decode_trit4(word: u32, shift: u32) -> vec4<f32> {
5
+ let c0 = (word >> shift) & 3u;
6
+ let c1 = (word >> (shift + 2u)) & 3u;
7
+ let c2 = (word >> (shift + 4u)) & 3u;
8
+ let c3 = (word >> (shift + 6u)) & 3u;
9
+ return vec4<f32>(
10
+ f32(i32(c0 & 1u) - i32(c0 >> 1u)),
11
+ f32(i32(c1 & 1u) - i32(c1 >> 1u)),
12
+ f32(i32(c2 & 1u) - i32(c2 >> 1u)),
13
+ f32(i32(c3 & 1u) - i32(c3 >> 1u)),
14
+ );
15
+ }
16
+
17
+ fn read_scale(scales: ptr<storage, array<u32>, read>, base_u32: u32, group_idx: u32) -> f32 {
18
+ let pair = unpack2x16float((*scales)[base_u32 + (group_idx >> 1u)]);
19
+ return select(pair.x, pair.y, (group_idx & 1u) == 1u);
20
+ }
21
+ `;
22
+
23
+ export const EMBED_WGSL = `
24
+ struct StepParams {
25
+ batch_len: u32,
26
+ start_pos: u32,
27
+ max_seq: u32,
28
+ pad0: u32,
29
+ };
30
+
31
+ @group(0) @binding(0) var<uniform> step: StepParams;
32
+ @group(0) @binding(1) var<storage, read> token_ids: array<u32>;
33
+ @group(0) @binding(2) var<storage, read> embed_trits: array<u32>;
34
+ @group(0) @binding(3) var<storage, read> embed_scales: array<u32>;
35
+ @group(0) @binding(4) var<storage, read_write> out_x: array<f32>;
36
+
37
+ ${DECODE_HELPER_WGSL}
38
+
39
+ @compute @workgroup_size(64, 1, 1)
40
+ fn main(
41
+ @builtin(workgroup_id) wg: vec3<u32>,
42
+ @builtin(local_invocation_id) lid: vec3<u32>,
43
+ ) {
44
+ let b = wg.x;
45
+ if (b >= step.batch_len) {
46
+ return;
47
+ }
48
+ let col4 = wg.y * 64u + lid.x;
49
+ let row = token_ids[b];
50
+ let group_idx = col4 >> 3u;
51
+ let word_idx = (col4 >> 2u) & 1u;
52
+ let shift = (col4 & 3u) * 8u;
53
+ let word = embed_trits[row * 128u + group_idx * 2u + word_idx];
54
+ let scale = read_scale(&embed_scales, row * 32u, group_idx);
55
+ let vals = decode_trit4(word, shift) * scale;
56
+ let dst = b * 2048u + col4 * 4u;
57
+ out_x[dst] = vals.x;
58
+ out_x[dst + 1u] = vals.y;
59
+ out_x[dst + 2u] = vals.z;
60
+ out_x[dst + 3u] = vals.w;
61
+ }
62
+ `;
63
+
64
+ export const RMSNORM_WGSL = `
65
+ struct StepParams {
66
+ batch_len: u32,
67
+ start_pos: u32,
68
+ max_seq: u32,
69
+ pad0: u32,
70
+ };
71
+
72
+ struct NormOp {
73
+ norm_offset: u32,
74
+ dim: u32,
75
+ pad0: u32,
76
+ pad1: u32,
77
+ };
78
+
79
+ @group(0) @binding(0) var<uniform> step: StepParams;
80
+ @group(0) @binding(1) var<uniform> op: NormOp;
81
+ @group(0) @binding(2) var<storage, read> in_x: array<f32>;
82
+ @group(0) @binding(3) var<storage, read> norms: array<f32>;
83
+ @group(0) @binding(4) var<storage, read_write> out_y: array<f32>;
84
+
85
+ var<workgroup> shared_sq: array<f32, 256>;
86
+
87
+ @compute @workgroup_size(256, 1, 1)
88
+ fn main(
89
+ @builtin(workgroup_id) wg: vec3<u32>,
90
+ @builtin(local_invocation_id) lid: vec3<u32>,
91
+ ) {
92
+ let b = wg.x;
93
+ let tid = lid.x;
94
+ var sq_sum = 0.0;
95
+ if (b < step.batch_len) {
96
+ let base = b * op.dim;
97
+ for (var idx = tid; idx < op.dim; idx += 256u) {
98
+ let v = in_x[base + idx];
99
+ sq_sum += v * v;
100
+ }
101
+ }
102
+ shared_sq[tid] = sq_sum;
103
+ workgroupBarrier();
104
+
105
+ for (var stride = 128u; stride > 0u; stride >>= 1u) {
106
+ if (tid < stride) {
107
+ shared_sq[tid] += shared_sq[tid + stride];
108
+ }
109
+ workgroupBarrier();
110
+ }
111
+
112
+ if (b < step.batch_len) {
113
+ let inv_rms = inverseSqrt(shared_sq[0] / f32(op.dim) + 1e-6);
114
+ let base = b * op.dim;
115
+ for (var idx = tid; idx < op.dim; idx += 256u) {
116
+ out_y[base + idx] = in_x[base + idx] * inv_rms * norms[op.norm_offset + idx];
117
+ }
118
+ }
119
+ }
120
+ `;
121
+
122
+ export const TERNARY_GEMV_WGSL = `
123
+ struct MatOp {
124
+ rows: u32,
125
+ in_groups: u32,
126
+ trit_offset: u32,
127
+ scale_offset: u32,
128
+ add_residual: u32,
129
+ pad0: u32,
130
+ pad1: u32,
131
+ pad2: u32,
132
+ };
133
+
134
+ @group(0) @binding(0) var<uniform> op: MatOp;
135
+ @group(0) @binding(1) var<storage, read> in_x: array<vec4<f32>>;
136
+ @group(0) @binding(2) var<storage, read> trits: array<u32>;
137
+ @group(0) @binding(3) var<storage, read> scales: array<u32>;
138
+ @group(0) @binding(4) var<storage, read_write> out_y: array<f32>;
139
+
140
+ ${DECODE_HELPER_WGSL}
141
+
142
+ var<workgroup> shared_x: array<vec4<f32>, 512>;
143
+ var<workgroup> partial_sum: array<f32, 256>;
144
+
145
+ @compute @workgroup_size(64, 4, 1)
146
+ fn main(
147
+ @builtin(workgroup_id) wg: vec3<u32>,
148
+ @builtin(local_invocation_id) lid: vec3<u32>,
149
+ ) {
150
+ let gx = lid.x;
151
+ let ry = lid.y;
152
+ let flat_tid = ry * 64u + gx;
153
+ let row = wg.x * 4u + ry;
154
+ let num_tiles = op.in_groups / 64u;
155
+
156
+ var acc = 0.0;
157
+ for (var tile = 0u; tile < num_tiles; tile += 1u) {
158
+ let x_vec_base = tile * 512u;
159
+ shared_x[flat_tid] = in_x[x_vec_base + flat_tid];
160
+ shared_x[flat_tid + 256u] = in_x[x_vec_base + flat_tid + 256u];
161
+ workgroupBarrier();
162
+
163
+ if (row < op.rows) {
164
+ let g = tile * 64u + gx;
165
+ let row_trit_base = op.trit_offset + row * op.in_groups * 2u;
166
+ let row_scale_base = op.scale_offset + row * (op.in_groups >> 1u);
167
+ let w0 = trits[row_trit_base + g * 2u];
168
+ let w1 = trits[row_trit_base + g * 2u + 1u];
169
+ let scale = read_scale(&scales, row_scale_base, g);
170
+ let x_off = gx * 8u;
171
+ let s0 = dot(decode_trit4(w0, 0u), shared_x[x_off])
172
+ + dot(decode_trit4(w0, 8u), shared_x[x_off + 1u])
173
+ + dot(decode_trit4(w0, 16u), shared_x[x_off + 2u])
174
+ + dot(decode_trit4(w0, 24u), shared_x[x_off + 3u]);
175
+ let s1 = dot(decode_trit4(w1, 0u), shared_x[x_off + 4u])
176
+ + dot(decode_trit4(w1, 8u), shared_x[x_off + 5u])
177
+ + dot(decode_trit4(w1, 16u), shared_x[x_off + 6u])
178
+ + dot(decode_trit4(w1, 24u), shared_x[x_off + 7u]);
179
+ acc += (s0 + s1) * scale;
180
+ }
181
+ workgroupBarrier();
182
+ }
183
+
184
+ partial_sum[flat_tid] = acc;
185
+ workgroupBarrier();
186
+
187
+ for (var stride = 32u; stride > 0u; stride >>= 1u) {
188
+ if (gx < stride) {
189
+ partial_sum[flat_tid] += partial_sum[flat_tid + stride];
190
+ }
191
+ workgroupBarrier();
192
+ }
193
+
194
+ if (gx == 0u && row < op.rows) {
195
+ let total = partial_sum[ry * 64u];
196
+ if (op.add_residual == 1u) {
197
+ out_y[row] += total;
198
+ } else {
199
+ out_y[row] = total;
200
+ }
201
+ }
202
+ }
203
+ `;
204
+
205
+ export const TERNARY_GEMM_WGSL = `
206
+ struct StepParams {
207
+ batch_len: u32,
208
+ start_pos: u32,
209
+ max_seq: u32,
210
+ pad0: u32,
211
+ };
212
+
213
+ struct MatOp {
214
+ rows: u32,
215
+ in_groups: u32,
216
+ trit_offset: u32,
217
+ scale_offset: u32,
218
+ add_residual: u32,
219
+ pad0: u32,
220
+ pad1: u32,
221
+ pad2: u32,
222
+ };
223
+
224
+ @group(0) @binding(0) var<uniform> step: StepParams;
225
+ @group(0) @binding(1) var<uniform> op: MatOp;
226
+ @group(0) @binding(2) var<storage, read> in_x: array<vec4<f32>>;
227
+ @group(0) @binding(3) var<storage, read> trits: array<u32>;
228
+ @group(0) @binding(4) var<storage, read> scales: array<u32>;
229
+ @group(0) @binding(5) var<storage, read_write> out_y: array<f32>;
230
+
231
+ ${DECODE_HELPER_WGSL}
232
+
233
+ var<workgroup> tile_x: array<vec4<f32>, 128>;
234
+ var<workgroup> tile_w: array<vec4<f32>, 128>;
235
+
236
+ @compute @workgroup_size(16, 16, 1)
237
+ fn main(
238
+ @builtin(workgroup_id) wg: vec3<u32>,
239
+ @builtin(local_invocation_id) lid: vec3<u32>,
240
+ ) {
241
+ let rx = lid.x;
242
+ let by = lid.y;
243
+ let row = wg.x * 16u + rx;
244
+ let b = wg.y * 16u + by;
245
+ let x_row_vecs = op.in_groups * 8u;
246
+
247
+ var acc = 0.0;
248
+ for (var g = 0u; g < op.in_groups; g += 1u) {
249
+ if (rx < 8u) {
250
+ if (b < step.batch_len) {
251
+ tile_x[by * 8u + rx] = in_x[b * x_row_vecs + g * 8u + rx];
252
+ } else {
253
+ tile_x[by * 8u + rx] = vec4<f32>(0.0);
254
+ }
255
+ }
256
+ if (by < 8u) {
257
+ if (row < op.rows) {
258
+ let row_trit_base = op.trit_offset + row * op.in_groups * 2u;
259
+ let row_scale_base = op.scale_offset + row * (op.in_groups >> 1u);
260
+ let word = trits[row_trit_base + g * 2u + (by >> 2u)];
261
+ let shift = (by & 3u) * 8u;
262
+ let scale = read_scale(&scales, row_scale_base, g);
263
+ tile_w[rx * 8u + by] = decode_trit4(word, shift) * scale;
264
+ } else {
265
+ tile_w[rx * 8u + by] = vec4<f32>(0.0);
266
+ }
267
+ }
268
+ workgroupBarrier();
269
+
270
+ let w_off = rx * 8u;
271
+ let x_off = by * 8u;
272
+ acc += dot(tile_w[w_off], tile_x[x_off])
273
+ + dot(tile_w[w_off + 1u], tile_x[x_off + 1u])
274
+ + dot(tile_w[w_off + 2u], tile_x[x_off + 2u])
275
+ + dot(tile_w[w_off + 3u], tile_x[x_off + 3u])
276
+ + dot(tile_w[w_off + 4u], tile_x[x_off + 4u])
277
+ + dot(tile_w[w_off + 5u], tile_x[x_off + 5u])
278
+ + dot(tile_w[w_off + 6u], tile_x[x_off + 6u])
279
+ + dot(tile_w[w_off + 7u], tile_x[x_off + 7u]);
280
+ workgroupBarrier();
281
+ }
282
+
283
+ if (b < step.batch_len && row < op.rows) {
284
+ let dst = b * op.rows + row;
285
+ if (op.add_residual == 1u) {
286
+ out_y[dst] += acc;
287
+ } else {
288
+ out_y[dst] = acc;
289
+ }
290
+ }
291
+ }
292
+ `;
293
+
294
+ export const QK_ROPE_KV_WGSL = `
295
+ struct StepParams {
296
+ batch_len: u32,
297
+ start_pos: u32,
298
+ max_seq: u32,
299
+ pad0: u32,
300
+ };
301
+
302
+ struct AttnOp {
303
+ local_layer: u32,
304
+ q_norm_offset: u32,
305
+ k_norm_offset: u32,
306
+ cos_offset: u32,
307
+ sin_offset: u32,
308
+ pad0: u32,
309
+ pad1: u32,
310
+ pad2: u32,
311
+ };
312
+
313
+ @group(0) @binding(0) var<uniform> step: StepParams;
314
+ @group(0) @binding(1) var<uniform> op: AttnOp;
315
+ @group(0) @binding(2) var<storage, read> norms: array<f32>;
316
+ @group(0) @binding(3) var<storage, read_write> q_buf: array<f32>;
317
+ @group(0) @binding(4) var<storage, read> k_in: array<f32>;
318
+ @group(0) @binding(5) var<storage, read> v_in: array<f32>;
319
+ @group(0) @binding(6) var<storage, read_write> k_cache: array<u32>;
320
+ @group(0) @binding(7) var<storage, read_write> v_cache: array<u32>;
321
+
322
+ var<workgroup> head_sq: array<f32, 64>;
323
+
324
+ @compute @workgroup_size(64, 1, 1)
325
+ fn main(
326
+ @builtin(workgroup_id) wg: vec3<u32>,
327
+ @builtin(local_invocation_id) lid: vec3<u32>,
328
+ ) {
329
+ let b = wg.x;
330
+ let head_id = wg.y;
331
+ let tid = lid.x;
332
+ if (b >= step.batch_len) {
333
+ return;
334
+ }
335
+
336
+ let is_q = head_id < 16u;
337
+ var x0 = 0.0;
338
+ var x1 = 0.0;
339
+ if (is_q) {
340
+ let base = b * 2048u + head_id * 128u;
341
+ x0 = q_buf[base + tid];
342
+ x1 = q_buf[base + tid + 64u];
343
+ } else {
344
+ let kv_h = head_id - 16u;
345
+ let base = b * 1024u + kv_h * 128u;
346
+ x0 = k_in[base + tid];
347
+ x1 = k_in[base + tid + 64u];
348
+ }
349
+
350
+ head_sq[tid] = x0 * x0 + x1 * x1;
351
+ workgroupBarrier();
352
+ for (var stride = 32u; stride > 0u; stride >>= 1u) {
353
+ if (tid < stride) {
354
+ head_sq[tid] += head_sq[tid + stride];
355
+ }
356
+ workgroupBarrier();
357
+ }
358
+
359
+ let inv_rms = inverseSqrt(head_sq[0] / 128.0 + 1e-6);
360
+ let norm_off = select(op.k_norm_offset, op.q_norm_offset, is_q);
361
+ let n0 = x0 * inv_rms * norms[norm_off + tid];
362
+ let n1 = x1 * inv_rms * norms[norm_off + tid + 64u];
363
+
364
+ let pos = step.start_pos + b;
365
+ let c = norms[op.cos_offset + pos * 64u + tid];
366
+ let s = norms[op.sin_offset + pos * 64u + tid];
367
+ let r0 = n0 * c - n1 * s;
368
+ let r1 = n1 * c + n0 * s;
369
+
370
+ if (is_q) {
371
+ let base = b * 2048u + head_id * 128u;
372
+ q_buf[base + tid] = r0;
373
+ q_buf[base + tid + 64u] = r1;
374
+ } else {
375
+ let kv_h = head_id - 16u;
376
+ let cache_slot = ((op.local_layer * 8u + kv_h) * step.max_seq + pos) * 64u;
377
+ if (tid < 32u) {
378
+ head_sq[tid] = r0;
379
+ head_sq[tid + 32u] = r1;
380
+ }
381
+ workgroupBarrier();
382
+ if (tid >= 32u) {
383
+ // Wait cleanly while first half writes; pack using contiguous pairs below.
384
+ }
385
+ // Pack contiguous (2*tid, 2*tid+1) for both K and V so GQA reads vec2 linearly.
386
+ workgroupBarrier();
387
+ head_sq[tid] = r0;
388
+ workgroupBarrier();
389
+ if (tid < 32u) {
390
+ let k_even = head_sq[tid * 2u];
391
+ let k_odd = head_sq[tid * 2u + 1u];
392
+ k_cache[cache_slot + tid] = pack2x16float(vec2<f32>(k_even, k_odd));
393
+ }
394
+ workgroupBarrier();
395
+ head_sq[tid] = r1;
396
+ workgroupBarrier();
397
+ if (tid < 32u) {
398
+ let k_even2 = head_sq[tid * 2u];
399
+ let k_odd2 = head_sq[tid * 2u + 1u];
400
+ k_cache[cache_slot + 32u + tid] = pack2x16float(vec2<f32>(k_even2, k_odd2));
401
+ }
402
+
403
+ let v_base = b * 1024u + kv_h * 128u + tid * 2u;
404
+ v_cache[cache_slot + tid] = pack2x16float(vec2<f32>(v_in[v_base], v_in[v_base + 1u]));
405
+ }
406
+ }
407
+ `;
408
+
409
+ export const GQA_ATTN_WGSL = `
410
+ struct StepParams {
411
+ batch_len: u32,
412
+ start_pos: u32,
413
+ max_seq: u32,
414
+ pad0: u32,
415
+ };
416
+
417
+ struct AttnOp {
418
+ local_layer: u32,
419
+ q_norm_offset: u32,
420
+ k_norm_offset: u32,
421
+ cos_offset: u32,
422
+ sin_offset: u32,
423
+ pad0: u32,
424
+ pad1: u32,
425
+ pad2: u32,
426
+ };
427
+
428
+ @group(0) @binding(0) var<uniform> step: StepParams;
429
+ @group(0) @binding(1) var<uniform> op: AttnOp;
430
+ @group(0) @binding(2) var<storage, read> q_buf: array<f32>;
431
+ @group(0) @binding(3) var<storage, read> k_cache: array<u32>;
432
+ @group(0) @binding(4) var<storage, read> v_cache: array<u32>;
433
+ @group(0) @binding(5) var<storage, read_write> attn_out: array<f32>;
434
+
435
+ var<workgroup> q_sh: array<vec2<f32>, 64>;
436
+ var<workgroup> tile_scores: array<f32, 64>;
437
+
438
+ @compute @workgroup_size(64, 1, 1)
439
+ fn main(
440
+ @builtin(workgroup_id) wg: vec3<u32>,
441
+ @builtin(local_invocation_id) lid: vec3<u32>,
442
+ ) {
443
+ let b = wg.x;
444
+ let q_head = wg.y;
445
+ let tid = lid.x;
446
+ if (b >= step.batch_len) {
447
+ return;
448
+ }
449
+
450
+ let kv_head = q_head >> 1u;
451
+ let q_base = b * 2048u + q_head * 128u + tid * 2u;
452
+ q_sh[tid] = vec2<f32>(q_buf[q_base], q_buf[q_base + 1u]);
453
+ workgroupBarrier();
454
+
455
+ let max_t = step.start_pos + b;
456
+ let kv_head_base = (op.local_layer * 8u + kv_head) * step.max_seq;
457
+ let inv_sqrt_d = 0.08838834764831845;
458
+
459
+ var m = -1e30;
460
+ var l = 0.0;
461
+ var acc = vec2<f32>(0.0, 0.0);
462
+
463
+ for (var t_base = 0u; t_base <= max_t; t_base += 64u) {
464
+ let t = t_base + tid;
465
+ var score = -1e30;
466
+ if (t <= max_t) {
467
+ let k_slot = (kv_head_base + t) * 64u;
468
+ var dot_sum = 0.0;
469
+ for (var d = 0u; d < 64u; d += 1u) {
470
+ dot_sum += dot(q_sh[d], unpack2x16float(k_cache[k_slot + d]));
471
+ }
472
+ score = dot_sum * inv_sqrt_d;
473
+ }
474
+ tile_scores[tid] = score;
475
+ workgroupBarrier();
476
+
477
+ let count = min(64u, max_t - t_base + 1u);
478
+ for (var j = 0u; j < count; j += 1u) {
479
+ let s = tile_scores[j];
480
+ let m_next = max(m, s);
481
+ let alpha = exp(m - m_next);
482
+ let beta = exp(s - m_next);
483
+ let v_pair = unpack2x16float(v_cache[(kv_head_base + t_base + j) * 64u + tid]);
484
+ acc = acc * alpha + v_pair * beta;
485
+ l = l * alpha + beta;
486
+ m = m_next;
487
+ }
488
+ workgroupBarrier();
489
+ }
490
+
491
+ let out_pair = acc / max(l, 1e-20);
492
+ attn_out[q_base] = out_pair.x;
493
+ attn_out[q_base + 1u] = out_pair.y;
494
+ }
495
+ `;
496
+
497
+ export const SILU_MUL_WGSL = `
498
+ struct StepParams {
499
+ batch_len: u32,
500
+ start_pos: u32,
501
+ max_seq: u32,
502
+ pad0: u32,
503
+ };
504
+
505
+ @group(0) @binding(0) var<uniform> step: StepParams;
506
+ @group(0) @binding(1) var<storage, read> gate_buf: array<f32>;
507
+ @group(0) @binding(2) var<storage, read> up_buf: array<f32>;
508
+ @group(0) @binding(3) var<storage, read_write> out_buf: array<f32>;
509
+
510
+ @compute @workgroup_size(256, 1, 1)
511
+ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
512
+ let idx = gid.x;
513
+ let total = step.batch_len * 6144u;
514
+ if (idx >= total) {
515
+ return;
516
+ }
517
+ let g = gate_buf[idx];
518
+ out_buf[idx] = (g / (1.0 + exp(-g))) * up_buf[idx];
519
+ }
520
+ `;
521
+
522
+ export const COPY_LAST_ROW_WGSL = `
523
+ struct StepParams {
524
+ batch_len: u32,
525
+ start_pos: u32,
526
+ max_seq: u32,
527
+ pad0: u32,
528
+ };
529
+
530
+ @group(0) @binding(0) var<uniform> step: StepParams;
531
+ @group(0) @binding(1) var<storage, read> in_x: array<f32>;
532
+ @group(0) @binding(2) var<storage, read_write> last_x: array<f32>;
533
+
534
+ @compute @workgroup_size(256, 1, 1)
535
+ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
536
+ let idx = gid.x;
537
+ if (idx < 2048u) {
538
+ let base = (step.batch_len - 1u) * 2048u;
539
+ last_x[idx] = in_x[base + idx];
540
+ }
541
+ }
542
+ `;
543
+
544
+ export const TOPK_BLOCKS_WGSL = `
545
+ const VOCAB_SIZE: u32 = 151669u;
546
+
547
+ struct Candidate {
548
+ logit: f32,
549
+ token_id: u32,
550
+ };
551
+
552
+ @group(0) @binding(0) var<storage, read> logits: array<f32>;
553
+ @group(0) @binding(1) var<storage, read_write> out_top: array<Candidate>;
554
+
555
+ var<workgroup> sh_val: array<f32, 256>;
556
+ var<workgroup> sh_idx: array<u32, 256>;
557
+
558
+ @compute @workgroup_size(256, 1, 1)
559
+ fn main(
560
+ @builtin(workgroup_id) wg: vec3<u32>,
561
+ @builtin(local_invocation_id) lid: vec3<u32>,
562
+ ) {
563
+ let block = wg.x;
564
+ let tid = lid.x;
565
+
566
+ var best_v = -1e30;
567
+ var best_i = 0u;
568
+ for (var idx = block + tid * 64u; idx < VOCAB_SIZE; idx += 16384u) {
569
+ let v = logits[idx];
570
+ if (v > best_v) {
571
+ best_v = v;
572
+ best_i = idx;
573
+ }
574
+ }
575
+ sh_val[tid] = best_v;
576
+ sh_idx[tid] = best_i;
577
+ workgroupBarrier();
578
+
579
+ for (var stride = 128u; stride > 0u; stride >>= 1u) {
580
+ if (tid < stride) {
581
+ let other_v = sh_val[tid + stride];
582
+ let other_i = sh_idx[tid + stride];
583
+ if (other_v > sh_val[tid] || (other_v == sh_val[tid] && other_i < sh_idx[tid])) {
584
+ sh_val[tid] = other_v;
585
+ sh_idx[tid] = other_i;
586
+ }
587
+ }
588
+ workgroupBarrier();
589
+ }
590
+
591
+ if (tid == 0u) {
592
+ out_top[block] = Candidate(sh_val[0], sh_idx[0]);
593
+ }
594
+ }
595
+ `;
web/src/bonsai-tokenizer.js ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Pure-JS Qwen3 ByteLevel BPE tokenizer matching Hugging Face tokenizers / llama.cpp.
2
+
3
+ const PRE_TOKENIZE_RE = new RegExp(
4
+ [
5
+ "(?:'[sStTrRdDmM]|'[rR][eE]|'[vV][eE]|'[lL][lL])",
6
+ "[^\\r\\n\\p{L}\\p{N}]?\\p{L}+",
7
+ "\\p{N}",
8
+ " ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*",
9
+ "\\s*[\\r\\n]+",
10
+ "\\s+(?!\\S)",
11
+ "\\s+",
12
+ ].join("|"),
13
+ "gu",
14
+ );
15
+
16
+ const MAX_WORD_CACHE = 8192;
17
+
18
+ function buildByteTables() {
19
+ const kept = [];
20
+ for (let b = 33; b <= 126; b += 1) kept.push(b);
21
+ for (let b = 161; b <= 172; b += 1) kept.push(b);
22
+ for (let b = 174; b <= 255; b += 1) kept.push(b);
23
+
24
+ const keptSet = new Set(kept);
25
+ const chars = kept.slice();
26
+ let extra = 0;
27
+ for (let b = 0; b < 256; b += 1) {
28
+ if (!keptSet.has(b)) {
29
+ kept.push(b);
30
+ chars.push(256 + extra);
31
+ extra += 1;
32
+ }
33
+ }
34
+ const byteToChar = new Array(256);
35
+ const charToByte = new Map();
36
+ for (let i = 0; i < 256; i += 1) {
37
+ const ch = String.fromCodePoint(chars[i]);
38
+ byteToChar[kept[i]] = ch;
39
+ charToByte.set(ch, kept[i]);
40
+ }
41
+ return { byteToChar, charToByte };
42
+ }
43
+
44
+ const { byteToChar, charToByte } = buildByteTables();
45
+ const utf8Encoder = new TextEncoder();
46
+
47
+ function escapeRegex(literal) {
48
+ return literal.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
49
+ }
50
+
51
+ function findLowestRankPair(symbols, mergeRank) {
52
+ let bestRank = Infinity;
53
+ let bestKey = null;
54
+ for (let i = 0; i < symbols.length - 1; i += 1) {
55
+ const key = `${symbols[i]} ${symbols[i + 1]}`;
56
+ const rank = mergeRank.get(key);
57
+ if (rank !== undefined && rank < bestRank) {
58
+ bestRank = rank;
59
+ bestKey = key;
60
+ }
61
+ }
62
+ return bestKey;
63
+ }
64
+
65
+ function mergePairOnce(symbols, first, second) {
66
+ const next = [];
67
+ let i = 0;
68
+ while (i < symbols.length) {
69
+ if (i < symbols.length - 1 && symbols[i] === first && symbols[i + 1] === second) {
70
+ next.push(first + second);
71
+ i += 2;
72
+ } else {
73
+ next.push(symbols[i]);
74
+ i += 1;
75
+ }
76
+ }
77
+ return next;
78
+ }
79
+
80
+ function applyBpe(wordSymbols, mergeRank) {
81
+ let symbols = wordSymbols;
82
+ while (symbols.length > 1) {
83
+ const pairKey = findLowestRankPair(symbols, mergeRank);
84
+ if (pairKey === null) {
85
+ break;
86
+ }
87
+ const splitAt = pairKey.indexOf(" ");
88
+ symbols = mergePairOnce(symbols, pairKey.slice(0, splitAt), pairKey.slice(splitAt + 1));
89
+ }
90
+ return symbols;
91
+ }
92
+
93
+ export class BonsaiTokenizer {
94
+ constructor(compact) {
95
+ this.vocab = compact.vocab;
96
+ this.eosTokenId = compact.eos_token_id ?? 151645;
97
+ this.padTokenId = compact.pad_token_id ?? 151643;
98
+ this.addedTokens = new Map(Object.entries(compact.added_tokens ?? {}));
99
+ this.specialIds = new Set(this.addedTokens.values());
100
+
101
+ this.vocabToId = new Map();
102
+ this.idToBytes = new Array(this.vocab.length);
103
+ for (let id = 0; id < this.vocab.length; id += 1) {
104
+ const token = this.vocab[id];
105
+ if (!token) continue;
106
+ this.vocabToId.set(token, id);
107
+ if (!this.specialIds.has(id)) {
108
+ const bytes = new Uint8Array(token.length);
109
+ let len = 0;
110
+ for (const ch of token) {
111
+ const b = charToByte.get(ch);
112
+ if (b !== undefined) {
113
+ bytes[len] = b;
114
+ len += 1;
115
+ }
116
+ }
117
+ this.idToBytes[id] = bytes.subarray(0, len);
118
+ }
119
+ }
120
+
121
+ this.mergeRank = new Map();
122
+ const mergeLines = compact.merges.split("\n");
123
+ for (let i = 0; i < mergeLines.length; i += 1) {
124
+ if (mergeLines[i]) {
125
+ this.mergeRank.set(mergeLines[i], i);
126
+ }
127
+ }
128
+
129
+ const specials = [...this.addedTokens.keys()].sort((a, b) => b.length - a.length);
130
+ this.specialSplitRe = specials.length
131
+ ? new RegExp(`(${specials.map(escapeRegex).join("|")})`, "g")
132
+ : null;
133
+ this.wordCache = new Map();
134
+ }
135
+
136
+ encodePiece(piece) {
137
+ const cached = this.wordCache.get(piece);
138
+ if (cached !== undefined) {
139
+ return cached;
140
+ }
141
+ const bytes = utf8Encoder.encode(piece);
142
+ const initial = new Array(bytes.length);
143
+ for (let i = 0; i < bytes.length; i += 1) {
144
+ initial[i] = byteToChar[bytes[i]];
145
+ }
146
+ const merged = applyBpe(initial, this.mergeRank);
147
+ const ids = [];
148
+ for (let i = 0; i < merged.length; i += 1) {
149
+ const id = this.vocabToId.get(merged[i]);
150
+ if (id !== undefined) {
151
+ ids.push(id);
152
+ }
153
+ }
154
+ if (this.wordCache.size >= MAX_WORD_CACHE) {
155
+ this.wordCache.clear();
156
+ }
157
+ this.wordCache.set(piece, ids);
158
+ return ids;
159
+ }
160
+
161
+ encode(text) {
162
+ const parts = this.specialSplitRe ? text.split(this.specialSplitRe) : [text];
163
+ const tokenIds = [];
164
+ for (const part of parts) {
165
+ if (!part) continue;
166
+ const specialId = this.addedTokens.get(part);
167
+ if (specialId !== undefined) {
168
+ tokenIds.push(specialId);
169
+ continue;
170
+ }
171
+ const normalized = part.normalize("NFC");
172
+ const matches = normalized.match(PRE_TOKENIZE_RE);
173
+ if (!matches) continue;
174
+ for (const piece of matches) {
175
+ const pieceIds = this.encodePiece(piece);
176
+ for (let i = 0; i < pieceIds.length; i += 1) {
177
+ tokenIds.push(pieceIds[i]);
178
+ }
179
+ }
180
+ }
181
+ return tokenIds;
182
+ }
183
+
184
+ createStreamDecoder() {
185
+ const decoder = new TextDecoder("utf-8", { fatal: false });
186
+ return {
187
+ push: (tokenId) => {
188
+ if (this.specialIds.has(tokenId)) {
189
+ return "";
190
+ }
191
+ const bytes = this.idToBytes[tokenId];
192
+ return bytes ? decoder.decode(bytes, { stream: true }) : "";
193
+ },
194
+ flush: () => decoder.decode(),
195
+ };
196
+ }
197
+ }
web/src/bonsai-webgpu.js ADDED
@@ -0,0 +1,572 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // WebGPU runtime for Bonsai 1.7B 2-bit packed ternary Qwen3ForCausalLM.
2
+ import {
3
+ COPY_LAST_ROW_WGSL,
4
+ EMBED_WGSL,
5
+ GQA_ATTN_WGSL,
6
+ QK_ROPE_KV_WGSL,
7
+ RMSNORM_WGSL,
8
+ SILU_MUL_WGSL,
9
+ TERNARY_GEMM_WGSL,
10
+ TERNARY_GEMV_WGSL,
11
+ TOPK_BLOCKS_WGSL,
12
+ } from "./bonsai-shaders.js";
13
+ import { BonsaiTokenizer } from "./bonsai-tokenizer.js";
14
+
15
+ export const DEFAULT_MODEL_BASE =
16
+ "https://huggingface.co/brianbellx/codehygiene-bonsai-1.7b/resolve/main/webgpu";
17
+
18
+ const CACHE_NAME = "codehygiene-bonsai-17b-v1";
19
+ const NUM_LAYERS = 28;
20
+ const LAYERS_PER_SHARD = 7;
21
+ const MAX_SEQ_LEN = 4096;
22
+ const PREFILL_BATCH = 16;
23
+ const UNIFORM_ALIGN = 256;
24
+ const TOPK_BLOCKS = 64;
25
+
26
+ const LAYER_TRIT_STRIDE = 3_145_728;
27
+ const LAYER_SCALE_STRIDE = 786_432;
28
+ const LAYER_NORM_STRIDE = 4_352;
29
+ const FINAL_NORM_OFFSET = NUM_LAYERS * LAYER_NORM_STRIDE;
30
+ const COS_TABLE_OFFSET = FINAL_NORM_OFFSET + 2048;
31
+ const SIN_TABLE_OFFSET = COS_TABLE_OFFSET + MAX_SEQ_LEN * 64;
32
+
33
+ const PROJ_SPECS = [
34
+ { name: "q", rows: 2048, inGroups: 64, tritOff: 0, residual: 0 },
35
+ { name: "k", rows: 1024, inGroups: 64, tritOff: 262_144, residual: 0 },
36
+ { name: "v", rows: 1024, inGroups: 64, tritOff: 393_216, residual: 0 },
37
+ { name: "o", rows: 2048, inGroups: 64, tritOff: 524_288, residual: 1 },
38
+ { name: "gate", rows: 6144, inGroups: 64, tritOff: 786_432, residual: 0 },
39
+ { name: "up", rows: 6144, inGroups: 64, tritOff: 1_572_864, residual: 0 },
40
+ { name: "down", rows: 2048, inGroups: 192, tritOff: 2_359_296, residual: 1 },
41
+ ];
42
+
43
+ async function openModelCache() {
44
+ if (!globalThis.caches) return null;
45
+ try {
46
+ return await globalThis.caches.open(CACHE_NAME);
47
+ } catch (err) {
48
+ console.warn("Cache storage unavailable:", err);
49
+ return null;
50
+ }
51
+ }
52
+
53
+ async function fetchCachedResponse(url, signal) {
54
+ const cacheStore = await openModelCache();
55
+ if (cacheStore) {
56
+ const hit = await cacheStore.match(url);
57
+ if (hit) return hit;
58
+ }
59
+ const response = await fetch(url, { signal, mode: "cors" });
60
+ if (!response.ok) {
61
+ throw new Error(`Shard download failed (${response.status}): ${url}`);
62
+ }
63
+ if (cacheStore) {
64
+ try {
65
+ await cacheStore.put(url, response.clone());
66
+ } catch (err) {
67
+ console.warn("Cache write skipped:", err);
68
+ }
69
+ }
70
+ return response;
71
+ }
72
+
73
+ async function gunzipStreamToBytes(response, expectedBytes, onChunkBytes) {
74
+ const stream = response.body.pipeThrough(new DecompressionStream("gzip"));
75
+ const reader = stream.getReader();
76
+ const out = new Uint8Array(expectedBytes);
77
+ let offset = 0;
78
+ for (;;) {
79
+ const { value, done } = await reader.read();
80
+ if (done) break;
81
+ out.set(value, offset);
82
+ offset += value.byteLength;
83
+ onChunkBytes(value.byteLength);
84
+ }
85
+ if (offset !== expectedBytes) {
86
+ throw new Error(`Shard length mismatch: got ${offset}, expected ${expectedBytes}`);
87
+ }
88
+ return out;
89
+ }
90
+
91
+ function makeStorageBuffer(device, byteLength, extraUsage = 0) {
92
+ const aligned = Math.ceil(byteLength / 4) * 4;
93
+ return device.createBuffer({
94
+ size: aligned,
95
+ usage: GPUBufferUsage.STORAGE | extraUsage,
96
+ });
97
+ }
98
+
99
+ function sampleTopCandidates(stagingBytes, temperature, topP) {
100
+ const view = new DataView(stagingBytes);
101
+ let bestVal = -Infinity;
102
+ let bestId = 0;
103
+ const items = new Array(TOPK_BLOCKS);
104
+ for (let i = 0; i < TOPK_BLOCKS; i += 1) {
105
+ const logit = view.getFloat32(i * 8, true);
106
+ const tokenId = view.getUint32(i * 8 + 4, true);
107
+ items[i] = { logit, tokenId };
108
+ if (logit > bestVal) {
109
+ bestVal = logit;
110
+ bestId = tokenId;
111
+ }
112
+ }
113
+ if (!(temperature > 0)) {
114
+ return bestId;
115
+ }
116
+ items.sort((a, b) => b.logit - a.logit);
117
+ const invTemp = 1.0 / temperature;
118
+ const maxScaled = items[0].logit * invTemp;
119
+ let sumExp = 0;
120
+ const probs = new Float64Array(TOPK_BLOCKS);
121
+ for (let i = 0; i < TOPK_BLOCKS; i += 1) {
122
+ const p = Math.exp(items[i].logit * invTemp - maxScaled);
123
+ probs[i] = p;
124
+ sumExp += p;
125
+ }
126
+ let cum = 0;
127
+ let cutoff = TOPK_BLOCKS;
128
+ for (let i = 0; i < TOPK_BLOCKS; i += 1) {
129
+ probs[i] /= sumExp;
130
+ cum += probs[i];
131
+ if (cum >= topP) {
132
+ cutoff = i + 1;
133
+ break;
134
+ }
135
+ }
136
+ const target = Math.random() * cum;
137
+ let running = 0;
138
+ for (let i = 0; i < cutoff; i += 1) {
139
+ running += probs[i];
140
+ if (target <= running) {
141
+ return items[i].tokenId;
142
+ }
143
+ }
144
+ return items[0].tokenId;
145
+ }
146
+
147
+ function sharedPrefixLength(left, right) {
148
+ const limit = Math.min(left.length, right.length);
149
+ let idx = 0;
150
+ while (idx < limit && left[idx] === right[idx]) idx += 1;
151
+ return idx;
152
+ }
153
+
154
+ export async function probeWebGpuSupport() {
155
+ if (!globalThis.navigator?.gpu) return false;
156
+ try {
157
+ const adapter = await navigator.gpu.requestAdapter();
158
+ if (!adapter || adapter.info?.isFallbackAdapter) return false;
159
+ return true;
160
+ } catch {
161
+ return false;
162
+ }
163
+ }
164
+
165
+ export class BonsaiWebGpuEngine {
166
+ constructor(device, tokenizer, buffers, pipelines, ops) {
167
+ this.device = device;
168
+ this.tokenizer = tokenizer;
169
+ this.buffers = buffers;
170
+ this.pipelines = pipelines;
171
+ this.ops = ops;
172
+ this.cachedTokens = [];
173
+ }
174
+
175
+ static async load({ baseUrl = DEFAULT_MODEL_BASE, signal, onProgress = () => {} } = {}) {
176
+ if (!globalThis.navigator?.gpu) {
177
+ throw new Error("WebGPU is unavailable in this browser.");
178
+ }
179
+ const adapter = await navigator.gpu.requestAdapter();
180
+ if (!adapter || adapter.info?.isFallbackAdapter) {
181
+ throw new Error("Hardware WebGPU adapter is unavailable.");
182
+ }
183
+ const device = await adapter.requestDevice();
184
+
185
+ const manifestRes = await fetchCachedResponse(`${baseUrl}/manifest.json`, signal);
186
+ const manifest = await manifestRes.json();
187
+ const shards = manifest.shards;
188
+
189
+ const shardOrder = [
190
+ ["tokenizer", shards.tokenizer],
191
+ ["norms", shards.norms],
192
+ ["embed_trits", shards.embed_trits],
193
+ ["embed_scales", shards.embed_scales],
194
+ ["layer_scales", shards.layer_scales],
195
+ ["layers_0", shards.layers_0],
196
+ ["layers_1", shards.layers_1],
197
+ ["layers_2", shards.layers_2],
198
+ ["layers_3", shards.layers_3],
199
+ ];
200
+ const totalRawBytes = shardOrder.reduce((sum, [, info]) => sum + info.raw_bytes, 0);
201
+ let loadedRawBytes = 0;
202
+ const reportBytes = (delta) => {
203
+ loadedRawBytes += delta;
204
+ onProgress(Math.min(loadedRawBytes, totalRawBytes), totalRawBytes);
205
+ };
206
+
207
+ const tokBytes = await gunzipStreamToBytes(
208
+ await fetchCachedResponse(`${baseUrl}/${shards.tokenizer.file}`, signal),
209
+ shards.tokenizer.raw_bytes,
210
+ reportBytes,
211
+ );
212
+ const tokenizer = new BonsaiTokenizer(JSON.parse(new TextDecoder().decode(tokBytes)));
213
+
214
+ const gpuWeights = {};
215
+ for (const [key, info] of shardOrder.slice(1)) {
216
+ const rawBytes = await gunzipStreamToBytes(
217
+ await fetchCachedResponse(`${baseUrl}/${info.file}`, signal),
218
+ info.raw_bytes,
219
+ reportBytes,
220
+ );
221
+ const buf = makeStorageBuffer(device, info.raw_bytes, GPUBufferUsage.COPY_DST);
222
+ device.queue.writeBuffer(buf, 0, rawBytes);
223
+ gpuWeights[key] = buf;
224
+ }
225
+
226
+ const kvHalfBytes = 14 * 8 * MAX_SEQ_LEN * 64 * 4;
227
+ const buffers = {
228
+ ...gpuWeights,
229
+ stepUniform: device.createBuffer({
230
+ size: 16,
231
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
232
+ }),
233
+ tokenIds: makeStorageBuffer(device, PREFILL_BATCH * 4, GPUBufferUsage.COPY_DST),
234
+ x: makeStorageBuffer(device, PREFILL_BATCH * 2048 * 4),
235
+ lastX: makeStorageBuffer(device, 2048 * 4),
236
+ normed: makeStorageBuffer(device, PREFILL_BATCH * 2048 * 4),
237
+ q: makeStorageBuffer(device, PREFILL_BATCH * 2048 * 4),
238
+ k: makeStorageBuffer(device, PREFILL_BATCH * 1024 * 4),
239
+ v: makeStorageBuffer(device, PREFILL_BATCH * 1024 * 4),
240
+ attnOut: makeStorageBuffer(device, PREFILL_BATCH * 2048 * 4),
241
+ gate: makeStorageBuffer(device, PREFILL_BATCH * 6144 * 4),
242
+ up: makeStorageBuffer(device, PREFILL_BATCH * 6144 * 4),
243
+ mlpMid: makeStorageBuffer(device, PREFILL_BATCH * 6144 * 4),
244
+ logits: makeStorageBuffer(device, 151669 * 4),
245
+ topOut: makeStorageBuffer(device, TOPK_BLOCKS * 8, GPUBufferUsage.COPY_SRC),
246
+ topRead: device.createBuffer({
247
+ size: TOPK_BLOCKS * 8,
248
+ usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
249
+ }),
250
+ kCache0: makeStorageBuffer(device, kvHalfBytes),
251
+ vCache0: makeStorageBuffer(device, kvHalfBytes),
252
+ kCache1: makeStorageBuffer(device, kvHalfBytes),
253
+ vCache1: makeStorageBuffer(device, kvHalfBytes),
254
+ };
255
+
256
+ const compile = (code) =>
257
+ device.createComputePipelineAsync({
258
+ layout: "auto",
259
+ compute: { module: device.createShaderModule({ code }), entryPoint: "main" },
260
+ });
261
+
262
+ const [embed, rmsNorm, gemv, gemm, qkRopeKv, gqaAttn, siluMul, copyLast, topk] =
263
+ await Promise.all([
264
+ compile(EMBED_WGSL),
265
+ compile(RMSNORM_WGSL),
266
+ compile(TERNARY_GEMV_WGSL),
267
+ compile(TERNARY_GEMM_WGSL),
268
+ compile(QK_ROPE_KV_WGSL),
269
+ compile(GQA_ATTN_WGSL),
270
+ compile(SILU_MUL_WGSL),
271
+ compile(COPY_LAST_ROW_WGSL),
272
+ compile(TOPK_BLOCKS_WGSL),
273
+ ]);
274
+ const pipelines = { embed, rmsNorm, gemv, gemm, qkRopeKv, gqaAttn, siluMul, copyLast, topk };
275
+ const ops = BonsaiWebGpuEngine.buildLayerOps(device, buffers, pipelines);
276
+ await device.queue.onSubmittedWorkDone();
277
+ return new BonsaiWebGpuEngine(device, tokenizer, buffers, pipelines, ops);
278
+ }
279
+
280
+ static buildLayerOps(device, b, p) {
281
+ const totalSlots = NUM_LAYERS * 11 + 4;
282
+ const staticBytes = new ArrayBuffer(totalSlots * UNIFORM_ALIGN);
283
+ const staticU32 = new Uint32Array(staticBytes);
284
+ let nextSlot = 0;
285
+ const allocSlot = (vals) => {
286
+ const slot = nextSlot;
287
+ nextSlot += 1;
288
+ staticU32.set(vals, (slot * UNIFORM_ALIGN) / 4);
289
+ return slot * UNIFORM_ALIGN;
290
+ };
291
+
292
+ const staticBuf = device.createBuffer({
293
+ size: staticBytes.byteLength,
294
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
295
+ });
296
+
297
+ const mkBg = (pipeline, entries) =>
298
+ device.createBindGroup({
299
+ layout: pipeline.getBindGroupLayout(0),
300
+ entries: entries.map((resource, binding) => ({ binding, resource })),
301
+ });
302
+ const uSlice = (offset, size = 32) => ({ buffer: staticBuf, offset, size });
303
+ const ref = (buf) => ({ buffer: buf });
304
+ const stepRef = ref(b.stepUniform);
305
+
306
+ const embedBg = mkBg(p.embed, [
307
+ stepRef,
308
+ ref(b.tokenIds),
309
+ ref(b.embed_trits),
310
+ ref(b.embed_scales),
311
+ ref(b.x),
312
+ ]);
313
+ const siluBg = mkBg(p.siluMul, [stepRef, ref(b.gate), ref(b.up), ref(b.mlpMid)]);
314
+ const copyLastBg = mkBg(p.copyLast, [stepRef, ref(b.x), ref(b.lastX)]);
315
+
316
+ const layerShards = [b.layers_0, b.layers_1, b.layers_2, b.layers_3];
317
+ const layers = [];
318
+
319
+ for (let l = 0; l < NUM_LAYERS; l += 1) {
320
+ const shardBuf = layerShards[Math.floor(l / LAYERS_PER_SHARD)];
321
+ const lInShard = l % LAYERS_PER_SHARD;
322
+ const kCache = l < 14 ? b.kCache0 : b.kCache1;
323
+ const vCache = l < 14 ? b.vCache0 : b.vCache1;
324
+ const localLayer = l < 14 ? l : l - 14;
325
+
326
+ const inNormOff = allocSlot([l * LAYER_NORM_STRIDE, 2048, 0, 0]);
327
+ const postNormOff = allocSlot([l * LAYER_NORM_STRIDE + 2048, 2048, 0, 0]);
328
+ const attnOff = allocSlot([
329
+ localLayer,
330
+ l * LAYER_NORM_STRIDE + 4096,
331
+ l * LAYER_NORM_STRIDE + 4224,
332
+ COS_TABLE_OFFSET,
333
+ SIN_TABLE_OFFSET,
334
+ 0, 0, 0,
335
+ ]);
336
+
337
+ const projIO = {
338
+ q: [b.normed, b.q],
339
+ k: [b.normed, b.k],
340
+ v: [b.normed, b.v],
341
+ o: [b.attnOut, b.x],
342
+ gate: [b.normed, b.gate],
343
+ up: [b.normed, b.up],
344
+ down: [b.mlpMid, b.x],
345
+ };
346
+ const projs = {};
347
+ for (const spec of PROJ_SPECS) {
348
+ const tritOff = lInShard * LAYER_TRIT_STRIDE + spec.tritOff;
349
+ const scaleOff = l * LAYER_SCALE_STRIDE + spec.tritOff / 4;
350
+ const off = allocSlot([spec.rows, spec.inGroups, tritOff, scaleOff, spec.residual, 0, 0, 0]);
351
+ const [inBuf, outBuf] = projIO[spec.name];
352
+ projs[spec.name] = {
353
+ rows: spec.rows,
354
+ gemvBg: mkBg(p.gemv, [
355
+ uSlice(off),
356
+ ref(inBuf),
357
+ ref(shardBuf),
358
+ ref(b.layer_scales),
359
+ ref(outBuf),
360
+ ]),
361
+ gemmBg: mkBg(p.gemm, [
362
+ stepRef,
363
+ uSlice(off),
364
+ ref(inBuf),
365
+ ref(shardBuf),
366
+ ref(b.layer_scales),
367
+ ref(outBuf),
368
+ ]),
369
+ };
370
+ }
371
+
372
+ layers.push({
373
+ inNormBg: mkBg(p.rmsNorm, [
374
+ stepRef, uSlice(inNormOff, 16), ref(b.x), ref(b.norms), ref(b.normed),
375
+ ]),
376
+ postNormBg: mkBg(p.rmsNorm, [
377
+ stepRef, uSlice(postNormOff, 16), ref(b.x), ref(b.norms), ref(b.normed),
378
+ ]),
379
+ qkRopeBg: mkBg(p.qkRopeKv, [
380
+ stepRef,
381
+ uSlice(attnOff),
382
+ ref(b.norms),
383
+ ref(b.q),
384
+ ref(b.k),
385
+ ref(b.v),
386
+ ref(kCache),
387
+ ref(vCache),
388
+ ]),
389
+ gqaBg: mkBg(p.gqaAttn, [
390
+ stepRef,
391
+ uSlice(attnOff),
392
+ ref(b.q),
393
+ ref(kCache),
394
+ ref(vCache),
395
+ ref(b.attnOut),
396
+ ]),
397
+ projs,
398
+ });
399
+ }
400
+
401
+ const finalNormStepBuf = device.createBuffer({
402
+ size: 16,
403
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
404
+ });
405
+ device.queue.writeBuffer(finalNormStepBuf, 0, new Uint32Array([1, 0, MAX_SEQ_LEN, 0]));
406
+ const finalNormOff = allocSlot([FINAL_NORM_OFFSET, 2048, 0, 0]);
407
+ const finalNormBg = mkBg(p.rmsNorm, [
408
+ ref(finalNormStepBuf),
409
+ uSlice(finalNormOff, 16),
410
+ ref(b.lastX),
411
+ ref(b.norms),
412
+ ref(b.normed),
413
+ ]);
414
+
415
+ const lmHeadOff = allocSlot([151669, 64, 0, 0, 0, 0, 0, 0]);
416
+ const lmHeadBg = mkBg(p.gemv, [
417
+ uSlice(lmHeadOff),
418
+ ref(b.normed),
419
+ ref(b.embed_trits),
420
+ ref(b.embed_scales),
421
+ ref(b.logits),
422
+ ]);
423
+ const topkBg = mkBg(p.topk, [ref(b.logits), ref(b.topOut)]);
424
+
425
+ device.queue.writeBuffer(staticBuf, 0, staticBytes);
426
+ return { embedBg, siluBg, copyLastBg, layers, finalNormBg, lmHeadBg, topkBg };
427
+ }
428
+
429
+ encodeForwardStep(batchTokens, startPos, { computeLogits }) {
430
+ const batchLen = batchTokens.length;
431
+ const { device, buffers: b, pipelines: p, ops } = this;
432
+ const tokenArr = new Uint32Array(PREFILL_BATCH);
433
+ tokenArr.set(batchTokens);
434
+ device.queue.writeBuffer(b.tokenIds, 0, tokenArr);
435
+ device.queue.writeBuffer(b.stepUniform, 0, new Uint32Array([batchLen, startPos, MAX_SEQ_LEN, 0]));
436
+
437
+ const enc = device.createCommandEncoder();
438
+ const pass = enc.beginComputePass();
439
+ const dispatchOp = (pipeline, bindGroup, wgX, wgY = 1) => {
440
+ pass.setPipeline(pipeline);
441
+ pass.setBindGroup(0, bindGroup);
442
+ pass.dispatchWorkgroups(wgX, wgY, 1);
443
+ };
444
+ const runMat = (proj) => {
445
+ if (batchLen === 1) {
446
+ dispatchOp(p.gemv, proj.gemvBg, Math.ceil(proj.rows / 4));
447
+ } else {
448
+ dispatchOp(p.gemm, proj.gemmBg, Math.ceil(proj.rows / 16), Math.ceil(batchLen / 16));
449
+ }
450
+ };
451
+
452
+ dispatchOp(p.embed, ops.embedBg, batchLen, 8);
453
+
454
+ for (let l = 0; l < NUM_LAYERS; l += 1) {
455
+ const layer = ops.layers[l];
456
+ dispatchOp(p.rmsNorm, layer.inNormBg, batchLen);
457
+ runMat(layer.projs.q);
458
+ runMat(layer.projs.k);
459
+ runMat(layer.projs.v);
460
+ dispatchOp(p.qkRopeKv, layer.qkRopeBg, batchLen, 24);
461
+ dispatchOp(p.gqaAttn, layer.gqaBg, batchLen, 16);
462
+ runMat(layer.projs.o);
463
+ dispatchOp(p.rmsNorm, layer.postNormBg, batchLen);
464
+ runMat(layer.projs.gate);
465
+ runMat(layer.projs.up);
466
+ dispatchOp(p.siluMul, ops.siluBg, Math.ceil((batchLen * 6144) / 256));
467
+ runMat(layer.projs.down);
468
+ }
469
+
470
+ if (computeLogits) {
471
+ const headSteps = [
472
+ [p.copyLast, ops.copyLastBg, 8],
473
+ [p.rmsNorm, ops.finalNormBg, 1],
474
+ [p.gemv, ops.lmHeadBg, Math.ceil(151669 / 4)],
475
+ [p.topk, ops.topkBg, TOPK_BLOCKS],
476
+ ];
477
+ for (const [pl, bg, wg] of headSteps) {
478
+ dispatchOp(pl, bg, wg);
479
+ }
480
+ }
481
+
482
+ pass.end();
483
+ if (computeLogits) {
484
+ enc.copyBufferToBuffer(b.topOut, 0, b.topRead, 0, TOPK_BLOCKS * 8);
485
+ }
486
+ device.queue.submit([enc.finish()]);
487
+ }
488
+
489
+ async readNextToken(temperature, topP) {
490
+ const readBuf = this.buffers.topRead;
491
+ await readBuf.mapAsync(GPUMapMode.READ);
492
+ try {
493
+ const copy = readBuf.getMappedRange().slice(0);
494
+ return sampleTopCandidates(copy, temperature, topP);
495
+ } finally {
496
+ readBuf.unmap();
497
+ }
498
+ }
499
+
500
+ promptFits(promptTokens, maxNewTokens = 1024) {
501
+ return promptTokens.length + maxNewTokens <= MAX_SEQ_LEN;
502
+ }
503
+
504
+ async streamCompletion(prompt, {
505
+ maxNewTokens = 1024,
506
+ temperature = 0.0,
507
+ topP = 1.0,
508
+ shouldCancel = () => false,
509
+ onProgress = () => {},
510
+ onToken = () => {},
511
+ } = {}) {
512
+ const promptTokens = this.tokenizer.encode(prompt);
513
+ const totalPrompt = promptTokens.length;
514
+ if (!this.promptFits(promptTokens, 256)) {
515
+ throw new Error("Prompt exceeds browser WebGPU context window.");
516
+ }
517
+
518
+ const reuse = Math.min(sharedPrefixLength(this.cachedTokens, promptTokens), totalPrompt - 1);
519
+ onProgress(reuse, totalPrompt);
520
+
521
+ let cursor = reuse;
522
+ while (cursor < totalPrompt) {
523
+ if (shouldCancel()) return "";
524
+ const remaining = totalPrompt - cursor;
525
+ const chunkLen = Math.min(PREFILL_BATCH, remaining);
526
+ const isFinalChunk = cursor + chunkLen === totalPrompt;
527
+ const batch = promptTokens.slice(cursor, cursor + chunkLen);
528
+ this.encodeForwardStep(batch, cursor, { computeLogits: isFinalChunk });
529
+ cursor += chunkLen;
530
+ if (!isFinalChunk) {
531
+ await this.device.queue.onSubmittedWorkDone();
532
+ }
533
+ onProgress(cursor, totalPrompt);
534
+ }
535
+
536
+ const history = promptTokens.slice();
537
+ const decoder = this.tokenizer.createStreamDecoder();
538
+ const tokenLimit = Math.min(maxNewTokens, MAX_SEQ_LEN - totalPrompt);
539
+ let fullReply = "";
540
+
541
+ for (let step = 0; step < tokenLimit; step += 1) {
542
+ if (shouldCancel()) {
543
+ this.cachedTokens = history;
544
+ return fullReply;
545
+ }
546
+ const nextId = await this.readNextToken(temperature, topP);
547
+ if (nextId === this.tokenizer.eosTokenId || nextId === this.tokenizer.padTokenId) {
548
+ break;
549
+ }
550
+ const piece = decoder.push(nextId);
551
+ if (piece) {
552
+ fullReply += piece;
553
+ onToken(piece);
554
+ if (fullReply.includes("<|im_end|>")) {
555
+ break;
556
+ }
557
+ }
558
+ const pos = history.length;
559
+ history.push(nextId);
560
+ if (step + 1 < tokenLimit && pos < MAX_SEQ_LEN) {
561
+ this.encodeForwardStep([nextId], pos, { computeLogits: true });
562
+ }
563
+ }
564
+ const tail = decoder.flush();
565
+ if (tail) {
566
+ fullReply += tail;
567
+ onToken(tail);
568
+ }
569
+ this.cachedTokens = history;
570
+ return fullReply.split("<|im_end|>")[0];
571
+ }
572
+ }
web/src/bonsai-worker.js ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Web Worker running Bonsai 1.7B WebGPU inference and closed-loop v0.6 codehygiene verification.
2
+ import { loadWeights } from "shared:engine";
3
+ import { buildPrompt, previewContent, scoreHygieneDict, verifyPatch } from "./bonsai-guards.js";
4
+ import { BonsaiWebGpuEngine, DEFAULT_MODEL_BASE } from "./bonsai-webgpu.js";
5
+
6
+ const PREVIEW_INTERVAL_MS = 85;
7
+ const PROGRESS_INTERVAL_MS = 200;
8
+ const GREEDY = { temperature: 0.0, topP: 1.0 };
9
+ const SAMPLED = { temperature: 0.45, topP: 0.92 };
10
+
11
+ const weightsReady = loadWeights(new URL("./weights.npz", import.meta.url).href);
12
+ let enginePromise = null;
13
+ let loadedBaseUrl = null;
14
+ const cancelledIds = new Set();
15
+
16
+ function getEngine(baseUrl, onLoadProgress) {
17
+ const resolvedBase = baseUrl || DEFAULT_MODEL_BASE;
18
+ if (!enginePromise || loadedBaseUrl !== resolvedBase) {
19
+ loadedBaseUrl = resolvedBase;
20
+ enginePromise = BonsaiWebGpuEngine.load({
21
+ baseUrl: resolvedBase,
22
+ onProgress: onLoadProgress,
23
+ }).catch((err) => {
24
+ enginePromise = null;
25
+ throw err;
26
+ });
27
+ }
28
+ return enginePromise;
29
+ }
30
+
31
+ async function runSingleAttempt({
32
+ engine,
33
+ weights,
34
+ attemptNo,
35
+ passNo,
36
+ base,
37
+ hygiene,
38
+ filename,
39
+ threshold,
40
+ sampled,
41
+ isCancelled,
42
+ emit,
43
+ }) {
44
+ if (isCancelled()) return { cancelled: true };
45
+ emit("attempt", { n: attemptNo, pass: passNo, sampled });
46
+
47
+ const prompt = buildPrompt(base, hygiene, filename);
48
+ const sampling = sampled ? SAMPLED : GREEDY;
49
+ let raw = "";
50
+ let tokens = 0;
51
+ let lastPreview = base;
52
+ let lastPreviewAt = 0;
53
+ let lastProgressAt = -PROGRESS_INTERVAL_MS;
54
+ let readFinished = false;
55
+
56
+ const flushPreview = () => {
57
+ lastPreviewAt = performance.now();
58
+ const found = previewContent(base, raw);
59
+ if (found && found.content !== lastPreview) {
60
+ lastPreview = found.content;
61
+ emit("preview", { content: lastPreview, applied_blocks: found.applied });
62
+ }
63
+ };
64
+
65
+ const reply = await engine.streamCompletion(prompt, {
66
+ maxNewTokens: 1024,
67
+ temperature: sampling.temperature,
68
+ topP: sampling.topP,
69
+ shouldCancel: isCancelled,
70
+ onProgress: (done, total) => {
71
+ if (tokens > 0 || readFinished) return;
72
+ const now = performance.now();
73
+ const finished = done >= total;
74
+ if (!finished && now - lastProgressAt < PROGRESS_INTERVAL_MS) return;
75
+ lastProgressAt = now;
76
+ readFinished = finished;
77
+ emit("progress", { phase: "read", done: Math.min(done, total), total });
78
+ },
79
+ onToken: (piece) => {
80
+ raw += piece;
81
+ tokens += 1;
82
+ emit("token", { text: piece });
83
+ if (performance.now() - lastPreviewAt >= PREVIEW_INTERVAL_MS) {
84
+ flushPreview();
85
+ }
86
+ },
87
+ });
88
+
89
+ if (isCancelled()) return { cancelled: true };
90
+ flushPreview();
91
+
92
+ const verdict = verifyPatch(base, reply, filename, threshold, hygiene, weights);
93
+ emit("verdict", {
94
+ n: attemptNo,
95
+ accepted: verdict.accepted,
96
+ reason: verdict.reason,
97
+ squiggles_before: verdict.squigglesBefore,
98
+ squiggles_after: verdict.squigglesAfter,
99
+ score_after: verdict.scoreAfter,
100
+ applied_blocks: verdict.appliedBlocks,
101
+ });
102
+ return { cancelled: false, verdict, tokens };
103
+ }
104
+
105
+ async function runFixJob(id, body, modelBaseUrl) {
106
+ const isCancelled = () => cancelledIds.has(id);
107
+ const emit = (name, data) => {
108
+ if (!isCancelled()) {
109
+ globalThis.postMessage({ id, event: name, data });
110
+ }
111
+ };
112
+
113
+ const startedAt = performance.now();
114
+ const weights = await weightsReady;
115
+ const threshold = body.threshold ?? 0.55;
116
+ const maxPasses = body.max_passes ?? 2;
117
+ const filename = body.filename ?? "";
118
+ const content = body.content ?? "";
119
+
120
+ const before = scoreHygieneDict(content, weights, threshold);
121
+ if (!before.squiggles || before.squiggles.length === 0) {
122
+ emit("start", { before_hygiene: before, model_id: "bonsai-1.7b-webgpu", cached: false });
123
+ emit("done", {
124
+ filename,
125
+ changes: "",
126
+ applied_blocks: 0,
127
+ updated_content: content,
128
+ before_hygiene: before,
129
+ after_hygiene: before,
130
+ passes_used: 0,
131
+ latency_ms: Math.round(performance.now() - startedAt),
132
+ accepted: false,
133
+ reason: null,
134
+ cached: false,
135
+ });
136
+ return;
137
+ }
138
+
139
+ let lastLoadEmit = 0;
140
+ const engine = await getEngine(modelBaseUrl, (done, total) => {
141
+ const now = performance.now();
142
+ if (done < total && now - lastLoadEmit < PROGRESS_INTERVAL_MS) return;
143
+ lastLoadEmit = now;
144
+ emit("progress", { phase: "read", done, total });
145
+ });
146
+
147
+ const firstPrompt = buildPrompt(content, before, filename);
148
+ if (!engine.promptFits(engine.tokenizer.encode(firstPrompt), 256)) {
149
+ throw new Error("Prompt exceeds browser WebGPU context budget.");
150
+ }
151
+
152
+ emit("start", { before_hygiene: before, model_id: "bonsai-1.7b-webgpu", cached: false });
153
+
154
+ let attemptCount = 0;
155
+ let totalTokens = 0;
156
+ const acceptedList = [];
157
+ let passesUsed = 1;
158
+ let rejectReason = null;
159
+
160
+ const nextAttempt = (passNo, base, hygiene, sampled) => {
161
+ attemptCount += 1;
162
+ return runSingleAttempt({
163
+ engine,
164
+ weights,
165
+ attemptNo: attemptCount,
166
+ passNo,
167
+ base,
168
+ hygiene,
169
+ filename,
170
+ threshold,
171
+ sampled,
172
+ isCancelled,
173
+ emit,
174
+ });
175
+ };
176
+
177
+ const first = await nextAttempt(1, content, before, false);
178
+ if (first.cancelled) return;
179
+ totalTokens += first.tokens;
180
+ if (first.verdict.accepted) {
181
+ acceptedList.push(first.verdict);
182
+ }
183
+
184
+ if (maxPasses >= 2) {
185
+ if (first.verdict.accepted && first.verdict.squigglesAfter > 0) {
186
+ passesUsed = 2;
187
+ const second = await nextAttempt(2, first.verdict.content, first.verdict.hygiene, false);
188
+ if (second.cancelled) return;
189
+ totalTokens += second.tokens;
190
+ if (second.verdict.accepted) {
191
+ acceptedList.push(second.verdict);
192
+ }
193
+ } else if (!first.verdict.accepted) {
194
+ passesUsed = 2;
195
+ const retries = [];
196
+ for (let r = 0; r < 2; r += 1) {
197
+ const res = await nextAttempt(2, content, before, true);
198
+ if (res.cancelled) return;
199
+ totalTokens += res.tokens;
200
+ retries.push(res.verdict);
201
+ }
202
+ const valid = retries.filter((v) => v.accepted);
203
+ if (valid.length > 0) {
204
+ valid.sort((a, b) => {
205
+ const sqDiff = a.squigglesAfter - b.squigglesAfter;
206
+ return sqDiff !== 0 ? sqDiff : (b.scoreAfter ?? 0) - (a.scoreAfter ?? 0);
207
+ });
208
+ acceptedList.push(valid[0]);
209
+ } else {
210
+ rejectReason = retries[retries.length - 1].reason;
211
+ }
212
+ }
213
+ }
214
+ if (acceptedList.length === 0 && rejectReason === null) {
215
+ rejectReason = first.verdict.reason;
216
+ }
217
+
218
+ const finalVerdict = acceptedList.length > 0 ? acceptedList[acceptedList.length - 1] : null;
219
+ emit("done", {
220
+ filename,
221
+ changes: acceptedList.map((v) => v.reply).join("\n\n"),
222
+ applied_blocks: acceptedList.reduce((s, v) => s + v.appliedBlocks, 0),
223
+ updated_content: finalVerdict ? finalVerdict.content : content,
224
+ before_hygiene: before,
225
+ after_hygiene: finalVerdict ? finalVerdict.hygiene : before,
226
+ passes_used: passesUsed,
227
+ latency_ms: Math.round(performance.now() - startedAt),
228
+ accepted: finalVerdict !== null,
229
+ reason: finalVerdict ? null : rejectReason,
230
+ cached: false,
231
+ tokens: totalTokens,
232
+ });
233
+ }
234
+
235
+ let queueChain = Promise.resolve();
236
+
237
+ globalThis.addEventListener("message", (messageEvent) => {
238
+ const { type, id, body, modelBaseUrl } = messageEvent.data;
239
+ if (type === "cancel") {
240
+ cancelledIds.add(id);
241
+ return;
242
+ }
243
+ if (type === "fix") {
244
+ queueChain = queueChain.then(async () => {
245
+ if (cancelledIds.has(id)) {
246
+ cancelledIds.delete(id);
247
+ globalThis.postMessage({ id, done: true });
248
+ return;
249
+ }
250
+ try {
251
+ await runFixJob(id, body, modelBaseUrl);
252
+ globalThis.postMessage({ id, done: true });
253
+ } catch (err) {
254
+ const message = err && err.message ? err.message : String(err);
255
+ globalThis.postMessage({ id, fallback: true, error: message });
256
+ } finally {
257
+ cancelledIds.delete(id);
258
+ }
259
+ });
260
+ }
261
+ });
web/src/browser-refiner.js ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Browser-first Bonsai 1.7B WebGPU cleanup with automatic Hugging Face ZeroGPU fallback.
2
+ import { probeWebGpuSupport } from "./bonsai-webgpu.js";
3
+ import { streamFix } from "./refiner.js";
4
+
5
+ const BONSAI_WORKER_URL = new URL("./bonsai-worker.js", import.meta.url);
6
+
7
+ let sharedWorker = null;
8
+ let webGpuAvailablePromise = null;
9
+ let serverBackend = "zerogpu";
10
+ let nextRequestId = 1;
11
+ const pendingJobs = new Map();
12
+
13
+ export function setServerBackend(backend) {
14
+ serverBackend = backend || "zerogpu";
15
+ }
16
+
17
+ function configuredMode() {
18
+ try {
19
+ const param = new URLSearchParams(globalThis.location?.search ?? "").get("refiner");
20
+ return param ? param.toLowerCase() : "auto";
21
+ } catch {
22
+ return "auto";
23
+ }
24
+ }
25
+
26
+ function configuredModelBaseUrl() {
27
+ try {
28
+ const override = globalThis.__CODEHYGIENE_BONSAI_URL;
29
+ if (override) return override;
30
+ return new URLSearchParams(globalThis.location?.search ?? "").get("bonsai_url") || "";
31
+ } catch {
32
+ return "";
33
+ }
34
+ }
35
+
36
+ function canTryBrowserModel() {
37
+ const mode = configuredMode();
38
+ if (mode === "zerogpu" || mode === "server") {
39
+ return Promise.resolve(false);
40
+ }
41
+ if (mode === "auto" && serverBackend === "mock") {
42
+ return Promise.resolve(false);
43
+ }
44
+ if (!webGpuAvailablePromise) {
45
+ webGpuAvailablePromise = probeWebGpuSupport();
46
+ }
47
+ return webGpuAvailablePromise;
48
+ }
49
+
50
+ function getBonsaiWorker() {
51
+ if (!sharedWorker) {
52
+ sharedWorker = new Worker(BONSAI_WORKER_URL, { type: "module" });
53
+ sharedWorker.addEventListener("message", (event) => {
54
+ const { id, event: eventName, data, done, fallback, error } = event.data;
55
+ const job = pendingJobs.get(id);
56
+ if (!job) return;
57
+ if (eventName) {
58
+ job.emittedTerminal ||= eventName === "done";
59
+ job.onEvent(eventName, data);
60
+ return;
61
+ }
62
+ pendingJobs.delete(id);
63
+ if (fallback) {
64
+ job.resolve({ fallback: true, error });
65
+ } else if (done) {
66
+ job.resolve({ fallback: false });
67
+ }
68
+ });
69
+ sharedWorker.addEventListener("error", () => {
70
+ for (const [id, job] of pendingJobs.entries()) {
71
+ pendingJobs.delete(id);
72
+ job.resolve({ fallback: true, error: "worker_crash" });
73
+ }
74
+ sharedWorker = null;
75
+ });
76
+ }
77
+ return sharedWorker;
78
+ }
79
+
80
+ function runWorkerSession(body, { signal, onEvent }) {
81
+ return new Promise((resolve) => {
82
+ const id = nextRequestId;
83
+ nextRequestId += 1;
84
+ const worker = getBonsaiWorker();
85
+ const job = { onEvent, emittedTerminal: false, resolve };
86
+ pendingJobs.set(id, job);
87
+
88
+ const onAbort = () => {
89
+ pendingJobs.delete(id);
90
+ worker.postMessage({ type: "cancel", id });
91
+ resolve({ fallback: false, aborted: true });
92
+ };
93
+ if (signal?.aborted) {
94
+ onAbort();
95
+ return;
96
+ }
97
+ signal?.addEventListener("abort", onAbort, { once: true });
98
+ worker.postMessage({
99
+ type: "fix",
100
+ id,
101
+ body,
102
+ modelBaseUrl: configuredModelBaseUrl(),
103
+ });
104
+ });
105
+ }
106
+
107
+ export async function streamCleanup(body, { signal, onEvent }) {
108
+ if (await canTryBrowserModel()) {
109
+ const outcome = await runWorkerSession(body, { signal, onEvent });
110
+ if (!outcome.fallback || signal?.aborted) {
111
+ return;
112
+ }
113
+ if (configuredMode() === "browser") {
114
+ onEvent("error", { code: "webgpu_failed", message: outcome.error || "WebGPU failed" });
115
+ return;
116
+ }
117
+ }
118
+ await streamFix(body, { signal, onEvent });
119
+ }
web/src/fix-run.js CHANGED
@@ -1,5 +1,5 @@
 
1
  import { STATUS } from "./labels.js";
2
- import { streamFix } from "./refiner.js";
3
  import { THRESHOLD } from "./scoring.js";
4
 
5
  const SEARCH_OPEN = "<<<<<<< SEARCH\n";
@@ -75,7 +75,7 @@ export class FixSession {
75
  body.no_cache = true;
76
  }
77
  try {
78
- await streamFix(body, {
79
  signal: this.controller.signal,
80
  onEvent: (name, data) => this.handle(name, data),
81
  });
 
1
+ import { streamCleanup } from "./browser-refiner.js";
2
  import { STATUS } from "./labels.js";
 
3
  import { THRESHOLD } from "./scoring.js";
4
 
5
  const SEARCH_OPEN = "<<<<<<< SEARCH\n";
 
75
  body.no_cache = true;
76
  }
77
  try {
78
+ await streamCleanup(body, {
79
  signal: this.controller.signal,
80
  onEvent: (name, data) => this.handle(name, data),
81
  });
web/src/index.html CHANGED
@@ -24,19 +24,27 @@
24
  <symbol id="i-download" viewBox="0 0 24 24"><path d="M12 4v11"/><path d="m7 10 5 5 5-5"/><path d="M5 20h14"/></symbol>
25
  <symbol id="i-pr" viewBox="0 0 24 24"><circle cx="6" cy="6" r="2.5"/><circle cx="18" cy="18" r="2.5"/><path d="M6 8.5V21"/><path d="M13 6h3a2 2 0 0 1 2 2v7.5"/><path d="m15.5 3.5-2.5 2.5 2.5 2.5"/></symbol>
26
  <symbol id="i-trophy" viewBox="0 0 24 24"><path d="M6 9H4.5a2.5 2.5 0 0 1 0-5H6"/><path d="M18 9h1.5a2.5 2.5 0 0 0 0-5H18"/><path d="M4 22h16"/><path d="M10 14.66V17c0 .55-.47.98-.97 1.21C7.85 18.75 7 20.24 7 22"/><path d="M14 14.66V17c0 .55.47.98.97 1.21C16.15 18.75 17 20.24 17 22"/><path d="M18 2H6v7a6 6 0 0 0 12 0V2Z"/></symbol>
 
27
  </svg>
28
- <aside class="banner" id="banner" aria-label="Live stats" hidden>
29
  <div class="banner-inner">
30
- <a class="banner-stats" id="banner-stats" href="leaderboard/#stats" target="_blank" rel="noopener" title="Stats">
31
  <span class="banner-stat" id="banner-fixed" hidden><b id="banner-fixed-value"></b> issues fixed</span>
32
  <span class="banner-stat" id="banner-merged" hidden><b id="banner-merged-value"></b> of PRs merged</span>
33
  <span class="banner-stat" id="banner-speed" hidden><b id="banner-speed-value"></b> per file</span>
34
  </a>
35
- <a class="banner-board" id="banner-board" href="leaderboard/" target="_blank" rel="noopener" aria-label="Leaderboard" title="Leaderboard" hidden>
36
- <svg class="icon" aria-hidden="true"><use href="#i-trophy"/></svg>
37
- <span class="banner-board-text">Leaderboard</span>
38
- <svg class="icon banner-board-arrow" aria-hidden="true"><use href="#i-external"/></svg>
39
- </a>
 
 
 
 
 
 
 
40
  </div>
41
  </aside>
42
  <div class="page">
 
24
  <symbol id="i-download" viewBox="0 0 24 24"><path d="M12 4v11"/><path d="m7 10 5 5 5-5"/><path d="M5 20h14"/></symbol>
25
  <symbol id="i-pr" viewBox="0 0 24 24"><circle cx="6" cy="6" r="2.5"/><circle cx="18" cy="18" r="2.5"/><path d="M6 8.5V21"/><path d="M13 6h3a2 2 0 0 1 2 2v7.5"/><path d="m15.5 3.5-2.5 2.5 2.5 2.5"/></symbol>
26
  <symbol id="i-trophy" viewBox="0 0 24 24"><path d="M6 9H4.5a2.5 2.5 0 0 1 0-5H6"/><path d="M18 9h1.5a2.5 2.5 0 0 0 0-5H18"/><path d="M4 22h16"/><path d="M10 14.66V17c0 .55-.47.98-.97 1.21C7.85 18.75 7 20.24 7 22"/><path d="M14 14.66V17c0 .55.47.98.97 1.21C16.15 18.75 17 20.24 17 22"/><path d="M18 2H6v7a6 6 0 0 0 12 0V2Z"/></symbol>
27
+ <symbol id="i-shield" viewBox="0 0 24 24"><path d="M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"/><path d="m9 12 2 2 4-4"/></symbol>
28
  </svg>
29
+ <aside class="banner" id="banner" aria-label="Live stats">
30
  <div class="banner-inner">
31
+ <a class="banner-stats" id="banner-stats" href="leaderboard/#stats" target="_blank" rel="noopener" title="Stats" hidden>
32
  <span class="banner-stat" id="banner-fixed" hidden><b id="banner-fixed-value"></b> issues fixed</span>
33
  <span class="banner-stat" id="banner-merged" hidden><b id="banner-merged-value"></b> of PRs merged</span>
34
  <span class="banner-stat" id="banner-speed" hidden><b id="banner-speed-value"></b> per file</span>
35
  </a>
36
+ <nav class="banner-links" aria-label="More">
37
+ <a class="banner-link" href="privacy/" target="_blank" rel="noopener" aria-label="Data retention" title="Data retention">
38
+ <svg class="icon" aria-hidden="true"><use href="#i-shield"/></svg>
39
+ <span class="banner-link-text">Data Retention</span>
40
+ <svg class="icon banner-link-arrow" aria-hidden="true"><use href="#i-external"/></svg>
41
+ </a>
42
+ <a class="banner-link" id="banner-board" href="leaderboard/" target="_blank" rel="noopener" aria-label="Leaderboard" title="Leaderboard" hidden>
43
+ <svg class="icon" aria-hidden="true"><use href="#i-trophy"/></svg>
44
+ <span class="banner-link-text">Leaderboard</span>
45
+ <svg class="icon banner-link-arrow" aria-hidden="true"><use href="#i-external"/></svg>
46
+ </a>
47
+ </nav>
48
  </div>
49
  </aside>
50
  <div class="page">
web/src/main.js CHANGED
@@ -1,3 +1,4 @@
 
1
  import { byId, copyWithIcon, prefersReducedMotion, tweenNumber } from "./dom.js";
2
  import { FixSession } from "./fix-run.js";
3
  import { isFullRepoUrl, parseRepoSpec, specLabel } from "./github.js";
@@ -20,7 +21,7 @@ import { createNavigator } from "./navigator.js";
20
  import { createTabs } from "./tabs.js";
21
  import { paintSample } from "./sample.js";
22
  import { boardLink, rankErrorText, rankLabel, requestRank } from "./ranking.js";
23
- import { hideBanner, renderBanner, reportScan } from "./telemetry.js";
24
 
25
  const TIMING = {
26
  firstStart: 800,
@@ -636,6 +637,7 @@ function handlePaste(event) {
636
  }
637
 
638
  function applyHealth(health) {
 
639
  app.maxChars = health.max_file_chars || DEFAULT_MAX_FILE_CHARS;
640
  app.prEnabled = health.github_pr_enabled === true;
641
  byId("foot-mode").hidden = health.backend !== "mock";
@@ -674,7 +676,7 @@ function bindControls() {
674
  function boot() {
675
  bindControls();
676
  app.healthReady = fetchHealth().then(applyHealth, keepDefaultLimits);
677
- fetchStats().then(renderBanner, hideBanner);
678
  paintSample(scorer.scoreAll);
679
  const repoParam = new URLSearchParams(window.location.search).get("repo");
680
  const spec = repoParam ? parseRepoSpec(repoParam) : null;
 
1
+ import { setServerBackend } from "./browser-refiner.js";
2
  import { byId, copyWithIcon, prefersReducedMotion, tweenNumber } from "./dom.js";
3
  import { FixSession } from "./fix-run.js";
4
  import { isFullRepoUrl, parseRepoSpec, specLabel } from "./github.js";
 
21
  import { createTabs } from "./tabs.js";
22
  import { paintSample } from "./sample.js";
23
  import { boardLink, rankErrorText, rankLabel, requestRank } from "./ranking.js";
24
+ import { hideBannerStats, renderBanner, reportScan } from "./telemetry.js";
25
 
26
  const TIMING = {
27
  firstStart: 800,
 
637
  }
638
 
639
  function applyHealth(health) {
640
+ setServerBackend(health.backend);
641
  app.maxChars = health.max_file_chars || DEFAULT_MAX_FILE_CHARS;
642
  app.prEnabled = health.github_pr_enabled === true;
643
  byId("foot-mode").hidden = health.backend !== "mock";
 
676
  function boot() {
677
  bindControls();
678
  app.healthReady = fetchHealth().then(applyHealth, keepDefaultLimits);
679
+ fetchStats().then(renderBanner, hideBannerStats);
680
  paintSample(scorer.scoreAll);
681
  const repoParam = new URLSearchParams(window.location.search).get("repo");
682
  const spec = repoParam ? parseRepoSpec(repoParam) : null;
web/src/privacy.css ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .board.privacy-page {
2
+ max-width: 688px;
3
+ }
4
+
5
+ .privacy-updated {
6
+ grid-column: 3;
7
+ }
8
+
9
+ .privacy-title {
10
+ padding-top: 40px;
11
+ font-size: 44px;
12
+ font-weight: 600;
13
+ line-height: 48px;
14
+ letter-spacing: -0.015em;
15
+ text-transform: uppercase;
16
+ }
17
+
18
+ .privacy-lede {
19
+ margin-top: 12px;
20
+ color: var(--ink-2);
21
+ font-size: 18px;
22
+ line-height: 26px;
23
+ text-wrap: pretty;
24
+ }
25
+
26
+ .receipt {
27
+ margin: 36px 0 0;
28
+ }
29
+
30
+ .receipt-head,
31
+ .receipt-code {
32
+ border: 1px solid var(--line-strong);
33
+ background: var(--surface);
34
+ }
35
+
36
+ .receipt-head {
37
+ display: flex;
38
+ align-items: center;
39
+ justify-content: space-between;
40
+ gap: 12px;
41
+ height: 48px;
42
+ padding: 0 10px 0 12px;
43
+ border-bottom-color: var(--line);
44
+ border-radius: var(--radius-stage) var(--radius-stage) 0 0;
45
+ }
46
+
47
+ .receipt-meta {
48
+ flex: none;
49
+ color: var(--ink-3);
50
+ font-size: 14px;
51
+ line-height: 20px;
52
+ white-space: nowrap;
53
+ }
54
+
55
+ .receipt-meta b {
56
+ color: var(--ink);
57
+ font-weight: 500;
58
+ font-variant-numeric: tabular-nums;
59
+ }
60
+
61
+ .receipt-code.stage-code {
62
+ padding: 10px 0;
63
+ overflow: visible;
64
+ border-top: 0;
65
+ border-radius: 0 0 var(--radius-stage) var(--radius-stage);
66
+ box-shadow: var(--shadow-stage);
67
+ }
68
+
69
+ .receipt-code .src {
70
+ --indent: 2;
71
+ }
72
+
73
+ .receipt-key {
74
+ color: var(--ink-3);
75
+ }
76
+
77
+ .receipt-caption {
78
+ max-width: 600px;
79
+ margin-top: 14px;
80
+ color: var(--ink-3);
81
+ font-size: 13px;
82
+ line-height: 20px;
83
+ }
84
+
85
+ .receipt-caption a,
86
+ .fact a {
87
+ border-radius: var(--radius-sm);
88
+ color: var(--ink);
89
+ text-decoration: underline 1px var(--line-strong);
90
+ text-underline-offset: 3px;
91
+ transition: text-decoration-color var(--motion) var(--ease);
92
+ }
93
+
94
+ .receipt-caption a:hover,
95
+ .fact a:hover {
96
+ text-decoration-color: currentColor;
97
+ }
98
+
99
+ .facts {
100
+ margin: 40px 0 0;
101
+ border-top: 1px solid var(--line);
102
+ }
103
+
104
+ .fact {
105
+ display: grid;
106
+ grid-template-columns: 136px minmax(0, 1fr);
107
+ gap: 16px;
108
+ padding: 14px 0;
109
+ border-bottom: 1px solid var(--line);
110
+ font-size: 14.5px;
111
+ line-height: 22px;
112
+ }
113
+
114
+ .fact dt {
115
+ color: var(--ink-3);
116
+ }
117
+
118
+ .fact dd {
119
+ margin: 0;
120
+ color: var(--ink);
121
+ }
122
+
123
+ @media (max-width: 640px) {
124
+ .privacy-page .board-home {
125
+ height: 40px;
126
+ }
127
+
128
+ .privacy-page .board-home span,
129
+ .privacy-updated {
130
+ display: inline;
131
+ }
132
+
133
+ .privacy-updated {
134
+ grid-column: 2;
135
+ }
136
+
137
+ .privacy-title {
138
+ padding-top: 20px;
139
+ font-size: 36px;
140
+ line-height: 38px;
141
+ }
142
+
143
+ .privacy-lede {
144
+ margin-top: 10px;
145
+ font-size: 16px;
146
+ line-height: 24px;
147
+ }
148
+
149
+ .receipt {
150
+ margin-top: 28px;
151
+ }
152
+
153
+ .receipt-code.stage-code {
154
+ display: block;
155
+ overflow: visible;
156
+ font-size: 12.5px;
157
+ line-height: 22px;
158
+ }
159
+
160
+ .receipt-code .line {
161
+ grid-template-columns: var(--gutter) minmax(0, 1fr);
162
+ padding-right: 12px;
163
+ }
164
+
165
+ .receipt-code .src {
166
+ padding-left: calc((var(--indent) + 4) * 1ch);
167
+ text-indent: calc((var(--indent) + 4) * -1ch);
168
+ white-space: pre-wrap;
169
+ overflow-wrap: anywhere;
170
+ }
171
+
172
+ .receipt-caption {
173
+ font-size: 13.5px;
174
+ line-height: 20px;
175
+ }
176
+
177
+ .facts {
178
+ margin-top: 32px;
179
+ }
180
+
181
+ .fact {
182
+ grid-template-columns: minmax(0, 1fr);
183
+ gap: 2px;
184
+ padding: 12px 0;
185
+ font-size: 15px;
186
+ }
187
+
188
+ .fact dt {
189
+ font-size: 13px;
190
+ line-height: 20px;
191
+ }
192
+ }
web/src/privacy.html ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en" data-root="../">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <meta name="description" content="CodeHygiene keeps no code. This is everything it keeps.">
7
+ <title>Zero data retention · codehygiene</title>
8
+ <link rel="stylesheet" href="../styles.css">
9
+ <link rel="stylesheet" href="../board.css">
10
+ <link rel="stylesheet" href="../privacy.css">
11
+ </head>
12
+ <body class="board-page">
13
+ <svg class="sprite" aria-hidden="true">
14
+ <symbol id="i-back" viewBox="0 0 24 24"><path d="M19 12H5"/><path d="m11 18-6-6 6-6"/></symbol>
15
+ <symbol id="i-external" viewBox="5 5 14 14"><path d="M7 17 17 7"/><path d="M8 7h9v9"/></symbol>
16
+ </svg>
17
+
18
+ <div class="board privacy-page">
19
+ <header class="board-head">
20
+ <a class="board-home" href="../" title="Back to CodeHygiene">
21
+ <svg class="icon" aria-hidden="true"><use href="#i-back"/></svg>
22
+ <span>CodeHygiene</span>
23
+ </a>
24
+ <p class="board-updated privacy-updated">Updated November 2026</p>
25
+ </header>
26
+
27
+ <main>
28
+ <h1 class="privacy-title">Zero data retention</h1>
29
+ <p class="privacy-lede">Your code is never stored. This is everything that is.</p>
30
+
31
+ <figure class="receipt">
32
+ <div class="receipt-head">
33
+ <span class="stage-path"><span class="path-dir">app/</span>send_receipt.py</span>
34
+ <span class="receipt-meta"><span class="stage-status">Kept</span> <b>1</b> of 6 lines</span>
35
+ </div>
36
+ <div class="stage-code receipt-code">
37
+ <div class="line is-removed"><span class="ln"></span><span class="src"><span>path</span> app/send_receipt.py</span></div>
38
+ <div class="line is-removed"><span class="ln"></span><span class="src"><span>repo</span> acme/payments</span></div>
39
+ <div class="line is-removed"><span class="ln"></span><span class="src"><span>code</span> def send_receipt(order): …</span></div>
40
+ <div class="line is-removed"><span class="ln"></span><span class="src"><span>user</span> octocat</span></div>
41
+ <div class="line is-removed"><span class="ln"></span><span class="src"><span>ip </span> 203.0.113.7</span></div>
42
+ <div class="line is-added"><span class="ln">1</span><span class="src"><span class="receipt-key">kept</span> py · 100–300&nbsp;lines · score&nbsp;29 · 3&nbsp;issues · 14&nbsp;ms</span></div>
43
+ </div>
44
+ <figcaption class="receipt-caption">Even that line is not saved as a row. It is added to <a href="../leaderboard/#stats">public totals</a>, and a one-way fingerprint held only in memory keeps a file from counting twice.</figcaption>
45
+ </figure>
46
+
47
+ <dl class="facts">
48
+ <div class="fact">
49
+ <dt>Scoring</dt>
50
+ <dd>Runs in your browser. Code is not uploaded to score it.</dd>
51
+ </div>
52
+ <div class="fact">
53
+ <dt>Cleanup</dt>
54
+ <dd>A small model in your browser does the work, so the code stays on your device. If your device can't run it, a GPU on Hugging Face (ZeroGPU) does, holding the file in memory only. Public repo cleanups may be reused from memory until a restart.</dd>
55
+ </div>
56
+ <div class="fact">
57
+ <dt>Pull requests</dt>
58
+ <dd>Your GitHub sign-in opens one pull request, then it is revoked.</dd>
59
+ </div>
60
+ <div class="fact">
61
+ <dt>Leaderboard</dt>
62
+ <dd>A public repo is listed only when someone asks to rank it.</dd>
63
+ </div>
64
+ <div class="fact">
65
+ <dt>Cookies</dt>
66
+ <dd>CodeHygiene sets none. No accounts and no third&#8209;party scripts.</dd>
67
+ </div>
68
+ <div class="fact">
69
+ <dt>Hosting</dt>
70
+ <dd>Hugging Face Spaces, under the <a href="https://huggingface.co/privacy" target="_blank" rel="noopener">Hugging Face privacy policy</a>.</dd>
71
+ </div>
72
+ </dl>
73
+ </main>
74
+ </div>
75
+ </body>
76
+ </html>
web/src/reward-facts.json CHANGED
@@ -16,5 +16,23 @@
16
  { "label": "Python vs browser", "value": "Δ 0.0000", "title": "Largest score difference between the Python and JavaScript scorers" },
17
  { "label": "Model", "value": "14.85 KiB", "title": "1.58-bit weights, NumPy only" }
18
  ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  }
20
  }
 
16
  { "label": "Python vs browser", "value": "Δ 0.0000", "title": "Largest score difference between the Python and JavaScript scorers" },
17
  { "label": "Model", "value": "14.85 KiB", "title": "1.58-bit weights, NumPy only" }
18
  ]
19
+ },
20
+ "0.6.0": {
21
+ "ref": "818aa04623b07f1c7222a16d6ae594e9741f503c",
22
+ "facts": [
23
+ { "label": "Gaming gain", "value": "+0.012", "title": "Largest rl_reward gain from an adversarial probe (40 padding helpers)" },
24
+ { "label": "Held-out issues", "value": "1.8 / 100 lines", "title": "25 unmodified CPython 3.13 stdlib modules" },
25
+ { "label": "Python vs browser", "value": "Δ 0.0000", "title": "Largest score difference between the Python and JavaScript scorers" },
26
+ { "label": "Model", "value": "23.84 KiB", "title": "1.58-bit weights, NumPy only" }
27
+ ]
28
+ },
29
+ "0.6.1": {
30
+ "ref": "2ec03172f47f14655c1490540c2f593b77095807",
31
+ "facts": [
32
+ { "label": "Gaming gain", "value": "+0.012", "title": "Largest rl_reward gain from an adversarial probe (40 padding helpers)" },
33
+ { "label": "Held-out issues", "value": "1.8 / 100 lines", "title": "25 unmodified CPython 3.13 stdlib modules" },
34
+ { "label": "Python vs browser", "value": "Δ 0.0000", "title": "Largest score difference between the Python and JavaScript scorers" },
35
+ { "label": "Model", "value": "23.84 KiB", "title": "1.58-bit weights, NumPy only" }
36
+ ]
37
  }
38
  }
web/src/styles.css CHANGED
@@ -272,29 +272,39 @@ body:has(> .page) {
272
  font-variant-numeric: tabular-nums;
273
  }
274
 
275
- .banner-board {
276
- display: inline-flex;
277
  flex: none;
278
  align-items: center;
279
- gap: 6px;
280
  margin-left: auto;
 
 
 
 
 
 
281
  border-radius: var(--radius-sm);
282
  color: var(--ink);
283
  }
284
 
285
- .banner-board .icon {
 
 
 
 
286
  width: 14px;
287
  height: 14px;
288
  }
289
 
290
- .banner-board .banner-board-arrow {
291
  width: 10px;
292
  height: 10px;
293
  color: var(--ink-3);
294
  transition: color var(--motion) var(--ease), transform 160ms var(--ease-out);
295
  }
296
 
297
- .banner-board:hover .banner-board-arrow {
298
  color: var(--ink);
299
  transform: translate(1px, -1px);
300
  }
@@ -666,7 +676,7 @@ body:has(#source-progress:not([hidden])) :is(.stage-code, .tree-list, .sample) {
666
 
667
  .stage-head {
668
  display: grid;
669
- grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr);
670
  align-items: center;
671
  gap: 12px;
672
  height: 52px;
@@ -1253,12 +1263,20 @@ body:has(#source-progress:not([hidden])) :is(.stage-code, .tree-list, .sample) {
1253
  margin-right: -8px;
1254
  }
1255
 
 
 
 
 
1256
  .banner-stat.is-extra,
1257
- .banner-board-text,
1258
- .banner-board-arrow {
1259
  display: none;
1260
  }
1261
 
 
 
 
 
1262
  .headline {
1263
  font-size: 24px;
1264
  line-height: 30px;
 
272
  font-variant-numeric: tabular-nums;
273
  }
274
 
275
+ .banner-links {
276
+ display: flex;
277
  flex: none;
278
  align-items: center;
279
+ gap: 20px;
280
  margin-left: auto;
281
+ }
282
+
283
+ .banner-link {
284
+ display: inline-flex;
285
+ align-items: center;
286
+ gap: 6px;
287
  border-radius: var(--radius-sm);
288
  color: var(--ink);
289
  }
290
 
291
+ .banner-link[hidden] {
292
+ display: none;
293
+ }
294
+
295
+ .banner-link .icon {
296
  width: 14px;
297
  height: 14px;
298
  }
299
 
300
+ .banner-link .banner-link-arrow {
301
  width: 10px;
302
  height: 10px;
303
  color: var(--ink-3);
304
  transition: color var(--motion) var(--ease), transform 160ms var(--ease-out);
305
  }
306
 
307
+ .banner-link:hover .banner-link-arrow {
308
  color: var(--ink);
309
  transform: translate(1px, -1px);
310
  }
 
676
 
677
  .stage-head {
678
  display: grid;
679
+ grid-template-columns: minmax(max-content, 1fr) auto minmax(max-content, 1fr);
680
  align-items: center;
681
  gap: 12px;
682
  height: 52px;
 
1263
  margin-right: -8px;
1264
  }
1265
 
1266
+ .banner-links {
1267
+ gap: 16px;
1268
+ }
1269
+
1270
  .banner-stat.is-extra,
1271
+ .banner-link-text,
1272
+ .banner-link .banner-link-arrow {
1273
  display: none;
1274
  }
1275
 
1276
+ .banner-stats[hidden] + .banner-links .banner-link-text {
1277
+ display: inline;
1278
+ }
1279
+
1280
  .headline {
1281
  font-size: 24px;
1282
  line-height: 30px;
web/src/telemetry.js CHANGED
@@ -99,12 +99,11 @@ export function renderBanner(stats) {
99
  for (const id of ids) {
100
  byId(id).classList.toggle("is-extra", visibleIds.indexOf(id) >= PHONE_BANNER_STATS);
101
  }
102
- const anyStat = visibleIds.length > 0;
103
- byId("banner-stats").hidden = !anyStat;
104
  byId("banner-board").hidden = stats.leaderboard_entries < MIN_BOARD_ENTRIES;
105
- byId("banner").hidden = !anyStat && byId("banner-board").hidden;
106
  }
107
 
108
- export function hideBanner() {
109
- byId("banner").hidden = true;
 
110
  }
 
99
  for (const id of ids) {
100
  byId(id).classList.toggle("is-extra", visibleIds.indexOf(id) >= PHONE_BANNER_STATS);
101
  }
102
+ byId("banner-stats").hidden = visibleIds.length === 0;
 
103
  byId("banner-board").hidden = stats.leaderboard_entries < MIN_BOARD_ENTRIES;
 
104
  }
105
 
106
+ export function hideBannerStats() {
107
+ byId("banner-stats").hidden = true;
108
+ byId("banner-board").hidden = true;
109
  }