{
  "schemaVersion": "1",
  "revision": "22ce5d34dbcb5a78",
  "id": "factory-debug-markers-practice",
  "slug": "debug-markers-practice",
  "title": "Human testimony joined to runtime evidence — prompts and exercises",
  "summary": "Complete reusable prompts, setup recipes, success checks, and caveats for human testimony joined to runtime evidence.",
  "category": "Verification",
  "tags": [
    "prompts",
    "exercises",
    "debug-markers"
  ],
  "sources": [
    {
      "label": "Human testimony joined to runtime evidence",
      "url": "https://mindful-mango-accy.here.now/"
    },
    {
      "label": "Public setup contract",
      "url": "https://mindful-mango-accy.here.now/agent.md"
    }
  ],
  "sourceUnits": [
    "09-markers/index.html#Quick start",
    "09-markers/index.html#Prompt library",
    "09-markers/index.html#Set it up (agent guide)",
    "09-markers/index.html#Hand an agent a debug packet",
    "09-markers/index.html#Grade your capture: can it be read cold?",
    "09-markers/index.html#Write the redaction policy first",
    "09-markers/agent.md"
  ],
  "collection": "factory",
  "categoryId": "verification",
  "wordCount": 3635,
  "url": "/topics/factory-debug-markers-practice/",
  "markdownUrl": "/markdown/factory-debug-markers-practice.md?raw=1&v=22ce5d34dbcb5a78",
  "jsonUrl": "/api/v1/documents/factory-debug-markers-practice.json",
  "headings": [
    {
      "id": "quick-start",
      "text": "Quick start",
      "level": 2
    },
    {
      "id": "prompt-library",
      "text": "Prompt library",
      "level": 2
    },
    {
      "id": "hand-an-agent-a-debug-packet",
      "text": "Hand an agent a debug packet",
      "level": 3
    },
    {
      "id": "grade-your-capture-can-it-be-read-cold",
      "text": "Grade your capture: can it be read cold?",
      "level": 3
    },
    {
      "id": "write-the-redaction-policy-first",
      "text": "Write the redaction policy first",
      "level": 3
    },
    {
      "id": "set-it-up-agent-guide",
      "text": "Set it up (agent guide)",
      "level": 2
    },
    {
      "id": "complete-reusable-setup-contract",
      "text": "Complete reusable setup contract",
      "level": 2
    },
    {
      "id": "debugging-with-markers-agent-setup-guide",
      "text": "Debugging with Markers — agent setup guide",
      "level": 2
    },
    {
      "id": "prerequisites",
      "text": "Prerequisites",
      "level": 2
    },
    {
      "id": "steps",
      "text": "Steps",
      "level": 2
    },
    {
      "id": "success-check",
      "text": "Success check",
      "level": 2
    },
    {
      "id": "notes-for-agents",
      "text": "Notes for agents",
      "level": 2
    }
  ],
  "markdown": "# Human testimony joined to runtime evidence — prompts and exercises\n\nComplete reusable prompts, setup recipes, success checks, and caveats for human testimony joined to runtime evidence.\n\n## Quick start\n\nRuns from any empty directory — needs only `curl` and Node 18+. It pulls the recorder, the packet renderer, and a real captured session from this site, then prints the agent-ready debug packet.\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\n## Prompt library\n\n### Hand an agent a debug packet\n\n- Agent: any coding agent\n- Working directory: anywhere\n- Expected result: a one-sentence hypothesis, then a reproducible scenario with unproven parts flagged\n\n``` text\nHere is a debug packet captured from a live session of my app. Before you read any code:\n\n1. Read the human testimony, then the evidence trail in seq order.\n2. State your single most likely hypothesis for the failure, in one sentence.\n3. Draft a reproducible scenario — preconditions, steps, expected, observed — using ONLY the evidence in the packet.\n4. Label anything the trail cannot prove as \"hypothesis — needs verification\".\n\nTestimony is not diagnosis. Context is not proof.\n\n--- PACKET ---\n[paste the output of: node scripts/make-agent-packet.mjs your-session.json]\n```\n\n### Grade your capture: can it be read cold?\n\n- Agent: any coding agent\n- Working directory: your project, with a fresh export on disk\n- Expected result: a stated hypothesis, or the one knob to turn first\n\n``` text\nHere is a marker-session export from my app (JSON, schemaVersion 1). Render it with scripts/make-agent-packet.mjs and read the packet cold — no source code, no other context.\n\nAnswer two things:\n1. Can you state one specific hypothesis from the testimony and trail alone? State it.\n2. If you cannot, tell me which single change to make first: mark closer to the failure, raise nearbyEventLimit, or add one missing event type to the recorder.\n```\n\n### Write the redaction policy first\n\n- Agent: your coding agent\n- Working directory: your project, before any recording code lands\n- Expected result: an exclusion list for your app plus a redaction JSON block for every export\n\n``` text\nI'm adding just-in-time debug capture (markers plus an event trail) to this app. Before any recording code lands, draft our redaction policy: list every category of data a capture must NEVER contain (request/response bodies, tokens, storage values, raw user text, plus anything specific to this codebase), and produce a redaction JSON block to embed verbatim in every export so readers can audit what was withheld. Default user text to \"preview+length only\".\n```\n\n## Set it up (agent guide)\n\n1.  Add the recorder to your app as `<static-dir>/agent-markers.js`. This is the whole thing — no dependencies, no build step. (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\n2.  Boot it with `<static-dir>/markers-boot.js` — starts recording, binds Ctrl/Cmd+M to “mark”, and exposes `exportMarkers()` for downloading the capture. Replace `\"my-app\"` with your app’s name.\n\n    ``` text\n    /* markers-boot.js — load AFTER agent-markers.js, BEFORE your app's own scripts.\n       Ctrl/Cmd+M drops a marker; exportMarkers() in the console downloads the capture. */\n    AgentMarkers.start({ app: \"my-app\" }); // replace \"my-app\" with your app's name\n\n    // One keystroke at the moment of surprise: one sentence of testimony.\n    window.addEventListener(\"keydown\", (e) => {\n      if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === \"m\") {\n        e.preventDefault();\n        const note = prompt(\"Why does this moment matter? (one sentence — it travels with the capture)\");\n        if (note !== null) console.log(\"marked:\", AgentMarkers.mark(\"user-flag\", note).id);\n      }\n    });\n\n    // Call exportMarkers() from the console, or wire it to a button.\n    window.exportMarkers = () => {\n      const session = AgentMarkers.exportSession();\n      const blob = new Blob([JSON.stringify(session, null, 2)], { type: \"application/json\" });\n      const a = Object.assign(document.createElement(\"a\"), {\n        href: URL.createObjectURL(blob),\n        download: session.sessionId + \".json\",\n      });\n      a.click();\n      URL.revokeObjectURL(a.href);\n      return session.sessionId + \".json\";\n    };\n    ```\n\n    Load both before your app’s own scripts: `<script src=\"agent-markers.js\"></script>` then `<script src=\"markers-boot.js\"></script>`.\n\n3.  Save the packet renderer as `scripts/make-agent-packet.mjs` in your project — it turns any export into the markdown packet the prompts above expect.\n\n    ``` text\n    #!/usr/bin/env node\n    /**\n     * make-agent-packet.mjs — turn a marker-session export into a bounded agent debug packet.\n     *\n     * Usage:\n     *   node scripts/make-agent-packet.mjs <session.json> [marker-id]\n     *\n     * Emits markdown on stdout: human testimony, the nearby evidence slice, redaction\n     * receipts, and an explicit claims boundary — ready to paste into any agent.\n     */\n    import { readFileSync } from \"node:fs\";\n\n    const [file, markerArg] = process.argv.slice(2);\n    if (!file) {\n      console.error(\"usage: node scripts/make-agent-packet.mjs <session.json> [marker-id]\");\n      process.exit(1);\n    }\n\n    const session = JSON.parse(readFileSync(file, \"utf8\"));\n    if (session.schemaVersion !== 1) {\n      console.error(`unsupported schemaVersion: ${session.schemaVersion}`);\n      process.exit(1);\n    }\n\n    const marker = markerArg\n      ? session.markers.find((m) => m.id === markerArg)\n      : session.markers.at(-1);\n    if (!marker) {\n      console.error(markerArg ? `marker '${markerArg}' not found` : \"no markers in session\");\n      process.exit(1);\n    }\n\n    const nearbyIds = new Set(marker.nearbyEventIds ?? []);\n    const nearby = session.events.filter((e) => nearbyIds.has(e.id));\n    const fmt = (e) => {\n      const d = e.data ?? {};\n      switch (e.type) {\n        case \"fetch\":\n          return `${d.method} ${d.url} → ${d.status ?? \"NETWORK-ERROR\"}${d.error ? ` (${d.error.preview ?? d.error})` : \"\"} [${d.ms}ms]`;\n        case \"console\":\n          return `console.${d.level}: ${d.message?.preview ?? \"\"}`;\n        case \"click\":\n          return `click <${d.tag}${d.id ? `#${d.id}` : \"\"}> \"${d.text?.preview ?? \"\"}\"`;\n        case \"error\":\n          return `error: ${d.message?.preview ?? \"\"}`;\n        default:\n          return JSON.stringify(d);\n      }\n    };\n\n    const lines = [];\n    lines.push(`# Debug packet — marker ${marker.id}`);\n    lines.push(\"\");\n    lines.push(`- session: ${session.sessionId} (started ${session.startedAt})`);\n    lines.push(`- marker time: t+${marker.t}ms · label: ${marker.label}`);\n    lines.push(`- screenshot: ${marker.screenshot ?? \"unavailable\"}`);\n    lines.push(\"\");\n    lines.push(\"## Human testimony (why this moment matters)\");\n    lines.push(\"\");\n    lines.push(`> ${marker.note || \"(no explanation recorded)\"}`);\n    lines.push(\"\");\n    lines.push(`## Evidence trail (${nearby.length} events nearest the marker, seq order)`);\n    lines.push(\"\");\n    for (const e of nearby) lines.push(`- [seq ${e.seq} · t+${e.t}ms] ${e.type}: ${fmt(e)}`);\n    lines.push(\"\");\n    lines.push(\"## Redaction receipts\");\n    lines.push(\"\");\n    for (const [k, v] of Object.entries(session.redaction ?? {})) lines.push(`- ${k}: ${v}`);\n    lines.push(\"\");\n    lines.push(\"## Task for the agent\");\n    lines.push(\"\");\n    lines.push(\"Draft a reproducible scenario (preconditions, steps, expected, observed) that\");\n    lines.push(\"explains the testimony using ONLY the evidence above. Flag anything the trail\");\n    lines.push(\"cannot prove as a hypothesis needing verification.\");\n    lines.push(\"\");\n    lines.push(\"## Claims boundary\");\n    lines.push(\"\");\n    lines.push(\"Testimony is not diagnosis. Context is not proof. The trail shows what was\");\n    lines.push(\"captured, not everything that happened.\");\n\n    console.log(lines.join(\"\\n\"));\n    ```\n\n**Success check:** render the real captured session from this site, then read the packet cold and state a hypothesis before looking at any code.\n\n``` text\ncurl -sO https://mindful-mango-accy.here.now/sample-session.json\nnode scripts/make-agent-packet.mjs sample-session.json\n```\n\n``` text\n# Debug packet — marker <demo-marker>\n\n- session: <demo-session> (started the recorded snapshot)\n- marker time: t+26900ms · label: user-flag\n- screenshot: unavailable\n\n## Human testimony (why this moment matters)\n\n> It said Saved but my note never reached the server — this happened right after I reconnected.\n\n## Evidence trail (9 events nearest the marker, seq order)\n\n- [seq 1 · t+0ms] session: {\"note\":\"recording started\",\"app\":\"field-notes-demo\"}\n- [seq 2 · t+16914ms] click: click <button#toggle-net> \"Go offline\"\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```\n\nYou pass when a reader — human or agent — gets from that packet alone to something like “the reconnect rotated or invalidated a session credential the client still holds.” Then verify the loop in your own app: press Ctrl/Cmd+M, type a sentence, run `exportMarkers()` in the console, and confirm the downloaded JSON has your marker and a `redaction` block.\n\n## Complete reusable setup contract\n\n## Debugging with Markers — agent setup guide\n\nFollowing this file sets up: a just-in-time debug-capture loop in the user's web app — a ~150-line dependency-free recorder (semantic event trail + human markers), a mark hotkey, a redacted JSON export, and a renderer that turns exports into agent-ready debug packets.\n\nPlaceholders used below: `<project-root>` = the project you are working in; `<static-dir>` = wherever that app serves static JS from (often `public/` or the app's HTML directory). All other paths are literal.\n\nHuman companion pages on this site (for your user, not needed to execute this file): the section guide at https://mindful-mango-accy.here.now/, a Session Replay of the captured run this file's success check reproduces at https://mindful-mango-accy.here.now/replay.html, and a Q&A Dialogue at https://mindful-mango-accy.here.now/dialogue.html.\n\n## Prerequisites\n\nCheck each before starting:\n\n```bash\nnode --version   # need v18 or newer\ncurl --version   # used only to download the sample session in the success check\n```\n\nExpected: Node 18+ and curl present. If a tool is missing, stop and tell your user what to install.\n\n## Steps\n\n1. Create `<static-dir>/agent-markers.js` with exactly this content (same bytes as https://mindful-mango-accy.here.now/agent-markers.js — you may download it instead of typing it):\n\n   ```js\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\n2. Create `<static-dir>/markers-boot.js` with exactly this content, replacing only `\"my-app\"` with the app's real name:\n\n   ```js\n   /* markers-boot.js — load AFTER agent-markers.js, BEFORE your app's own scripts.\n      Ctrl/Cmd+M drops a marker; exportMarkers() in the console downloads the capture. */\n   AgentMarkers.start({ app: \"my-app\" }); // replace \"my-app\" with your app's name\n\n   // One keystroke at the moment of surprise: one sentence of testimony.\n   window.addEventListener(\"keydown\", (e) => {\n     if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === \"m\") {\n       e.preventDefault();\n       const note = prompt(\"Why does this moment matter? (one sentence — it travels with the capture)\");\n       if (note !== null) console.log(\"marked:\", AgentMarkers.mark(\"user-flag\", note).id);\n     }\n   });\n\n   // Call exportMarkers() from the console, or wire it to a button.\n   window.exportMarkers = () => {\n     const session = AgentMarkers.exportSession();\n     const blob = new Blob([JSON.stringify(session, null, 2)], { type: \"application/json\" });\n     const a = Object.assign(document.createElement(\"a\"), {\n       href: URL.createObjectURL(blob),\n       download: session.sessionId + \".json\",\n     });\n     a.click();\n     URL.revokeObjectURL(a.href);\n     return session.sessionId + \".json\";\n   };\n   ```\n\n3. Load both files in the app's page BEFORE the app's own scripts (and before any code that replaces `window.fetch` — app-level fetch wrappers such as mocks or auth shims must be installed before `AgentMarkers.start()` runs so their calls land in the trail):\n\n   ```html\n   <script src=\"agent-markers.js\"></script>\n   <script src=\"markers-boot.js\"></script>\n   ```\n\n4. Create `<project-root>/scripts/make-agent-packet.mjs` with exactly this content (same bytes as https://mindful-mango-accy.here.now/make-agent-packet.mjs):\n\n   ```js\n   #!/usr/bin/env node\n   /**\n    * make-agent-packet.mjs — turn a marker-session export into a bounded agent debug packet.\n    *\n    * Usage:\n    *   node scripts/make-agent-packet.mjs <session.json> [marker-id]\n    *\n    * Emits markdown on stdout: human testimony, the nearby evidence slice, redaction\n    * receipts, and an explicit claims boundary — ready to paste into any agent.\n    */\n   import { readFileSync } from \"node:fs\";\n\n   const [file, markerArg] = process.argv.slice(2);\n   if (!file) {\n     console.error(\"usage: node scripts/make-agent-packet.mjs <session.json> [marker-id]\");\n     process.exit(1);\n   }\n\n   const session = JSON.parse(readFileSync(file, \"utf8\"));\n   if (session.schemaVersion !== 1) {\n     console.error(`unsupported schemaVersion: ${session.schemaVersion}`);\n     process.exit(1);\n   }\n\n   const marker = markerArg\n     ? session.markers.find((m) => m.id === markerArg)\n     : session.markers.at(-1);\n   if (!marker) {\n     console.error(markerArg ? `marker '${markerArg}' not found` : \"no markers in session\");\n     process.exit(1);\n   }\n\n   const nearbyIds = new Set(marker.nearbyEventIds ?? []);\n   const nearby = session.events.filter((e) => nearbyIds.has(e.id));\n   const fmt = (e) => {\n     const d = e.data ?? {};\n     switch (e.type) {\n       case \"fetch\":\n         return `${d.method} ${d.url} → ${d.status ?? \"NETWORK-ERROR\"}${d.error ? ` (${d.error.preview ?? d.error})` : \"\"} [${d.ms}ms]`;\n       case \"console\":\n         return `console.${d.level}: ${d.message?.preview ?? \"\"}`;\n       case \"click\":\n         return `click <${d.tag}${d.id ? `#${d.id}` : \"\"}> \"${d.text?.preview ?? \"\"}\"`;\n       case \"error\":\n         return `error: ${d.message?.preview ?? \"\"}`;\n       default:\n         return JSON.stringify(d);\n     }\n   };\n\n   const lines = [];\n   lines.push(`# Debug packet — marker ${marker.id}`);\n   lines.push(\"\");\n   lines.push(`- session: ${session.sessionId} (started ${session.startedAt})`);\n   lines.push(`- marker time: t+${marker.t}ms · label: ${marker.label}`);\n   lines.push(`- screenshot: ${marker.screenshot ?? \"unavailable\"}`);\n   lines.push(\"\");\n   lines.push(\"## Human testimony (why this moment matters)\");\n   lines.push(\"\");\n   lines.push(`> ${marker.note || \"(no explanation recorded)\"}`);\n   lines.push(\"\");\n   lines.push(`## Evidence trail (${nearby.length} events nearest the marker, seq order)`);\n   lines.push(\"\");\n   for (const e of nearby) lines.push(`- [seq ${e.seq} · t+${e.t}ms] ${e.type}: ${fmt(e)}`);\n   lines.push(\"\");\n   lines.push(\"## Redaction receipts\");\n   lines.push(\"\");\n   for (const [k, v] of Object.entries(session.redaction ?? {})) lines.push(`- ${k}: ${v}`);\n   lines.push(\"\");\n   lines.push(\"## Task for the agent\");\n   lines.push(\"\");\n   lines.push(\"Draft a reproducible scenario (preconditions, steps, expected, observed) that\");\n   lines.push(\"explains the testimony using ONLY the evidence above. Flag anything the trail\");\n   lines.push(\"cannot prove as a hypothesis needing verification.\");\n   lines.push(\"\");\n   lines.push(\"## Claims boundary\");\n   lines.push(\"\");\n   lines.push(\"Testimony is not diagnosis. Context is not proof. The trail shows what was\");\n   lines.push(\"captured, not everything that happened.\");\n\n   console.log(lines.join(\"\\n\"));\n   ```\n\n## Success check\n\nRun from `<project-root>`:\n\n```bash\ncurl -sO https://mindful-mango-accy.here.now/sample-session.json\nnode scripts/make-agent-packet.mjs sample-session.json\n```\n\nExpected observable result: a markdown debug packet beginning `# Debug packet — marker <demo-marker>`, containing the testimony line `> It said Saved but my note never reached the server — this happened right after I reconnected.`, a 9-event evidence trail whose last line is `- [seq 9 · t+19031ms] fetch: POST /api/notes → 401 [122ms]`, four redaction receipts, a task section, and a claims boundary.\n\nThen perform the cold-read check: read that packet with NO other context (do not open the recorder source or this page) and state one specific hypothesis for the failure. A passing hypothesis names the mechanism, e.g. \"the reconnect rotated or invalidated a session credential the client still holds, and the app treats the resulting 401 as success.\"\n\nFinally, verify the loop live in the user's app: open it in a browser, press Ctrl/Cmd+M (or run `window.__AGENT_MARKERS__.mark(\"user-flag\", \"test marker\")` in the console — `prompt()` blocks automation), then run `exportMarkers()` in the console. Confirm a `session-*.json` file downloads with `markers.length >= 1` and a `redaction` block.\n\nReport to your user: what you set up, the packet output of the success check, your cold-read hypothesis, and anything you had to adapt.\n\n## Notes for agents\n\n- `prompt()` blocks scripted browsers. In automation, call `window.__AGENT_MARKERS__.mark(label, note)` instead of the Ctrl/Cmd+M hotkey.\n- On macOS, Cmd+M can collide with the browser's minimize shortcut. The console call or an on-page button wired to the same `dropMarker` logic is the reliable path.\n- The event ring buffer is in-memory only — a page reload wipes it. Export before navigating or reloading.\n- `make-agent-packet.mjs` exits with `unsupported schemaVersion` unless the export has `schemaVersion: 1`. Exports from this recorder always do; hand-edited files may not.\n- The export deliberately excludes storage values, request/response bodies, and raw user text (preview+length only). Do not \"improve\" it by adding them — the redaction block inside every export is the audit trail readers rely on.\n- The recorder caps the trail at 200 events and pins the 12 nearest event ids to each marker (`maxEvents` / `nearbyEventLimit` options on `AgentMarkers.start`). If packets read too thin, raise `nearbyEventLimit` before adding new event types."
}
