AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.
Rust agent-memoryai-agentsbm25claude-codeclicode-searchcursordatabaseelasticsearchfull-text-searchhybrid-searchjsonllocal-firstmcpmcp-servermodel-context-protocolragrustsearch-enginevector-search
feat(functions): store /api/field-report in R2, not KV; wire the binding and go live
xerj-orgb53154849303
diff --git a/functions/api/field-report.js b/functions/api/field-report.jsindex d1ea73847..d0dd5827c 100644--- a/functions/api/field-report.js+++ b/functions/api/field-report.js@@ -6,265 +6,145 @@// xerj feedback --open-pr → user-feedback/16-agent-field-reports/// That path STAYS primary. This endpoint exists ONLY for the agent persona// that cannot reach it: no shell, no git, no `gh`, no GitHub identity (e.g. a-// sandboxed Claude Code). It was proposed in-// docs/research/llms-txt-2026-09/ (POST https://xerj.org/api/field-report)-// and is the "GitHub-unavailable fallback", nothing more. Every success-// response points the caller back at the GitHub tree.+// sandboxed Claude Code). Proposed in docs/research/llms-txt-2026-09/ as the+// "GitHub-unavailable fallback". Every success response points back at GitHub.//// ─────────────────────────────── CONTRACT ───────────────────────────────-// POST https://xerj.org/api/field-report-// Content-Type: application/json-// Body (all values are short strings):-// { "agent": "...", "used_for": "...", "verdict": "...", // required-// "version": "...", "os": "...", "indexed": "...", // optional-// "notes": "..." } // optional-// 200 { ok:true, stored:true, note:"...GitHub PR is canonical..." }+// POST https://xerj.org/api/field-report (Content-Type: application/json)+// Body (short strings): { agent, used_for, verdict, // required+// version?, os?, indexed?, notes? }+// 200 { ok:true, stored:true, note:"…GitHub PR is canonical…" }+// Not POST → 405 · not JSON → 415 · >16 KB → 413 · bad/missing field → 400+// Same IP within 60s → 429 · daily safety cap reached → 503//-// Method other than POST/OPTIONS .......... 405-// Content-Type not application/json ....... 415-// Body larger than ~16 KB ................. 413-// Malformed JSON / missing required field . 400-// Same IP again within 60s ................ 429 (rate limit)-// Daily safety cap reached ................ 503 (use the GitHub PR path)-//-// ────────────────────────── FREE-TIER / ANTI-SPAM ───────────────────────-// Storage is Workers KV (binding FIELD_REPORTS), never R2 (R2 is frozen by-// owner order). KV free tier = 1000 writes/day, 100k reads/day, 1 GB. Two-// guards keep us inside it and stop spam from causing a bill:-// 1. RATE LIMIT — at most 1 accepted report per IP per minute-// (key `rl:<ip>`, 60s TTL). A second request inside 60s → 429.-// 2. DAILY CAP — an accepted-report counter `cnt:<YYYY-MM-DD>` (2-day TTL).-// When it reaches DAILY_CAP we DROP new reports with 503 and tell the-// caller to use the GitHub PR path. This is the deliberate "drop new-// reports if going over, to prevent overages by spam" rule.-// Each ACCEPTED report costs exactly 3 KV writes: the rate-limit marker, the-// report itself, and the counter bump. DAILY_CAP is sized so 3×cap stays-// well under the 1000 writes/day limit (see the constant below). Rejected-// requests (405/415/413/400/429/503) perform NO writes — at most two cheap-// reads — so a flood of junk cannot burn the write budget or the wallet.+// ─────────────────────── STORAGE: R2, free-tier-safe ────────────────────+// Stored in Cloudflare R2 (binding FIELD_REPORTS → bucket xerj-field-reports),+// the cheapest storage already granted to the Pages deploy token (the same+// account's Functions use R2 for LEADS/INSTALLS). R2 free tier = 10 GB,+// 1M Class-A ops/mo (writes/list), 10M Class-B ops/mo (reads). Two guards keep+// us far inside it and stop spam from causing a bill:+// 1. RATE LIMIT — ≤1 accepted report per IP per minute (object rl/<ipHash>,+// body = timestamp; a second request inside 60s → 429, a READ only).+// 2. DAILY CAP — accepted-report counter meta/count-<YYYY-MM-DD>; at+// DAILY_CAP we DROP new reports with 503 and point to the GitHub PR path.+// An accepted report costs 3 Class-A writes (rate marker + report + counter);+// DAILY_CAP×3 stays far under 1M/mo. Rejected requests do NO writes (at most+// two cheap reads), so a flood cannot burn the write budget or the wallet.+// R2 has no TTL; rl/ and meta/ objects are tiny — a bucket lifecycle rule+// (expire rl/ after 1 day) keeps them swept. Reports under reports/ are kept.//// ─────────────────────────────── PRIVACY ────────────────────────────────-// The raw IP is NEVER stored. We store sha-256(IP + salt) as `ip_hash` so-// reports from the same source can be grouped without retaining the address.-// No secrets are stored; untrusted input is length-capped, control-char-// stripped, and never echoed back as HTML.-//-// ─────────────────────────────── ROUTING ────────────────────────────────-// This file lives at functions/api/field-report.js, so Pages Functions serve-// it at /api/field-report (same file-path→URL convention by which-// functions/lead.js serves /lead). landing/_routes.json MUST list-// "/api/field-report" in its include array or the static asset handler-// shadows it and this function never runs.+// Raw IP is NEVER stored. ip_hash = sha-256(IP + salt). Untrusted input is+// length-capped, control-char stripped, never echoed back as HTML.-// ── Tunables ─────────────────────────────────────────────────────────────-// 300 accepted reports/day × 3 KV writes each (rate-limit marker + report +-// counter) = 900 writes/day, deliberately well under the 1000/day KV free-// tier so spam can never push the account into an overage. The owner's stated-// requirement ("well under the 1000/day KV write limit") binds over the-// example value; bump this only after confirming the KV write quota.-const DAILY_CAP = 300;-const RATE_LIMIT_TTL = 60; // seconds; one accepted report per IP per minute-const COUNTER_TTL = 172800; // 2 days; the daily counter self-expires-const MAX_BODY = 16 * 1024; // 16 KB hard cap on the request body+const DAILY_CAP = 300; // ×3 writes = 900/day, far under 1M/mo R2 free+const RATE_WINDOW_MS = 60_000; // one accepted report per IP per minute+const MAX_BODY = 16 * 1024; // 16 KB request-body cap-// Per-field length caps (all values must be short strings). Their sum is far-// below MAX_BODY, so an oversized body is rejected before we ever parse it.-const FIELD_CAPS = {- agent: 120,- used_for: 1000,- verdict: 80,- version: 80,- os: 120,- indexed: 200,- notes: 4000,-};-const REQUIRED = ['agent', 'used_for', 'verdict'];-const OPTIONAL = ['version', 'os', 'indexed', 'notes'];+const FIELD_CAPS = { agent:120, used_for:1000, verdict:80, version:80, os:120, indexed:200, notes:4000 };+const REQUIRED = ['agent','used_for','verdict'];+const OPTIONAL = ['version','os','indexed','notes'];const CANONICAL_NOTE ='Thanks. The canonical path is a GitHub PR: ' +'https://github.com/xerj-org/xerj/tree/main/user-feedback/16-agent-field-reports';-// Permissive CORS: agents call this cross-origin from arbitrary contexts.const CORS = {'access-control-allow-origin': '*','access-control-allow-methods': 'POST, OPTIONS','access-control-allow-headers': 'content-type','access-control-max-age': '86400',};-const JSON_HEADERS = { 'content-type': 'application/json', 'cache-control': 'no-store', ...CORS };+const JSON_HEADERS = { 'content-type':'application/json', 'cache-control':'no-store', ...CORS };+const json = (obj, status = 200) => new Response(JSON.stringify(obj), { status, headers: JSON_HEADERS });-function json(obj, status = 200) {- return new Response(JSON.stringify(obj), { status, headers: JSON_HEADERS });-}--// Strip control characters, collapse to a plain string, trim, and length-cap.-// Never returns HTML-significant content unescaped because we never render it;-// this only keeps stored values short and free of control bytes.function clean(value, cap) {- return String(value)- .replace(/[\u0000-\u001f\u007f]/g, ' ')- .trim()- .slice(0, cap);+ return String(value).replace(/[\u0000-\u001f\u007f]/g, ' ').trim().slice(0, cap);}-async function sha256hex(input) {- const data = new TextEncoder().encode(input);- const digest = await crypto.subtle.digest('SHA-256', data);+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(input));return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('');}-// Single entry point so we control every status code (including the 405) and-// attach CORS headers uniformly.export async function onRequest(context) {- const { request } = context;- const method = request.method.toUpperCase();-- if (method === 'OPTIONS') {- // CORS preflight — no body, just the allow headers.- return new Response(null, { status: 204, headers: CORS });- }- if (method !== 'POST') {- // Method guard: POST only.- return json({ ok: false, error: 'method not allowed; use POST' }, 405);- }+ const method = context.request.method.toUpperCase();+ if (method === 'OPTIONS') return new Response(null, { status: 204, headers: CORS });+ if (method !== 'POST') return json({ ok:false, error:'method not allowed; use POST' }, 405);return handlePost(context);}async function handlePost({ request, env }) {- // Content-Type guard.const ct = (request.headers.get('content-type') || '').toLowerCase();- if (!ct.includes('application/json')) {- return json({ ok: false, error: 'content-type must be application/json' }, 415);- }+ if (!ct.includes('application/json')) return json({ ok:false, error:'content-type must be application/json' }, 415);- // Body size cap — reject early on the declared length when present.const declared = parseInt(request.headers.get('content-length') || '0', 10);- if (Number.isFinite(declared) && declared > MAX_BODY) {- return json({ ok: false, error: 'body too large' }, 413);- }+ if (Number.isFinite(declared) && declared > MAX_BODY) return json({ ok:false, error:'body too large' }, 413);- // Read the raw body and enforce the cap again on the actual bytes (a lying- // or absent content-length cannot sneak past).let raw;- try {- raw = await request.text();- } catch (_) {- return json({ ok: false, error: 'could not read body' }, 400);- }- if (raw.length > MAX_BODY) {- return json({ ok: false, error: 'body too large' }, 413);- }+ try { raw = await request.text(); } catch (_) { return json({ ok:false, error:'could not read body' }, 400); }+ if (raw.length > MAX_BODY) return json({ ok:false, error:'body too large' }, 413);- // Parse JSON.let body;- try {- body = JSON.parse(raw);- } catch (_) {- return json({ ok: false, error: 'invalid JSON body' }, 400);- }- if (body === null || typeof body !== 'object' || Array.isArray(body)) {- return json({ ok: false, error: 'body must be a JSON object' }, 400);- }+ try { body = JSON.parse(raw); } catch (_) { return json({ ok:false, error:'invalid JSON body' }, 400); }+ if (body === null || typeof body !== 'object' || Array.isArray(body)) return json({ ok:false, error:'body must be a JSON object' }, 400);- // Validate + sanitise fields. Every field must be a short string; anything- // that is not a string is rejected rather than coerced.const report = {};for (const key of REQUIRED) {const v = body[key];- if (typeof v !== 'string' || clean(v, FIELD_CAPS[key]).length === 0) {- return json({ ok: false, error: `missing or invalid required field: ${key}` }, 400);- }+ if (typeof v !== 'string' || clean(v, FIELD_CAPS[key]).length === 0)+ return json({ ok:false, error:`missing or invalid required field: ${key}` }, 400);report[key] = clean(v, FIELD_CAPS[key]);}for (const key of OPTIONAL) {- if (body[key] === undefined || body[key] === null) {- report[key] = '';- continue;- }- if (typeof body[key] !== 'string') {- return json({ ok: false, error: `field must be a string: ${key}` }, 400);- }+ if (body[key] === undefined || body[key] === null) { report[key] = ''; continue; }+ if (typeof body[key] !== 'string') return json({ ok:false, error:`field must be a string: ${key}` }, 400);report[key] = clean(body[key], FIELD_CAPS[key]);}- // Without the KV binding we cannot rate-limit, count, or store. Degrade like- // functions/lead.js does when its bucket is absent: accept-but-do-not-store,- // no writes, and still hand back the canonical GitHub pointer. This is the- // state before the owner runs the one-time `wrangler kv namespace create`.- if (!env.FIELD_REPORTS) {- console.log('[field-report] no FIELD_REPORTS KV binding; not stored');- return json({ ok: true, stored: false, note: CANONICAL_NOTE });- }- const kv = env.FIELD_REPORTS;+ // Degrade like functions/lead.js when its bucket is absent: accept, do not+ // store, still return the canonical pointer. (State before the binding wires.)+ const bucket = env.FIELD_REPORTS;+ if (!bucket) { console.log('[field-report] no FIELD_REPORTS R2 binding; not stored'); return json({ ok:true, stored:false, note: CANONICAL_NOTE }); }const ip = request.headers.get('CF-Connecting-IP') || '';+ const ipHash = ip ? await sha256hex(ip + (env.FIELD_REPORT_SALT || 'xerj-field-report-v1')) : 'noip';- // ── Guard 1: rate limit (1 accepted report per IP per minute) ──────────- // A read; no write unless the request is ultimately accepted below.- const rlKey = `rl:${ip}`;+ // Guard 1: per-IP rate limit (read-only unless we accept below).+ const rlKey = `rl/${ipHash}`;try {- if (await kv.get(rlKey)) {- return json({ ok: false, error: 'rate limited: one report per minute per source' }, 429);+ const prev = await bucket.get(rlKey);+ if (prev) {+ const ts = parseInt(await prev.text(), 10) || 0;+ if (Date.now() - ts < RATE_WINDOW_MS) return json({ ok:false, error:'rate limited: one report per minute per source' }, 429);}- } catch (_) {- // Read failure: fail closed on the rate limiter is unfriendly; fail open- // but the daily cap below still bounds total writes.- }+ } catch (_) { /* fail open; the daily cap still bounds writes */ }- // ── Guard 2: daily safety cap (anti-overage) ───────────────────────────- // Approximate counter (KV has no atomic increment; the 1-per-minute rate- // limit makes races negligible, and the cap sits far below the write quota).- const today = new Date().toISOString().slice(0, 10); // YYYY-MM-DD- const cntKey = `cnt:${today}`;+ // Guard 2: daily safety cap (anti-overage).+ const today = new Date().toISOString().slice(0, 10);+ const cntKey = `meta/count-${today}`;let count = 0;- try {- count = parseInt((await kv.get(cntKey)) || '0', 10) || 0;- } catch (_) {- count = 0;- }- if (count >= DAILY_CAP) {- // Over the safety cap: DROP the report to prevent KV-write overages from- // spam, and tell the caller to use the canonical GitHub PR path instead.- return json(- {- ok: false,- error: 'daily capacity reached; please file via the GitHub PR path',- note: CANONICAL_NOTE,- },- 503- );- }+ try { const c = await bucket.get(cntKey); if (c) count = parseInt(await c.text(), 10) || 0; } catch (_) { count = 0; }+ if (count >= DAILY_CAP)+ return json({ ok:false, error:'daily capacity reached; please file via the GitHub PR path', note: CANONICAL_NOTE }, 503);- // ── Accept: 3 KV writes (rate-limit marker, report, counter bump) ──────+ // Accept: 3 R2 writes.const now = new Date();- const iso = now.toISOString();const rand = (crypto.randomUUID ? crypto.randomUUID() : `${Math.random()}`).slice(0, 8);- const key = `report:${today}T${now.getTime()}-${rand}`;-+ const key = `reports/${today}/${now.getTime()}-${rand}.json`;const stored = {- received_at: iso,- ip_hash: ip ? await sha256hex(ip + (env.FIELD_REPORT_SALT || 'xerj-field-report-v1')) : '',- agent: report.agent,- used_for: report.used_for,- verdict: report.verdict,- version: report.version,- os: report.os,- indexed: report.indexed,- notes: report.notes,+ received_at: now.toISOString(),+ ip_hash: ip ? ipHash : '',+ agent: report.agent, used_for: report.used_for, verdict: report.verdict,+ version: report.version, os: report.os, indexed: report.indexed, notes: report.notes,ua: clean(request.headers.get('user-agent') || '', 300),};-try {- // Reserve the per-IP minute slot first so a burst of concurrent valid- // requests from one IP cannot all slip through.- if (ip) await kv.put(rlKey, '1', { expirationTtl: RATE_LIMIT_TTL });- await kv.put(key, JSON.stringify(stored));- await kv.put(cntKey, String(count + 1), { expirationTtl: COUNTER_TTL });+ await bucket.put(rlKey, String(Date.now()));+ await bucket.put(key, JSON.stringify(stored), { httpMetadata: { contentType: 'application/json' } });+ await bucket.put(cntKey, String(count + 1));} catch (e) {- console.log('[field-report] KV write failed:', String(e));- return json({ ok: false, error: 'storage unavailable; please file via the GitHub PR path', note: CANONICAL_NOTE }, 503);+ console.log('[field-report] R2 write failed:', String(e));+ return json({ ok:false, error:'storage unavailable; please file via the GitHub PR path', note: CANONICAL_NOTE }, 503);}-- return json({ ok: true, stored: true, note: CANONICAL_NOTE });+ return json({ ok:true, stored:true, note: CANONICAL_NOTE });}diff --git a/wrangler.toml b/wrangler.tomlindex 874f0a282..88549091a 100644--- a/wrangler.toml+++ b/wrangler.toml@@ -8,18 +8,15 @@# Cloudflare dashboard (R2 → Create bucket → `xerj-installs`);# until it exists the function serves the installer normally and# simply does not count. Fail-open is deliberate.-# FIELD_REPORTS (Workers KV) — functions/api/field-report.js stores each-# accepted agent field report as a small JSON value. This is the-# GitHub-unavailable FALLBACK to `xerj feedback --open-pr`; the-# PR path stays primary. KV only — NEVER R2 (R2 is frozen by-# owner order). The namespace must be created ONCE and its id-# pasted below, replacing the placeholder; until then the-# function accepts requests but does not store (fail-open, like-# get.js). One-time setup (owner runs it; do NOT run against the-# live account from CI/agents):-# wrangler kv namespace create FIELD_REPORTS-# then copy the printed id into `id = "..."` under the-# [[kv_namespaces]] block below and redeploy.+# FIELD_REPORTS — functions/api/field-report.js stores each accepted agent+# field report as a small JSON object under reports/<date>/. This+# is the GitHub-unavailable FALLBACK to `xerj feedback --open-pr`;+# the PR path stays primary. R2 bucket `xerj-field-reports` (the+# cheapest storage already granted to the Pages token; the same+# account's LEADS/INSTALLS Functions use R2). A per-IP rate limit+# and a daily cap keep writes far inside the R2 free tier. Until+# the bucket exists the function accepts requests but does not+# store (fail-open, like get.js).## Routing: landing/_routes.json pins Function invocation to /get, /get.ps1,# /lead and /api/field-report. A NEW FUNCTION ADDED UNDER functions/ WILL NOT@@ -36,19 +33,11 @@ bucket_name = "xerj-leads"binding = "INSTALLS"bucket_name = "xerj-installs"-# Workers KV for agent field reports (functions/api/field-report.js).-# PLACEHOLDER id — NOT a real namespace. Create the namespace once with-# wrangler kv namespace create FIELD_REPORTS-# and replace the id below with the one it prints. Do not commit a real id-# from the live account via an automated run; the owner wires this at deploy.-# [[kv_namespaces]] — COMMENTED OUT until the owner wires the real namespace.-# A placeholder id here makes `wrangler pages deploy` fail with-# "Error 8000022: Invalid KV namespace ID", which blocks EVERY xerj.org deploy-# (this file is on the deploy trigger path). With no binding declared, the-# Function fails open: /api/field-report accepts a report and returns 200 but-# does NOT store it (see functions/api/field-report.js, the `!env.FIELD_REPORTS`-# branch). To activate storage, create the namespace and restore this block:-# wrangler kv namespace create FIELD_REPORTS # prints an id-# [[kv_namespaces]]-# binding = "FIELD_REPORTS"-# id = "<the id it printed>"+# Agent field reports filed via the HTTP fallback POST /api/field-report+# (functions/api/field-report.js). R2 is the cheapest storage already granted+# to the Pages deploy token. Reports land under reports/<date>/; a per-IP+# rate limit and a daily cap keep writes far inside the R2 free tier.+[[r2_buckets]]+binding = "FIELD_REPORTS"+bucket_name = "xerj-field-reports"+