Skip to content

feat(labeler): serve the operator console and Access-guarded read API (W9.3 server) - #2015

Merged
ascorbic merged 3 commits into
feat/plugin-registry-labelling-servicefrom
feat/labeler-console-server
Jul 13, 2026
Merged

ascorbic merged 3 commits into
feat/plugin-registry-labelling-servicefrom
feat/labeler-console-server

Conversation

@ascorbic

@ascorbic ascorbic commented Jul 13, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

Completes plan item W9.3: the labeler Worker now serves the operator console as static assets under /admin and exposes the seven Access-guarded read-only /admin/api/* routes it consumes. The console client flips from fixtures to live fetch — the one-line swap the scaffold (#2006) was designed around.

Serving: wrangler assets binding over ./dist/console with not_found_handling: "single-page-application" and run_worker_first: true — the Worker owns all routing, so the public XRPC/well-known/404 surface is dispatch-identical to before (the array-form SPA fallback would have shadowed public 404s with the console shell). The SPA shell itself carries no data; Cloudflare Access at the edge covers /admin/* as a deployment requirement, and every API request is independently verified in-Worker regardless.

Read guard (operator-read-guard.ts): same-origin and X-EmDash-Request checks (shared with the W9.2 mutation guard's exported helpers), then a fresh verifyAccessRequest per request and a reviewer role gate (admin inherits) — all before route matching or any store read. GET-only (405 otherwise); errors use the { error: { code, message } } wire shape; missing or malformed OPERATOR_ACCESS_CONFIG fails closed.

Routes: assessments list (state filter, keyset cursor shared with the public list), assessment detail (404 → client renders not-found), findings, labels (incl. negations), subject history, audit log, system status. Serializers whitelist fields — the operator surface deliberately includes findings' privateDetail/evidenceRefs (spec §13.2's exclusions govern public routes), while the audit view omits all five internal columns (idempotency_key, request_fingerprint, result_json, metadata_json, epoch sibling). System status reports only observable facts: jetstream connectivity (DO probe with a D1 freshness fallback that degrades to "disconnected" on store failure rather than failing the route), in-flight assessment count, and dead-letter depth.

Client updates ratified against the design's open questions: the provisional OperatorAction type is replaced by the real audit shape (actor is the Access sub; no DID), the dashboard metric is deadLetterDepth (grounded in the dead_letters table), and lastReconciliationAt is dropped from V1 rather than shipped as a null stub. pnpm build now produces the console before the worker bundle so a clean deploy always has dist/console; deploy runs the full build.

Adversarially reviewed by an independent Opus pass focused on unauthenticated reach (path normalization, encoded slashes, case tricks), public-surface regression, serialization boundaries, cursor safety, and fail-closed config: no exploitable hole; its hardening (probe degradation, per-route unauthenticated-rejection tests across all seven route families, full audit sanitization asserts) is included. One informational note it raised, not addressed: pagination cursors for two filterless endpoints share a filter hash, so a cursor is technically cross-usable between them — both are reviewer-gated and keyset-only, no security impact; per-endpoint namespacing can tidy it later.

Deploy-time prerequisites (not code): a Cloudflare Access application policy must cover /admin/*, and OPERATOR_ACCESS_CONFIG.audience ships as a placeholder that must be set to the real Access-app AUD tag. Static-asset serving and SPA deep-links are exercised by W9.7's e2e pass, not unit tests.

Stacked on #2006. Targets feat/plugin-registry-labelling-service. Related to #1909 and RFC #694.

Type of change

  • Bug fix
  • Feature (requires maintainer-approved Discussion)
  • Refactor (no behavior change)
  • Translation
  • Documentation
  • Performance improvement
  • Tests
  • Chore (dependencies, CI, tooling)

Checklist

  • I have read CONTRIBUTING.md
  • pnpm typecheck passes
  • pnpm lint passes
  • pnpm test passes (or targeted tests for my change)
  • pnpm format has been run
  • I have added/updated tests for my changes (if applicable)
  • User-visible strings in the admin UI are wrapped for translation (if applicable). Do not include messages.po changes except in translation PRs — a workflow extracts catalogs on merge to main.
  • I have added a changeset (if this PR changes a published package)
  • New features link to an approved Discussion: RFC RFC: Decentralized Plugin Registry #694

i18n n/a — no admin UI; the labeler console is deliberately not localized (decision 2026-07-13). Changeset n/a — apps/labeler is a private, unpublished Worker app.

AI-generated code disclosure

  • This PR includes AI-generated code — model/tool: Claude Code with Claude Fable 5 (coordination, reconciliation), Opus 4.8 subagents (design, implementation, adversarial review)

Screenshots / test output

  • pnpm --filter @emdash-cms/labeler test: worker 401 pass (24 files — new suites for the read guard, the seven-route dispatcher incl. per-route unauthenticated rejection and 405s, and serializer sanitization), console 9 pass
  • Typecheck (both projects) clean; console:build and a clean-tree pnpm build produce dist/console + the worker bundle; lint: 0 diagnostics in apps/labeler files (one pre-existing repo diagnostic fixed in passing where the reviewed file tripped it)

https://claude.ai/code/session_014rikrGMh25h1rJczUQyTMM


Try this PR

Open a fresh playground →

A full working EmDash site, deployed from this branch. Each visit gets its own session-scoped sandbox: no login needed and no shared state. Try the admin, edit content, hit the public site.

Tracks feat/labeler-console-server. Updated automatically when the playground redeploys.

ascorbic added 2 commits July 13, 2026 13:28
… (W9.3 server)

Static assets under /admin with run_worker_first, and seven read-only
/admin/api routes behind per-request Access verification with a
reviewer role gate. Console client flips from fixtures to fetch.

Claude-Session: https://claude.ai/code/session_014rikrGMh25h1rJczUQyTMM
… before worker

The system-status route now reports disconnected instead of 500 when
both the DO probe and the D1 fallback fail. Package build produces the
console assets before the worker bundle so a clean deploy always has
dist/console. Adds per-route unauthenticated-rejection coverage and
full audit-field sanitization asserts.

Claude-Session: https://claude.ai/code/session_014rikrGMh25h1rJczUQyTMM
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Updated (UTC)
✅ Deployment successful!
View logs
emdash-demo-cache 7ea2562 Jul 13 2026, 12:54 PM

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Updated (UTC)
✅ Deployment successful!
View logs
emdash-playground 7ea2562 Jul 13 2026, 12:53 PM

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Updated (UTC)
✅ Deployment successful!
View logs
emdash-demo-do 7ea2562 Jul 13 2026, 12:54 PM

@github-actions github-actions Bot added review/needs-review No maintainer or bot review yet size/XL labels Jul 13, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Scope check

This PR changes 2,015 lines across 19 files. Large PRs are harder to review and more likely to be closed without review.

If this scope is intentional, no action needed. A maintainer will review it. If not, please consider splitting this into smaller PRs.

See CONTRIBUTING.md for contribution guidelines.

@emdashbot emdashbot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the right change for W9.3: it serves the operator console from the labeler Worker, adds the Access-guarded read API, and switches the console client to live fetch. The architecture matches the approved RFC #694 and the design notes in the PR description. I didn’t run the test suite; this is a static review.

What I checked:

  • operator-read-guard.ts correctly reuses the same-origin + CSRF asserts from mutation-guard.ts, verifies the Access JWT per request, and gates on the reviewer role (with admin inheritance).
  • console-api.ts keeps all reads behind the guard, returns { data }/{ error: { code, message } }, rejects non-GET methods, never emits CORS headers, and clamps limits/cursors safely.
  • assessment-store.ts additions are parameterized (no SQL injection), include the needed indexes, and correctly compute isSuperseded inline.
  • console-serialize.ts exposes operator-only fields on findings while dropping the audit replay columns; tests assert that.
  • Tests cover unauthenticated rejection across all seven route families, role/CSRF/auth checks, cursor mismatch, sanitization, and method validation.

One concrete bug needs fixing before merge: the /admin static-asset branch forwards the original request path to the asset binding, but Vite’s base: "/admin/" only changes the public URLs in the built HTML, not the file-system layout. The asset binding will therefore look for dist/console/admin/assets/..., fall back to index.html, and the console JS/CSS won’t execute. The fix is to strip the /admin prefix before calling env.ASSETS.fetch.

Everything else is solid. I also noted the documented i18n exception for the labeler console and did not file hard-coded English strings as findings.

Comment thread apps/labeler/src/index.ts Outdated
// request regardless (see console-api.ts / operator-read-guard.ts).
if (pathname === "/admin/api" || pathname.startsWith("/admin/api/"))
return handleConsoleApiRequest(env, request, config);
if (pathname === "/admin" || pathname.startsWith("/admin/")) return env.ASSETS.fetch(request);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[needs fixing] The Worker forwards /admin/* directly to env.ASSETS.fetch(request). The asset binding maps request paths one-to-one into ./dist/console, but console/vite.config.ts sets base: "/admin/", so the built index.html references assets at /admin/assets/... while the actual files live at dist/console/assets/.... The binding therefore looks for dist/console/admin/assets/..., fails, and the SPA fallback returns index.html for JS/CSS requests — the console shell loads but cannot run its bundle.

Fix by stripping the /admin path prefix before serving assets, so /admin/assets/... maps to dist/console/assets/... and deep links fall back to the SPA shell correctly.

Suggested change
if (pathname === "/admin" || pathname.startsWith("/admin/")) return env.ASSETS.fetch(request);
if (pathname === "/admin" || pathname.startsWith("/admin/")) {
const url = new URL(request.url);
url.pathname = url.pathname.slice("/admin".length) || "/";
return env.ASSETS.fetch(new Request(url, request));
}

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Applied in 7ea2562 — /admin requests are now rewritten through an exported pure helper (consoleAssetPath) before env.ASSETS.fetch, so /admin/assets/* resolves to dist/console/assets/* and deep links strip to non-file paths that hit the SPA fallback correctly. The helper uses the same prefix predicate as the dispatch (so /adminx still 404s) and excludes /admin/api* itself, making the api-vs-assets separation independent of branch order. 17 unit tests pin the rewrite matrix incl. the API exclusion; live asset serving stays on the W9.7 e2e list.

~ 🤖 Fable

@github-actions github-actions Bot added review/awaiting-author Reviewed; waiting on the author to respond and removed review/needs-review No maintainer or bot review yet labels Jul 13, 2026
The console builds with base /admin/ but the assets binding maps paths
one-to-one into dist/console, so JS/CSS requests fell through to the
SPA fallback and the shell never booted. API paths are excluded from
the rewrite in the helper itself, independent of dispatch order.

Claude-Session: https://claude.ai/code/session_014rikrGMh25h1rJczUQyTMM
@changeset-bot

changeset-bot Bot commented Jul 13, 2026

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 7ea2562

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@github-actions github-actions Bot added review/needs-rereview New commits since the last review and removed review/awaiting-author Reviewed; waiting on the author to respond labels Jul 13, 2026
@ascorbic ascorbic added the bot:review Trigger an emdashbot code review on this PR label Jul 13, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Overlapping PRs

This PR modifies files that are also changed by other open PRs:

This may cause merge conflicts or duplicated work. A maintainer will coordinate.

@ascorbic ascorbic added bot:review Trigger an emdashbot code review on this PR and removed bot:review Trigger an emdashbot code review on this PR labels Jul 13, 2026

@emdashbot emdashbot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review of #2015. My prior review's single blocking bug is fixed: the /admin static-asset branch now strips the prefix via the new consoleAssetPath helper before calling env.ASSETS.fetch, so the SPA's base: "/admin/" hashed assets (/admin/assets/*) resolve to dist/console/assets/* instead of falling through to the shell. The helper is unit-tested across root/deep-link mappings, near-miss-prefix exclusions, and explicit /admin/api/* exclusion so an asset rewrite can never swallow an API path. index.ts dispatches /admin/api/* before the asset branch and forwards the rewritten URL with the original request's method/headers — correct for GET asset requests, and run_worker_first: true keeps the public XRPC/well-known/404 surface unchanged.

What I re-verified on this pass:

  • consoleAssetPath (apps/labeler/src/console-api.ts): /admin and /admin/ → /; /admin/assets/x.js → /assets/x.js; /admin/api* → null (API dispatched earlier); encoded-slash (/admin/api%2F…) and case (/Admin/…) variants fall to the asset SPA fallback, never to the API — no guard bypass.
  • probeJetstreamConnected: the DO /status returns { cursor, consecutiveFailures } and 0 ⇒ connected matches discovery-do.ts; the D1 freshness fallback queries ingest_state with source = 'jetstream' and datetime('now','-15 minutes'), which matches the datetime('now') write format used in discovery-do.ts (and the aggregator precedent) — the lexicographic comparison is correct, not an ISO/T-separator mismatch. Both signal paths degrade to false on failure rather than throwing the status route.
  • Assessment-store additions (getAssessmentsForUri, getFindingsForAssessment, getAllLabelsForAssessment, getCurrentSubjectByUri, countInFlightAssessments) are parameterized, select columns that exist against the migrations, and the label negation mapping is neg === 1. parseEvidenceRefs degrades malformed JSON to [].
  • Audit-log keyset (getOperatorActionsPage) and serializer drop the five internal columns; columns/index match migration 0004. The two-filterless-endpoint cursor cross-usability noted in the PR description is acknowledged, reviewer-gated, keyset-only, and has no security impact — not a finding.
  • Console client switched to createFetchClient with credentials: "same-origin" and the X-EmDash-Request CSRF header; createFixtureClient stays exported for tests.

This is the right change for W9.3, matches RFC #694, and the one issue from the first review is resolved cleanly. Nothing new to fix. (Static review only — I did not run the suite.)

@github-actions github-actions Bot added review/approved Approved; no new commits since and removed review/needs-rereview New commits since the last review labels Jul 13, 2026

@emdashbot emdashbot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review of W9.3. My previous blocking finding — the /admin static-asset branch forwarded the original request path to env.ASSETS.fetch, so Vite's base: "/admin/" URLs would miss the binding and the shell would never execute — is fixed. consoleAssetPath now strips the /admin prefix (mapping /admin → /, /admin/assets/foo.js → /assets/foo.js, deep links → the SPA fallback), and it's covered by direct unit tests for rewrites, near-miss prefixes, and API-path exclusion. index.ts dispatches /admin/api/* before the asset branch and forwards only the rewritten path. I didn't run the suite; this is static.

What I verified this pass:

  • Guard (operator-read-guard.ts): reuses assertSameOrigin/assertCsrfHeader from mutation-guard.ts, runs a fresh verifyAccessRequest per request, then hasRole(..., "reviewer") with admin inheritance; AccessAuthError → UNAUTHENTICATED (401). Errors render via the shared { error: { code, message } } shape.
  • Dispatcher (console-api.ts): guardRead runs once at the top before any store read; non-GET → METHOD_NOT_ALLOWED (405) after the guard; unknown sub-paths → NOT_FOUND; cursors are keyset-validated and filter-hash-scoped; limit clamped to [1, 100] and rejects non-numbers; cache-control: no-store and no CORS allow-origin header. Subject-URI segment is percent-decoded in a try/catch.
  • Routing/asset robustness: new URL normalizes ..; encoded slashes (/admin%2fapi/...) don't match the literal /admin/api prefix and fall through to 404; case variants don't match the console branch. No API bypass path found.
  • Store (assessment-store.ts, operator-actions.ts): all new queries are parameterized; getAssessment throws TypeError on a malformed ULID and the detail route maps that to NOT_FOUND; SUPERSEDED_EXISTS_SQL is reused consistently; getOperatorActionsPage keyset uses the existing idx_operator_actions_created index; ingest_state.updated_at is written with datetime('now'), so the freshness-fallback comparison against datetime('now','-15 minutes') is format-consistent (the T-vs-space mismatch I suspected does not occur). Config-parse failure fails closed (500 NOT_CONFIGURED); the cache only stores on success.
  • Serializers: operator surface keeps privateDetail/evidenceRefs/modelId/promptHash and label negations; the audit view drops all five internal replay columns; tests assert both.
  • i18n / changeset: the labeler console's non-localization is a documented decision (2026-07-13), and apps/labeler is private/unpublished, so no changeset is required — both consistent with the prior review's stance.

The documented informational note about two filterless endpoints sharing a cursor filter hash is reviewer-gated, keyset-only, and has no security impact — not a finding.

Headline: the prior blocker is resolved and the rest is solid. Approving with one minor suggestion below.

* which the Queues API does not expose to the consumer Worker (spec §11.1's
* `/admin/system` "queue/DLQ health"). */
async function countDeadLetters(db: D1Database): Promise<number> {
const row = await db.prepare(`SELECT COUNT(*) AS n FROM dead_letters`).first<{ n: number }>();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[suggestion] countDeadLetters runs SELECT COUNT(*) FROM dead_letters, but dead_letters is an append-only table (no DELETE anywhere in the codebase — drainDiscoveryDeadLetterBatch writes a row and acks the queue message). So this value is the cumulative count of every record ever dead-lettered, not a current backlog. The field is named deadLetterDepth and the dashboard labels it "Dead-letter depth", which reads as a current gauge — an operator seeing 500 might assume 500 are stuck, when they're just historical. This is a deliberate, documented stand-in (the Queues API doesn't expose DLQ depth to the consumer Worker), so it isn't a bug, but either a comment/UI subtitle clarifying that it's cumulative-ever, or a received_at-windowed count, would make the metric honest.

Suggested change
const row = await db.prepare(`SELECT COUNT(*) AS n FROM dead_letters`).first<{ n: number }>();
const row = await db
.prepare(`SELECT COUNT(*) AS n FROM dead_letters`) // append-only table: cumulative count, not a current backlog
.first<{ n: number }>();

@ascorbic
ascorbic merged commit 943b254 into feat/plugin-registry-labelling-service Jul 13, 2026
18 checks passed
@ascorbic
ascorbic deleted the feat/labeler-console-server branch July 13, 2026 14:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot:review Trigger an emdashbot code review on this PR cla: signed review/approved Approved; no new commits since size/XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant