Collect Feedback on Every Answer

Every answer now carries its version’s ID, and your eval runs score each version on cases you wrote. They can’t say how useful hikers find v7’s answers once that version reaches them.

In this lesson, you’ll collect ratings and other signals hikers leave, each tied to its answer’s trace, then count the ratings from a simulated week to see how many you can act on. Start with what makes a rating useful.

Tie Each Rating to Its Answer’s Trace

A rating helps only if it leads you to the answer it judges. A row with a rating, a date, and “it said the hut was open but it’s closed for the season” tells you only that some answer upset someone that day. With the answer’s trace ID, you can inspect the retrieved reports, the version that ran, and the output to tell a stale report from a model that ignored a good one.

Your trace ID is the request ID in each /ask response’s X-Request-Id header. Add a rating form template, with an <output> for errors, to public/index.html:

Language: HTML Filename: public/index.html
<template id="rate">
  <form>
    <button name="value" value="up">Helpful</button>
    <button name="value" value="down">Not helpful</button>
    <select name="reason">
      <option value="">Why? (optional)</option>
      <option value="out-of-date">Out of date</option>
      <option value="wrong-place">Wrong place or route</option>
      <option value="missed-closure">Missed a closure</option>
      <option value="no-answer">Didn't answer my question</option>
    </select>
    <textarea name="text" maxlength="500"
      placeholder="Anything else? (optional)"></textarea>
    <output></output>
  </form>
</template>

In public/app.js, current holds the on-screen answer’s ID. The header arrives before the first word, so right after fetch() in ask(), set current = res.headers.get("X-Request-Id") and finished = false. Once the answer has streamed, set finished = true and call addRating(answerBox, current):

Language: JavaScript Filename: public/app.js
let current = null;
let finished = false;

function signal(body) {
  return fetch("/feedback", { method: "POST", keepalive: true,
    headers: { "Content-Type": "application/json",
      "X-Hiker-Id": hiker },
    body: JSON.stringify(body) });
}

function addRating(answerBox, traceId) {
  const form = document.querySelector("#rate")
    .content.firstElementChild.cloneNode(true);
  form.addEventListener("submit", async (event) => {
    event.preventDefault();
    const data = new FormData(form);
    const res = await signal({ traceId, kind: "thumbs",
      value: event.submitter.value,
      reason: data.get("reason") || undefined,
      text: data.get("text") || undefined,
    }).catch(() => null);
    if (res?.ok) {
      form.replaceWith(await res.text()
        || "Thanks for rating this answer.");
    } else {
      form.querySelector("output").value =
        "Your rating wasn't sent. Please try again.";
    }
  });
  answerBox.after(form);
}

event.submitter is the button the hiker clicked. The form goes away only once the server returns a successful response, so a hiker can retry a failed send. If they rate twice, the latest rating counts. If /feedback returns text, that text replaces the form, as its handler below shows. hiker is the page’s anonymous ID, which /feedback uses for its limit.

The server checks each signal and stores it in feedback/, one JSON Lines file per day. Save feedback.js:

Language: JavaScript Filename: feedback.js
import { appendFile, mkdir } from "node:fs/promises";
import { z } from "zod";
import { redact } from "./redact.js";

const traceId = z.uuid();
export const Feedback = z.discriminatedUnion("kind", [
  z.object({ kind: z.literal("thumbs"), traceId,
    value: z.enum(["up", "down"]),
    reason: z.enum(["out-of-date", "wrong-place",
      "missed-closure", "no-answer"]).optional(),
    text: z.string().max(500).optional() }),
  z.object({ kind: z.literal("handoff"), traceId }),
  z.object({ kind: z.literal("left"), traceId,
    finished: z.boolean() }),
]);

export async function record(signal) {
  const time = new Date().toISOString();
  const line = { time, ...signal };
  if (line.text) line.text = redact(line.text);
  await mkdir("feedback", { recursive: true });
  await appendFile(`feedback/${time.slice(0, 10)}.jsonl`,
    JSON.stringify(line) + "\n");
}

z.discriminatedUnion() picks the schema by kind, so a thumbs rating needs up or down, and a handoff can’t carry a comment. A feedback comment is one more copy of a hiker’s words on your personal-data map, and redact() can’t catch everything. Pass "feedback" to sweepTraces() beside "handoffs" so feedback is deleted after RETENTION_DAYS.

In a test run, “Ana Brunner, 079 555 0142, hut 6 Thursday” was stored as “Ana Brunner, [phone:ad563792cc9e9272], hut 6 Thursday”. Decide what still identifies the hiker, then open the mentor below and paste the redacted text with your answer:

Record Signals Beyond Ratings

Most hikers never rate, but what they do next says something. You can track three implicit signals without asking for a rating: a question asked again within ten minutes, a request to Talk to a warden, and a departure from the page.

In the warden button’s handler, add if (current) signal({ traceId: current, kind: "handoff" });. The signal identifies the on-screen answer, even mid-stream. Then record leaving:

Language: JavaScript Filename: public/app.js
addEventListener("pagehide", () => {
  if (current) {
    signal({ traceId: current, kind: "left", finished });
  }
});

Use finished to distinguish leaving mid-answer from the normal end of a visit, which isn’t a complaint, so count only finished: false. The pagehide event fires as the page goes away, and keepalive: true lets the request outlive it. Mobile browsers often skip pagehide, though, so a missing left proves nothing.

Only the server sees a repeat. Rather than copy the question, compare the places and topics about() returns, kept in a Map in memory only, since it holds the hiker ID:

Language: JavaScript Filename: feedback.js
const WINDOW_MS = 10 * 60_000;
const recent = new Map();

function sweep() {
  for (const [id, r] of recent) {
    if (Date.now() - r.at > WINDOW_MS) recent.delete(id);
  }
}
setInterval(sweep, 60_000).unref();

export function lookUp(traceId) {
  const r = recent.get(traceId);
  return r && Date.now() - r.at <= WINDOW_MS ? r : undefined;
}

export function noteAsk(traceId, hiker, asked, version) {
  sweep();
  const key = JSON.stringify([asked.places, asked.topics]);
  const earlier = [...recent].findLast(([, r]) =>
    asked.places.length > 0 && r.answered
    && r.hiker === hiker && r.key === key);
  recent.set(traceId,
    { hiker, key, version, at: Date.now(), answered: false });
  if (!earlier) return null;
  return { target: earlier[0], version: earlier[1].version };
}

export function answered(traceId) {
  const r = lookUp(traceId);
  if (r) r.answered = true;
}

The timer sweeps every minute, even without traffic, and lookUp() ignores entries over ten minutes old. noteAsk() matches only answers answered() marked as sent, so a retry after a failure doesn’t count. A match is still a noisy hint.

Ratings need a limit of their own, so they never use up course 4’s /ask limit. Add a count to feedback.js:

Language: JavaScript Filename: feedback.js
const PER_MINUTE = 20;
const counts = new Map();
let minute = null;

export function tooMany(hiker) {
  const now = new Date().toISOString().slice(0, 16);
  if (now !== minute) {
    minute = now;
    counts.clear();
  }
  const n = (counts.get(hiker) ?? 0) + 1;
  counts.set(hiker, n);
  return n > PER_MINUTE;
}

A script that changes IDs still gets past this cap of 20 a minute.

In server.js, which already imports emergencyWord() and RESCUE_LINE, import the new functions and wire /ask and /feedback. The names avoid a clash with course 3’s cache function, remember():

Language: JavaScript Filename: server.js
import { Feedback, record, lookUp, noteAsk, answered,
  tooMany } from "./feedback.js";
import { about } from "./about.js";

const writeFailed = (err) =>
  console.error("feedback write failed", err.code);

// In /ask, after its first lines:
const flags = (res.locals.flags = {});
res.locals.version = live.id;
const again = noteAsk(id, hiker, about(question), live.id);
if (again) {
  res.locals.signal = { kind: "askedAgain", ...again };
  record({ kind: "askedAgain", traceId: again.target,
    version: again.version }).catch(writeFailed);
}
// Where /ask already learns each outcome:
//   after gate(): flags.guardrail = !passed;
//   flags.refusal = refused;
//   inside handoff(): flags.handoff = reason;
//   where it writes CUT_OFF: flags.cutOff = true;
// At the end of /ask, once the reply is sent in full:
answered(id);
flags.answered = true;

app.post("/feedback", async (req, res) => {
  const parsed = Feedback.safeParse(req.body);
  const hiker = req.get("X-Hiker-Id");
  if (!parsed.success || !hiker) return res.sendStatus(400);
  const { kind, traceId, text } = parsed.data;
  const version = lookUp(traceId)?.version ?? null;
  const known = version !== null;
  const line = { ...parsed.data, version, known };
  res.locals.signal = { kind, target: traceId, version };
  const busy = tooMany(hiker);
  if (text && emergencyWord(text)) {
    if (!busy) record(line).catch(writeFailed);
    return res.type("text").send(RESCUE_LINE);
  }
  if (busy) return res.sendStatus(429);
  await record(line);
  res.sendStatus(204);
});

The askedAgain write isn’t awaited and logs its own failure, since a lost feedback line costs less than a lost answer about a closure. In /feedback, a failed non-emergency write becomes a 500, so the page can retry.

The emergency check comes before the rate-limit response, as in /ask. A comment that emergencyWord() matches gets RESCUE_LINE, shown in place of the form, regardless of the rate limit or the write’s outcome.

known: false means lookUp() didn’t find the trace ID. The rating may arrive after ten minutes or a restart, or use a made-up ID. Storing unmatched feedback keeps real late ratings. An answered line with its ID in server.log tells a late rating from a fake one.

Set the other flags where the comments say. In timer(), add version, signal, and flags from res.locals to the line. A signal’s target is the requestId of the answer it’s about. That joins the signal to the answer’s /ask line, which only a finished request writes.

Before clicking the button below, write down one repeat noteAsk() would miss and one it would count wrongly, and paste both into the mentor chat:

Count a Week of Ratings

Use scripts/count-feedback.js to count how many ratings you get and how many lead to a trace. Its lines() function comes from Spot Misuse in a Week of Traffic:

Language: JavaScript Filename: scripts/count-feedback.js
import { existsSync, readFileSync, readdirSync } from "node:fs";

const lines = (file) => readFileSync(file, "utf8").split("\n")
  .filter(Boolean).map((line) => JSON.parse(line));
const all = (dir) => (existsSync(dir)
  ? readdirSync(dir).flatMap((f) => lines(`${dir}/${f}`)) : []);

const kept = new Set(all("traces").map((s) => s.traceId));
const latest = new Map();
for (const f of all("feedback")) {
  if (f.kind === "thumbs") latest.set(f.traceId, f.value);
}
const answers = readFileSync("server.log", "utf8")
  .split("\n").filter((l) => l.includes('"answered":true'))
  .length;
const lost = [...latest.keys()].filter((t) => !kept.has(t));
console.log(`${latest.size} rated of ${answers} answers`);
console.log(`${lost.length} rated answers with no kept trace`);

The script counts rated answers, not clicks, against log lines flagged answered, so refusals and failed requests stay out. It treats a missing folder as empty.

Clear the last run’s feedback and traces:

Language: Windows PowerShell
PS> Remove-Item -Recurse -Force -ErrorAction Ignore feedback, traces
Language: Shell
$ rm -rf feedback traces

Start the server with its output also going to a fresh server.log:

Language: Windows PowerShell
PS> npm start | Tee-Object server.log
Language: Shell
$ npm start | tee server.log

In a second terminal, run npm run traffic -- --month=september --feedback, whose new --feedback option makes some simulated hikers rate, ask again, ask for a warden, or leave. When it returns, wait until server.log stops growing, stop the server with Ctrl+C, and run node scripts/count-feedback.js.

The first line’s rating share comes from the simulator’s settings. Its hikers submit ratings at a fixed rate, whatever the answer’s quality. Real hikers rate far less, mostly when annoyed, and give more weight to how an answer feels than to whether it’s right. That’s all you need about those biases for now.

The second line counts ratings you can’t debug. The trace writer keeps every error and flagged answer but one in ten of the rest, so about 90 percent (1 − SAMPLE_RATE) of rated answers that passed every check have no trace.

In three other tests on December 3, 2026, each with 10,000 such answers, course 2’s shouldKeep() left 8,979, 8,946, and 9,027 without one. Your share of ratings without traces is lower, since flagged answers keep their traces. A share near zero means a bug.

The count covers thumbs ratings only, so search server.log for the traceId of one feedback/ record of each other kind. Your IDs will differ:

Language: Windows PowerShell
PS> Select-String c5e640c0-2070-4a06-9a6d-cef4307bc111 server.log
Language: Shell
$ grep c5e640c0-2070-4a06-9a6d-cef4307bc111 server.log

Besides the signal’s own line, where the ID is the target, an askedAgain signal must match an earlier answered /ask line. A handoff signal matches the on-screen answer’s line, answered or not. A left signal with finished: false matches no other line, since an abandoned request writes none.

Check Your Understanding

  1. A thumbs-down in feedback/ has a trace ID that matches no kept trace. What can you still learn from it, and what can’t you?
  2. Why does noteAsk() compare fields from about() rather than the question’s text?
  1. You can still learn the rating’s reason, redacted comment, day, and version from the record or the answer’s /ask log line. You can’t see the retrieved reports or the answer, so you can’t tell why it went wrong or make it an eval case.
  2. With fields, no copy of the question waits ten minutes in the map or reaches feedback/. Fields also catch a rephrased question, though about() misses places and topics it doesn’t list.

In the next lesson, Keep the Traces Hikers Rated, you’ll make sure every rated answer keeps its trace.

Become a Member to join the conversation.