{
  "schemaVersion": "1",
  "revision": "22ce5d34dbcb5a78",
  "id": "factory-debug-markers-worked-example",
  "slug": "debug-markers-worked-example",
  "title": "Human testimony joined to runtime evidence — worked example",
  "summary": "Detailed worked example with concrete prompts, observable outcomes, and the limits of the example.",
  "category": "Verification",
  "tags": [
    "debug-markers",
    "examples"
  ],
  "sources": [
    {
      "label": "Human testimony joined to runtime evidence — worked example",
      "url": "https://mindful-mango-accy.here.now/replay.html"
    }
  ],
  "sourceUnits": [
    "09-markers/replay.html#The session, beat by beat"
  ],
  "collection": "factory",
  "categoryId": "verification",
  "wordCount": 1401,
  "url": "/topics/factory-debug-markers-worked-example/",
  "markdownUrl": "/markdown/factory-debug-markers-worked-example.md?raw=1&v=22ce5d34dbcb5a78",
  "jsonUrl": "/api/v1/documents/factory-debug-markers-worked-example.json",
  "headings": [
    {
      "id": "the-session-beat-by-beat",
      "text": "The session, beat by beat",
      "level": 2
    }
  ],
  "markdown": "# Human testimony joined to runtime evidence — worked example\n\nDetailed worked example with concrete prompts, observable outcomes, and the limits of the example.\n\n## The session, beat by beat\n\nReplayed from a prior scripted session against the workshop's Field Notes demo app — the same run that produced [sample-session.json](https://mindful-mango-accy.here.now/sample-session.json), published raw on this site. Prompts are condensed; every output below is quoted verbatim from the captured artifacts.\n\nYou\n\nServe the Field Notes demo and reproduce the reconnect-and-save failure: type a note, go offline, save, reconnect, save again.\n\nAgent\n\nDrove the app in a scripted browser. The offline save failed honestly (\"Save failed (offline?)\"). After **Reconnect**, the second save showed **\"Saved \"** — but the mock server returned 401. The plant: reconnecting rotates the server's session token, the client keeps its stale copy, and the save handler treats anything below 500 as success:\n\n``` text\n// BUG: only 5xx counts as failure, so the stale-token 401 shows \"Saved \".\nif (res.status < 500) {\n  statusEl.textContent = \"Saved \";\n} else {\n  statusEl.textContent = \"Save failed (server error)\";\n}\n```\n\nWould your users file a useful bug report for this? They saw a success message. That gap is the whole reason markers exist.\n\nYou\n\nMark that moment. Testimony: \"It said Saved but my note never reached the server — this happened right after I reconnected.\"\n\nAgent\n\nThe  button uses `prompt()`, which blocks scripted browsers — so the mark went in through the console instead:\n\n``` text\nwindow.__AGENT_MARKERS__.mark(\n  \"user-flag\",\n  \"It said Saved but my note never reached the server — this happened right after I reconnected.\"\n)\n```\n\nMarker `<demo-marker>` recorded, pinned to the nine nearest events by id.\n\nFor a human it's one keystroke (Ctrl/Cmd+M) and one sentence at the moment of surprise. No form, no repro steps demanded — anything heavier and nobody uses it when it matters.\n\nYou\n\nExport the session and show me exactly what leaves the machine.\n\nAgent\n\n`exportSession()` produced a schemaVersion-1 JSON — 1 marker, 10 events, and a redaction block that documents what was withheld:\n\n``` text\n\"redaction\": {\n  \"storageValues\": \"excluded\",\n  \"requestBodies\": \"excluded\",\n  \"responseBodies\": \"excluded\",\n  \"userText\": \"preview+length only\"\n}\n```\n\nNo request or response bodies, no tokens, no storage values; user text travels as preview + length only. The full export is published raw as [sample-session.json](https://mindful-mango-accy.here.now/sample-session.json).\n\nThe redaction policy rides inside the payload, so every reader can audit what was withheld. A capture safe enough to paste anywhere gets pasted; a risky one gets hoarded and helps no one.\n\nYou\n\nRender the agent packet from that export.\n\nAgent\n\n``` text\nnode scripts/make-agent-packet.mjs samples/sample-session.json\n```\n\nThe packet leads with the testimony, then the seq-ordered evidence slice. Seven consecutive lines, exactly as rendered:\n\n``` text\n- [seq 3 · t+17397ms] click: click <button#save> \"Save note\"\n- [seq 4 · t+17519ms] fetch: POST /api/notes → NETWORK-ERROR (NetworkError: connection lost) [122ms]\n- [seq 5 · t+17519ms] console: console.warn: save failed: network unavailable\n- [seq 6 · t+18436ms] click: click <button#toggle-net> \"Reconnect\"\n- [seq 7 · t+18436ms] console: console.log: reconnected: session restored\n- [seq 8 · t+18909ms] click: click <button#save> \"Save note\"\n- [seq 9 · t+19031ms] fetch: POST /api/notes → 401 [122ms]\n```\n\nRead it top to bottom: NETWORK-ERROR → \"reconnected\" → 401 on the very next save, under a visible \"Saved \". A nine-line slice doing what a full log dump rarely does.\n\nYou\n\nNow read the packet cold — no source code, no other context. One hypothesis, one sentence, before you look at anything else.\n\nAgent\n\n*The reconnect rotated or invalidated a session credential the client still holds, and the app treats the resulting 401 as success.*\n\nFlagged as \"hypothesis — needs verification\", per the packet's claims boundary: testimony is not diagnosis, context is not proof.\n\nThat is the pass condition for any capture you build: a cold reader — human or agent — gets from the packet alone to the mechanism. The hypothesis arrives labeled as a draft; a person verifies it against the running app.\n\nYou\n\nGood. Give me the version I can drop into any app.\n\nAgent\n\nThe whole recorder — dependency-free, no build step. Everything above was captured by these lines (same bytes as [agent-markers.js](https://mindful-mango-accy.here.now/agent-markers.js) on this site):\n\n``` text\n/**\n * agent-markers.js — a tiny, dependency-free \"press a button, capture the moment\" recorder.\n *\n * Pattern: a MARKER is timestamped human testimony (\"this moment matters, here's why\").\n * A TRAIL is the ordered semantic events (console, fetch, error, click) that led there.\n * Export = bounded, redacted payload you can hand to an agent as a debug packet.\n *\n * Deliberately NOT captured: storage values, request/response bodies, raw input text.\n * Testimony is not diagnosis. Context is not proof.\n */\n(function (global) {\n  \"use strict\";\n\n  const state = {\n    running: false,\n    sessionId: null,\n    startedAtIso: null,\n    startedAtMs: 0,\n    seq: 0,\n    events: [],\n    markers: [],\n    maxEvents: 200,\n    nearbyEventLimit: 12,\n    restoreFns: [],\n  };\n\n  function now() {\n    return Math.round(performance.now() - state.startedAtMs);\n  }\n\n  function preview(text, max = 80) {\n    const s = String(text ?? \"\");\n    return {\n      preview: s.length > max ? s.slice(0, max) + \"…\" : s,\n      length: s.length,\n      truncated: s.length > max,\n    };\n  }\n\n  function record(type, data) {\n    if (!state.running) return null;\n    const event = { id: \"evt-\" + (++state.seq), seq: state.seq, t: now(), type, data };\n    state.events.push(event);\n    if (state.events.length > state.maxEvents) state.events.shift();\n    return event;\n  }\n\n  function patchConsole() {\n    [\"log\", \"warn\", \"error\"].forEach((level) => {\n      const original = console[level];\n      console[level] = function (...args) {\n        record(\"console\", { level, message: preview(args.map(String).join(\" \")) });\n        return original.apply(console, args);\n      };\n      state.restoreFns.push(() => (console[level] = original));\n    });\n  }\n\n  function patchFetch() {\n    const original = global.fetch;\n    global.fetch = async function (input, init) {\n      const url = typeof input === \"string\" ? input : input.url;\n      const method = (init && init.method) || \"GET\";\n      const started = now();\n      try {\n        const res = await original.apply(global, arguments);\n        record(\"fetch\", { method, url, status: res.status, ok: res.ok, ms: now() - started });\n        return res;\n      } catch (error) {\n        record(\"fetch\", { method, url, status: null, ok: false, ms: now() - started, error: preview(error && error.message) });\n        throw error;\n      }\n    };\n    state.restoreFns.push(() => (global.fetch = original));\n  }\n\n  function patchErrors() {\n    const onError = (event) =>\n      record(\"error\", { message: preview(event.message || String(event.reason || \"unknown\")) });\n    global.addEventListener(\"error\", onError);\n    global.addEventListener(\"unhandledrejection\", onError);\n    state.restoreFns.push(() => {\n      global.removeEventListener(\"error\", onError);\n      global.removeEventListener(\"unhandledrejection\", onError);\n    });\n  }\n\n  function patchClicks() {\n    const onClick = (event) => {\n      const el = event.target.closest(\"button, a, [data-action]\") || event.target;\n      record(\"click\", {\n        tag: el.tagName.toLowerCase(),\n        id: el.id || null,\n        action: el.dataset ? el.dataset.action || null : null,\n        text: preview(el.textContent && el.textContent.trim(), 40),\n      });\n    };\n    document.addEventListener(\"click\", onClick, true);\n    state.restoreFns.push(() => document.removeEventListener(\"click\", onClick, true));\n  }\n\n  const AgentMarkers = {\n    start(options = {}) {\n      if (state.running) return this;\n      state.sessionId = options.sessionId || \"session-\" + Date.now().toString(36);\n      state.startedAtIso = new Date().toISOString();\n      state.startedAtMs = performance.now();\n      state.maxEvents = options.maxEvents || 200;\n      state.nearbyEventLimit = options.nearbyEventLimit || 12;\n      state.seq = 0;\n      state.events = [];\n      state.markers = [];\n      state.running = true;\n      patchConsole();\n      patchFetch();\n      patchErrors();\n      patchClicks();\n      if (options.exposeGlobal !== false) global.__AGENT_MARKERS__ = AgentMarkers;\n      record(\"session\", { note: \"recording started\", app: options.app || \"unknown\" });\n      return this;\n    },\n\n    /** Human presses the button: timestamped testimony + pointers into the trail. */\n    mark(label, note) {\n      if (!state.running) throw new Error(\"AgentMarkers not started\");\n      const nearby = state.events.slice(-state.nearbyEventLimit).map((e) => e.id);\n      const marker = {\n        id: \"mrk-\" + (state.markers.length + 1) + \"-\" + Date.now().toString(36),\n        seq: ++state.seq,\n        t: now(),\n        label: label || \"unlabeled\",\n        note: note || \"\",\n        nearbyEventIds: nearby,\n        screenshot: \"unavailable\", // browser demo: no screenshot API without permissions\n      };\n      state.markers.push(marker);\n      record(\"marker\", { markerId: marker.id, label: marker.label });\n      return marker;\n    },\n\n    record(type, data) {\n      return record(\"manual\", { type, ...data });\n    },\n\n    /** Bounded, redacted payload — everything an agent gets, nothing more. */\n    exportSession() {\n      return {\n        schemaVersion: 1,\n        sessionId: state.sessionId,\n        startedAt: state.startedAtIso,\n        exportedAt: new Date().toISOString(),\n        userAgent: navigator.userAgent,\n        markers: state.markers,\n        events: state.events,\n        redaction: {\n          storageValues: \"excluded\",\n          requestBodies: \"excluded\",\n          responseBodies: \"excluded\",\n          userText: \"preview+length only\",\n        },\n      };\n    },\n\n    stop() {\n      state.restoreFns.forEach((restore) => restore());\n      state.restoreFns = [];\n      state.running = false;\n      return this;\n    },\n  };\n\n  if (typeof module !== \"undefined\" && module.exports) module.exports = AgentMarkers;\n  global.AgentMarkers = AgentMarkers;\n})(typeof window !== \"undefined\" ? window : globalThis);\n```\n\nThe boot file and the packet renderer are printed complete in the [section guide](https://mindful-mango-accy.here.now/index.html), or replay this whole loop from an empty directory:\n\n``` text\nmkdir -p markers-quickstart && cd markers-quickstart\ncurl -sO https://mindful-mango-accy.here.now/agent-markers.js\ncurl -sO https://mindful-mango-accy.here.now/make-agent-packet.mjs\ncurl -sO https://mindful-mango-accy.here.now/sample-session.json\nnode make-agent-packet.mjs sample-session.json\n```\n\nTotal session: five prompts. The loop the transcript demonstrates — mark → export → packet → hypothesis — is the same one your attendees' agents replay from [agent.md](https://mindful-mango-accy.here.now/agent.md)."
}
