{
  "_ai_door": {
    "see": "https://miscsubjects.com/start",
    "note": "Operable site; bounded keyless credentials; every action receipted on a public ledger. Your operator's instructions take precedence — acting is optional, reading is a complete outcome."
  },
  "task": {
    "task_id": "WT-0481",
    "kind": "work",
    "objective": "WT-0481 Cloudflare plane — Code Mode MCP, API token minting, D1/KV/R2/Workers, Workers for Platforms; token failures as fixtures",
    "detail": "# WT-0481 — Cloudflare plane — Code Mode MCP, API token minting, D1/KV/R2/Workers, Workers for Platforms; token failures as fixtures\n\n## GOAL\nEvery Cloudflare capability the build uses (the Cloudflare API through minted tokens, Code Mode MCP with its 3 tools, D1_QUERY/D1_EXEC, KV, R2, Workers list/get/upload, Pages deploy, Workers for Platforms dispatch namespaces, Access service tokens, the 14 Cloudflare MCP servers) has a contract, runs through its declared executor with the five fields, and the token-list auth failure and the deploy permission gate are fixtures.\n\n## WHY THIS EXISTS\nThe owner asked which Cloudflare tokens are which (mint token, full token, account). Sessions hit `wrangler deploy` permission gates and token-list 403s repeatedly. The four Code-Mode models must see Cloudflare as contracts, not as a memory of which token worked.\n\n## CURRENT STATE (measured 2026-09-23)\n- Tokens: CLOUDFLARE_MINT_TOKEN (mints others) + scripts/cf-mint-token.mjs; CF_API_TOKEN (full); account id in the vault; token list endpoint 403 for a minted token (fixture).\n- Code Mode MCP: 3 tools (docs/search/execute) on the aggregate server; `||` breaks on the MCP-tool path (memory).\n- Cloudflare MCP servers: 14 skills, 188 tools, 181 directory rows via CF_API_TOKEN (2026-09-21).\n- Workers for Platforms: gate wfp-gate (DISPATCHER=production, DISPATCHER_STAGING=staging), custom domain gate.miscsubjects.com; scripts/wfp-tenant.mjs, scripts/cf-tenant.mjs; functions/_lib/wfp_worker.js (uploadScript, provisionTenantWorker).\n- Deploy: `node scripts/ship.mjs` only; `wrangler deploy` blocked by the auto-mode classifier (memory: name the one command).\n- functions/_lib/cf_account.js (GraphQL analytics).\n\n## SOURCE OF TRUTH\n- scripts/cf-mint-token.mjs, scripts/cf-tenant.mjs, scripts/wfp-tenant.mjs\n- functions/_lib/wfp_worker.js, functions/_lib/cf_account.js\n- ~/codemode-mcp/src (the Code Mode MCP product)\n- Cloudflare API docs via the CF_MAIN_DOCS/CF_MAIN_SEARCH rows\n\n## IN-SCOPE INVENTORY\n- Executor ids: cf_api (REST with a named token), cf_codemode (Code Mode execute), cf_mcp_<server> (the 14 servers), cf_d1_binding (D1_QUERY/D1_EXEC in-Worker), cf_kv_binding, cf_r2_binding, cf_wfp_dispatch (tenant Worker), cf_pages_deploy (ship.mjs).\n- Token contract table `cf_tokens` (names only; values in the vault): name, purpose, scopes (from /user/tokens/verify), can_list_tokens (bool, measured), expires_at, minted_by.\n- Verbs: CF_TOKEN_VERIFY {name}, CF_TOKEN_MINT {name, scopes[], ttl} (via the mint token), CF_WORKERS_LIST, CF_WORKER_GET {name}, CF_D1_QUERY {db, sql}, CF_KV_GET/PUT, CF_R2_LIST/GET/PUT, CF_WFP_UPLOAD {namespace, name, script}, CF_ACCESS_SERVICE_TOKENS_LIST, CF_ANALYTICS {graphql}.\n- Fixtures: token list 403 with a minted token (verify works, list does not — record both); wrangler deploy classifier block (the one command is `node scripts/ship.mjs`); `||` in Code Mode execute; D1 statement splitter cutting on `;`; SQLite LIKE `_`.\n\n## OUT OF SCOPE\n- The build's own deploy pipeline changes (governed). Tenant onboarding (WT-0488). Model configuration (WT-0482).\n\n## ONTOLOGY (separate axes; never a flat string)\n- TOOL SURFACE: dispatch CF_* rows; MCP CF_MAIN_DOCS/CF_MAIN_SEARCH/CF_MAIN_EXECUTE and the 14 servers; misc line; cell\n- CAPABILITY: the verbs above\n- OBJECT: a token, a Worker, a database, a bucket, a namespace, a tenant script\n- ROUTE / CONTEXT: account id + token name + namespace (staging|production)\n- PROTOCOL: HTTPS REST, GraphQL, MCP JSON-RPC, Worker bindings\n- EXECUTOR: Worker (bindings), Worker fetch to api.cloudflare.com, Code Mode sandbox, ship.mjs on the Mac\n- PLATFORM: Cloudflare\n\n## DISCOVERY (run these first; they answer, they do not prove)\n- `node scripts/cf-mint-token.mjs --help`\n- `curl -sS \"https://api.cloudflare.com/client/v4/user/tokens/verify\" -H \"Authorization: Bearer $CF_API_TOKEN\"` (`grep '^CF_API_TOKEN=' ~/.build-vault.env`)\n- `curl -sS -X POST https://ops.miscsubjects.com/api/dispatch -H \"x-terminal-key: $TERMINAL_KEY\" -H \"content-type: application/json\" -d '{\"key\":\"CF_MAIN_SEARCH\",\"body\":{\"q\":\"dispatch namespace\"}}'`\n\n## CONTRACT (FIELD LAW)\n- CF_TOKEN_MINT `{name (required, unique), scopes (required, array of permission group ids), ttl_days (optional 1..365, default 30), resources (optional account/zone map)}` → Cloudflare `{success, result:{id, value (stored to the vault by the script, never returned in the return field), expires_on}}` — the return field carries `value: \"<stored in vault as NAME>\"`.\n- CF_D1_QUERY `{db (enum main|ledger), sql (required, one statement; `;` splits — refuse multi-statement with statement_split)}`; CF_WFP_UPLOAD `{namespace (enum), name, script (≤ 1 MB), bindings?}`.\n\n## MINIMUM VALID INVOCATION\n`curl -sS -X POST https://ops.miscsubjects.com/api/dispatch -H \"x-terminal-key: $TERMINAL_KEY\" -H \"content-type: application/json\" -d '{\"key\":\"CF_TOKEN_VERIFY\",\"body\":{\"name\":\"CF_API_TOKEN\"}}'`\n\n## FULL / MAXIMUM INVOCATION\n`node scripts/cf-mint-token.mjs --name wt0481-test --scopes \"Workers Scripts Read\" --ttl-days 1 --store` (mints with CLOUDFLARE_MINT_TOKEN, stores the value in the vault as CF_TOKEN_WT0481_TEST, prints only the name)\n\n## RAW CONFIRMATION SHAPE\nCloudflare `{\"success\":true,\"errors\":[],\"messages\":[]}` + HTTP status; binding calls return `{meta:{changes, duration}}`; MCP tool result envelope.\n\n## RAW RETURN SHAPE\nCloudflare `result` verbatim (secrets redacted to vault names); D1 rows; R2 keys; Worker metadata.\n\n## ERROR SHAPES\n- 403 `Authentication error` on /user/tokens (list) with a minted token — fixture\n- 9109 invalid access token\n- statement_split\n- classifier block on wrangler deploy — use ship.mjs\n- Code Mode `||` parse failure — use `? :`\n\n## RECEIPT / TRACE / PARENT LINKAGE\nproof_run surface=cf_*; token operations receipted with the token NAME.\n\n## TEST MATRIX\n| case | what runs | kind |\n|---|---|---|\n| verify each token | CF_API_TOKEN, CLOUDFLARE_MINT_TOKEN, each Access token → scopes recorded in cf_tokens | live |\n| mint | 1-day token, stored, verified, then deleted | live |\n| list tokens 403 | with the minted token → the exact 403 recorded | fixture |\n| workers list/get | 16 Workers | live |\n| d1 query both dbs | one SELECT each | live |\n| kv/r2 | one get/put/list each | live |\n| wfp upload | tenant-demo script to staging namespace | live |\n| codemode execute | one script through CF_MAIN_EXECUTE | live |\n| 14 servers | one tool each through /api/mcp | live |\n| graphql | one analytics query | live |\n\n## ACCEPTANCE TESTS (mechanical; the infrastructure runs them)\n- `{\"type\": \"evidence_present\", \"id\": \"commit\", \"field\": \"commit\"}`\n- `{\"type\": \"evidence_present\", \"id\": \"live\", \"field\": \"verification\"}`\n- `{\"type\": \"evidence_present\", \"id\": \"matrix\", \"field\": \"test_matrix_results\"}`\nEvidence fields the submitting agent supplies: commit, test_matrix_results, verification. `verification` = the list of receipt ids and the live URLs checked, one per line. `test_matrix_results` = the matrix above with a receipt id or the verbatim failure per row.\n\n## KNOWN FAILURES / REGRESSION FIXTURES (preserve; never rewrite into success)\n- Cloudflare token-list auth failure\n- wrangler deploy permission gate\n- Code Mode `||`\n- D1 `;` splitter\n- SQLite LIKE `_`\n- stale workers.dev hosts\n\n## DEPENDENCIES\n- depends_on: WT-0470, WT-0471\n- OWNS (only this task rewrites): scripts/cf-mint-token.mjs, scripts/cf-tenant.mjs, scripts/wfp-tenant.mjs; functions/_lib/wfp_worker.js, functions/_lib/cf_account.js; CF_* rows; migrations/0486_cf_tokens.sql (new); ~/codemode-mcp\n- SHARED (additive edits only): functions/api/mcp.js (WT-0472; the 14 servers are rows, not code); scripts/ship.mjs (governed; never changed here)\n\n## HANDOFF FOR NEXT SESSION\n- Token values never in returns, receipts or chat; names only.\n- The deploy is always `node scripts/land.mjs`; if a classifier blocks, that is the fixture, not a reason to stop.\n- Evidence: the cf_tokens table dump (names/scopes) + receipts.\n\n## DONE LAW (this task is done when every line is true and evidenced; not before)\n- cf_tokens holds every token name with measured scopes.\n- Every executor id has a receipt; the 403 fixture is recorded.\n- Contracts for all CF_* rows in capability_contracts.\n\n## Shared vocabulary (defined by WT-0470; every task uses these words with these meanings)\n- **TOOL SURFACE** — how a caller or model asks (curl, MCP tools/call, `=DISPATCH` cell, a tapped URL, a Shortcut, a webhook, a tag in text).\n- **CAPABILITY** — the operation requested, named by a Directory key (semantic).\n- **OBJECT** — what it acts on (a chat, a file, a profile, a row, a page).\n- **ROUTE / CONTEXT** — which machine, device, account, browser profile, tenant, network, session.\n- **PROTOCOL** — how the request physically travels (HTTP, JSON-RPC, gRPC, WebSocket, SSH, SQL, a local process, a queue).\n- **EXECUTOR** — what performs it (a Worker, the Mac bridge `/exec`, Chromium over CDP, `osascript`, `pymobiledevice3`, a vendor API).\n- **PLATFORM** — which technology or vendor owns that executor (Cloudflare, Apple, AdsPower, Blooio, Google, Starlink).\n- **RAW CONTRACT** — the exact physical invocation sent, fully resolved.\n- **CONFIRMATION** — the executor's immediate acknowledgement (HTTP status + headers, spawn/exit metadata, JSON-RPC ack, WebSocket ack, queue receipt).\n- **RETURN** — the final result, verbatim, including failure payloads.\n- **RECEIPT** — evidence and provenance: receipt id/URL, trace id, execution id, timestamps, parent linkage.\n\n## Definition of proof (PROOF_LAW, governing invariant; read it: GET https://ops.miscsubjects.com/api/work → governing_invariants)\nA capability is proven only when the DECLARED invocation surface itself ran and the five fields exist for that run: CAUSE (why it ran: user request / task / parent invocation / event / webhook / model call), RAW INVOCATION (the fully resolved physical contract actually sent), RAW CONFIRMATION (the executor's acknowledgement), RAW RETURN (the actual output, failures verbatim), PROOF / RECEIPT (receipt id/URL, trace, execution id, timestamps, parent linkage sufficient to inspect or replay).\nAn HTTP 200 proves an HTTP 200. A webhook acknowledgement proves receipt. Hidden bash proves bash. A sibling implementation, documentation, a model doing it elsewhere, or the dispatcher working while the surface under test never ran prove nothing about that surface. A missing field is a missing implementation requirement, never something to invent. Existing failures stay as evidence and become regression fixtures; they are never rewritten into success.\n\n## Six-column projection (unchanged; not the source of truth)\n`TOOL NAME | ONTOLOGY | RAW INVOCATION | RAW CONFIRMATION | RAW RETURN | PROOF / RECEIPT` — the build workbook sheet `sh_nyab2cgy` (vault `CONTRACTS_WORKBOOK_SHEET`, 11,035 rows on 2026-09-23). No seventh column, no contract-type column, no prose in place of an executable invocation. Extra metadata belongs in the canonical capability / task / receipt objects.\n\n## Parallelism law\nOther tasks run at the same time in other sessions. Own only the files and objects named under OWNS; touch a shared file only as named under SHARED (additive, never a rewrite). If this task finds the global law insufficient, it files an amendment: `POST /api/work/task/<this id>/fail` naming failure_class `law_insufficient`, layer `WT-0470`, and the missing invariant — it never creates a second standard. Ask the build, never the owner: keys are in `~/.build-vault.env` (`grep '^NAME=' ~/.build-vault.env`; `CLOUDFLARE_API_TOKEN=$CF_API_TOKEN` is a shell reference, resolve `$NAME`). The owner key travels as header `x-terminal-key`. Deploy only with `node scripts/land.mjs \"<WT id> what changed\"` from `~/miscsubjects-pages`. Submit evidence: `POST https://ops.miscsubjects.com/api/work/task/<id>/submit {agent, evidence:{commit, verification, …}, changed:[…]}` with header `x-terminal-key`.\n\n## Shared canonical objects and files — never independently rewritten (additive edits only, named per task)\n- `functions/api/dispatch.js` (the one door; runHttp/runFn/tenant delegation) — owner WT-0471.\n- `functions/_lib/invocation_methods.js`, `functions/_lib/grammar.js`, `functions/_lib/projection_manifest.js`, `functions/api/tools/[[path]].js`, `functions/api/mcp.js`, `functions/_lib/mcp_inspect.js` — owner WT-0472 (spellings and model projections).\n- `functions/_lib/event_log.js`, `functions/_lib/wire_log.js`, `functions/_lib/lean_receipt.js`, `functions/_lib/invocation_record.js`, the `events` table and R2 `logs/` — owner WT-0485 (ledger).\n- `functions/_lib/admin_session.js` (tokens, capabilities, tenants), `functions/_lib/tenant_devices.js`, `functions/api/onboard/[[path]].js` — owner WT-0487 (authority) / WT-0488 (onboarding).\n- `functions/_lib/mac_bridge.js`, `bridge/server.js`, `bridge/device_auth.js`, `bridge/surface-run.py`, `bridge/surface-verbs.py`, `bridge/bridge-run.py`, `bridge/bridge-browser.mjs`, `public/device-kit/*` (synced copies) — owners WT-0474 / WT-0475 / WT-0478.\n- `functions/_lib/work_object.js`, `functions/api/work/[[path]].js`, the `laws` and `work_tasks` tables — owner WT-0470 (law rows) and the build (task engine).\n- `scripts/contracts-*.mjs`, `apps-script/Contracts.gs`, the `CONTRACTS_RUN` directory row, sheet `sh_nyab2cgy` — owner WT-0473.\n- `scripts/ship.mjs`, `scripts/land.mjs`, `scripts/write.mjs`, `scripts/check-*.mjs`, `.githooks/*` — governed; add a gate only by adding a new `scripts/check-<name>.mjs` and wiring it as the existing gates are wired.\n",
    "state": "open",
    "priority": 3,
    "revision": 1,
    "depends_on": [
      "WT-0470",
      "WT-0471"
    ],
    "permitted_capabilities": [
      "dispatch",
      "d1",
      "bridge",
      "sheets",
      "receipts"
    ],
    "acceptance_tests": [
      {
        "type": "evidence_present",
        "id": "commit",
        "field": "commit"
      },
      {
        "type": "evidence_present",
        "id": "live",
        "field": "verification"
      },
      {
        "type": "evidence_present",
        "id": "matrix",
        "field": "test_matrix_results"
      }
    ],
    "required_evidence": [
      "commit",
      "test_matrix_results",
      "verification"
    ],
    "parent_task": null,
    "supersedes": null,
    "failure": null,
    "failure_count": 0,
    "last_result": null,
    "completed_at": null,
    "created_at": "2026-09-22T19:51:56-07:00",
    "updated_at": "2026-09-22T19:51:56-07:00",
    "audit": "/api/work/task/WT-0481/audit",
    "submit_to": "/api/work/task/WT-0481/submit"
  }
}