@weatherboard/annotation 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/ADOPTING.md +52 -0
  2. package/README.md +9 -1
  3. package/dist/anchor.cjs +2 -0
  4. package/dist/anchor.cjs.map +7 -0
  5. package/dist/anchor.d.cts +295 -0
  6. package/dist/anchor.d.mts +295 -0
  7. package/dist/anchor.d.ts +295 -0
  8. package/dist/anchor.mjs +2 -0
  9. package/dist/anchor.mjs.map +7 -0
  10. package/dist/arming.d.cts +30 -2
  11. package/dist/arming.d.mts +30 -2
  12. package/dist/arming.d.ts +30 -2
  13. package/dist/host.cjs +1 -1
  14. package/dist/host.cjs.map +1 -1
  15. package/dist/host.mjs.map +1 -1
  16. package/dist/index.cjs +4 -4
  17. package/dist/index.cjs.map +3 -3
  18. package/dist/index.d.cts +3 -3
  19. package/dist/index.d.mts +3 -3
  20. package/dist/index.d.ts +3 -3
  21. package/dist/index.mjs +4 -4
  22. package/dist/index.mjs.map +3 -3
  23. package/dist/markers.cjs +57 -0
  24. package/dist/markers.cjs.map +7 -0
  25. package/dist/markers.d.cts +246 -0
  26. package/dist/markers.d.mts +246 -0
  27. package/dist/markers.d.ts +246 -0
  28. package/dist/markers.mjs +57 -0
  29. package/dist/markers.mjs.map +7 -0
  30. package/dist/protocol.cjs +1 -1
  31. package/dist/protocol.cjs.map +3 -3
  32. package/dist/protocol.d.cts +29 -0
  33. package/dist/protocol.d.mts +29 -0
  34. package/dist/protocol.d.ts +29 -0
  35. package/dist/protocol.mjs +1 -1
  36. package/dist/protocol.mjs.map +3 -3
  37. package/dist/read.cjs +2 -0
  38. package/dist/read.cjs.map +7 -0
  39. package/dist/read.d.cts +149 -0
  40. package/dist/read.d.mts +149 -0
  41. package/dist/read.d.ts +149 -0
  42. package/dist/read.mjs +2 -0
  43. package/dist/read.mjs.map +7 -0
  44. package/dist/transport.d.cts +53 -1
  45. package/dist/transport.d.mts +53 -1
  46. package/dist/transport.d.ts +53 -1
  47. package/package.json +48 -5
package/ADOPTING.md CHANGED
@@ -334,6 +334,58 @@ frame opened on for the rest of the session.
334
334
 
335
335
  ---
336
336
 
337
+ ## 9. Show the markers other reviewers left (optional)
338
+
339
+ The toolbar WRITES. This reads back: an icon on each annotated component, and a
340
+ panel with the comment, who raised it, when, and what has happened to it.
341
+
342
+ ```tsx
343
+ const { readToken } = readArming(); // from `ai_read`, stripped and stored
344
+ if (!readToken) return; // a link minted before markers shipped
345
+
346
+ const { createAnnotationReader } = await import("@weatherboard/annotation/read");
347
+ const { mountAnnotationMarkers } = await import("@weatherboard/annotation/markers");
348
+
349
+ const layer = mountAnnotationMarkers({
350
+ reader: createAnnotationReader({
351
+ endpoint: "https://<console>/ingest/annotations",
352
+ readToken,
353
+ }),
354
+ });
355
+ await layer.refresh(); // and again after a route change
356
+ ```
357
+
358
+ **It is a second credential, not the capture token.** The console refuses a write
359
+ claim at the read endpoint and a read claim at the ingest, so handing
360
+ `captureToken` to the reader does not degrade to a read — it fails. The read
361
+ claim also lives **one hour** rather than four, so the toolbar outlives the
362
+ markers: a reviewer who leaves a tab open all afternoon finds the count line
363
+ saying it cannot read before they find Send broken. That ordering is deliberate —
364
+ the credential that discloses other people's words is the one that dies first.
365
+
366
+ **Expect most markers on a list page to be route-level.** Measured against live
367
+ pages: only about **25%** of annotated elements resolve uniquely, and the rest are
368
+ identical siblings a source ref genuinely cannot tell apart. The layer refuses to
369
+ draw on an ambiguous match — wrong-placement measured **zero** across every
370
+ mutation tested, and it is zero *because* it refuses — so markers that resolve to
371
+ the same element are drawn as one icon carrying a count, and the panel lists all
372
+ of them.
373
+
374
+ **The count line is the feature.** It renders whenever armed, before and after
375
+ the read, whatever the answer: *"3 annotations here, 1 shown"*. Zero markers is
376
+ exactly what "working, nothing here" looks like and a dozen distinct causes
377
+ produce it, so a layer that drew only icons would be silent in every one.
378
+
379
+ **`refresh()` never rejects.** A refused CORS preflight arrives as `TypeError:
380
+ Failed to fetch` with no status and no body; it becomes a sentence in the count
381
+ line rather than an exception in your page.
382
+
383
+ **None of this reaches a production bundle** as long as § 3's switch is a per-key
384
+ `NEXT_PUBLIC_*` read compared against a literal, so your bundler can fold the
385
+ branch and drop the dynamic imports. Passing `process.env` as a value defeats that
386
+ and every unit test still passes — see `bundle-gate.mjs` in this package, which
387
+ asserts both halves against a real emitted bundle.
388
+
337
389
  ## Troubleshooting, by symptom
338
390
 
339
391
  Everything below presents as **"waiting for the page to announce itself"**. Work
package/README.md CHANGED
@@ -20,7 +20,7 @@ adding to your supply chain.
20
20
  npm i @weatherboard/annotation
21
21
  ```
22
22
 
23
- ## Three entry points
23
+ ## Six entry points
24
24
 
25
25
  They are split by **who imports them**, not by topic.
26
26
 
@@ -29,6 +29,14 @@ They are split by **who imports them**, not by topic.
29
29
  | `@weatherboard/annotation` | The browser | The page SDK — overlay, target resolution, state collection, screenshots |
30
30
  | `@weatherboard/annotation/protocol` | Anywhere, no DOM | The wire names and the two readers. This is what a middleware imports |
31
31
  | `@weatherboard/annotation/host` | The reviewing console | The parent half of the channel |
32
+ | `@weatherboard/annotation/anchor` | The browser | `resolveAnchor` — where a capture's marker goes, or why it goes nowhere |
33
+ | `@weatherboard/annotation/read` | The browser | `createAnnotationReader` — the captures already made on this page |
34
+ | `@weatherboard/annotation/markers` | The browser | The marker layer and its panel |
35
+
36
+ The last three are separate for one reason: they run only in a product that
37
+ RENDERS markers, and a product that merely captures should not pay for them. They
38
+ are subpaths rather than a tree-shaking promise for the same reason `/protocol`
39
+ is.
32
40
 
33
41
  `/protocol` is a subpath rather than a tree-shaking promise on purpose: an edge
34
42
  middleware is often bundled as CJS, and CJS does not shake. Importing the root
@@ -0,0 +1,2 @@
1
+ "use strict";var f=Object.defineProperty;var x=Object.getOwnPropertyDescriptor;var E=Object.getOwnPropertyNames;var T=Object.prototype.hasOwnProperty;var R=(e,n)=>{for(var t in n)f(e,t,{get:n[t],enumerable:!0})},b=(e,n,t,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of E(n))!T.call(e,r)&&r!==t&&f(e,r,{get:()=>n[r],enumerable:!(o=x(n,r))||o.enumerable});return e};var y=e=>b(f({},"__esModule",{value:!0}),e);var L={};R(L,{anchorFromTarget:()=>S,resolveAnchor:()=>A,tallyAnchors:()=>_});module.exports=y(L);var u="data-src";function g(e){return e.selection==="region"?"region":"element"}var m=8;function s(e){if(!e)return null;let n=e.lastIndexOf(":");if(n<=0)return null;let t=e.lastIndexOf(":",n-1);if(t<=0)return null;let o=e.slice(0,t),r=Number(e.slice(t+1,n)),i=Number(e.slice(n+1));return!o||!Number.isFinite(r)||!Number.isFinite(i)?null:{file:o,line:r,column:i}}function d(e,n=m){let t=[],o=e;for(;o&&t.length<n;){let r=s(o.getAttribute(u));if(r){let i=t[t.length-1];i&&i.file===r.file&&i.line===r.line||t.push(r)}o=o.parentElement}return t}function h(e){let n=e;for(;n;){if(s(n.getAttribute(u)))return n;n=n.parentElement}return null}function l(e,n){return e.file!==n.file||e.line!==n.line?!1:e.column===void 0||n.column===void 0?!0:e.column===n.column}function k(e,n){if(e.length===0)return!1;if(e.length<m){if(n.length!==e.length)return!1}else if(n.length<e.length)return!1;return e.every((t,o)=>{let r=n[o];return r!==void 0&&l(t,r)})}function N(e,n){let t={file:e.file,line:e.line};e.column!==void 0&&(t.column=e.column);let o=n.querySelectorAll(`[${u}]`),r=[];for(let i=0;i<o.length;i++){let a=o[i],c=s(a.getAttribute(u));if(!c||!l(t,c))continue;let p=s(h(a.parentElement)?.getAttribute(u)??null);p&&l(p,c)||r.push(a)}return r}function A(e,n){switch(e.kind){case"route":{if(!e.path)return"none";let t=n.location?.pathname;return!t||t!==e.path?"none":n.body??"none"}case"dom-path":{if(!e.path)return"none";let t;try{t=n.querySelectorAll(e.path)}catch{return"none"}return t.length===0?"none":t.length>1?"ambiguous":t[0]}case"source-ref":{if(e.chain.length===0)return"none";let t=N(e,n).filter(o=>k(e.chain,d(o)));return t.length===0?"none":t.length>1?"ambiguous":t[0]}default:return"none"}}function S(e,n={}){let t=()=>n.path===void 0?{kind:"route"}:{kind:"route",path:n.path};if(g(e)==="region")return t();let o=e.sourceChain??[],r=o[0],i=e.source??r;if(i&&r&&l(i,r)){let a={kind:"source-ref",file:i.file,line:i.line,chain:o};return i.column!==void 0&&(a.column=i.column),n.ordinal!==void 0&&(a.ordinal=n.ordinal),a}return e.domPath?{kind:"dom-path",path:e.domPath}:t()}function _(e,n){let t={total:e.length,placed:0,ambiguous:0,unresolved:0};for(let o of e){let r=A(o,n);r==="ambiguous"?t.ambiguous+=1:r==="none"?t.unresolved+=1:t.placed+=1}return t}
2
+ //# sourceMappingURL=anchor.cjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/anchor.ts", "../src/protocol.ts", "../src/target.ts"],
4
+ "sourcesContent": ["/**\n * Putting a capture back on the element it came from (A-275).\n *\n * ===========================================================================\n * WHY THIS IS A PACKAGE EXPORT AND NOT A MEASUREMENT HARNESS\n * ===========================================================================\n *\n * The slice that produced this file was originally scoped as \"measure whether\n * anchoring can work\", with rendering explicitly out of scope. That was wrong,\n * and the reason is A-268's shape: resolving an anchor against a live DOM **is**\n * the marker-placement code. Measuring with one implementation and shipping\n * another later gives two implementations of one primitive, and two\n * implementations of one primitive is a way for them to disagree \u2014 which is the\n * principle `capture-token.ts` already names, and the defect A-268 already was.\n *\n * So `resolveAnchor` is the export the marker layer (A-277) imports, and the\n * measurement in A-275 is that same function called on staging pages.\n *\n * **The measurement and the decision it produced are in\n * `docs/decisions/a-275-anchor-placement.md`**, and `anchor-measure.mjs` runs it\n * again. Read the decision before changing anything here.\n *\n * Every figure in this file is quoted from that document with its denominator,\n * or is a property of the code rather than a measurement and says so. That rule\n * exists because it was broken here: two comments claimed `MEASURED: 105 of 200`\n * \u2014 a stale figure, from a SAMPLE the decision document explicitly retires, for a\n * branch it was not even a statistic about. **A number labelled MEASURED that no\n * checked-in artifact can reproduce is worse than no number**, which this\n * package's own size-budget note already says about a different number.\n *\n * The headline, so it is not paraphrased loosely elsewhere: **139 of 546\n * annotated elements on the staging home page resolve to exactly one element,\n * and 0 of 546 resolve to the wrong one.** Every plausible improvement to the\n * first figure is a way of trading the second one away.\n *\n * ===========================================================================\n * WHY `source_file:source_line` IS NOT AN ANCHOR\n * ===========================================================================\n *\n * A source ref identifies a **component**, not an **instance**. Six cards\n * rendered from one `<PubCard/>` all carry the same `data-src`, and the file and\n * line say nothing about which one a reviewer clicked.\n *\n * The first draft of this scheme fixed that with an ordinal \u2014 the element's\n * index among the matches, in document order. A reviewer showed that this is\n * **wrong rather than merely incomplete**, and the argument is worth keeping\n * because it is not obvious:\n *\n * An ordinal is POSITIONAL. Delete the second card, and a capture anchored to\n * ordinal 3 resolves to what used to be card 4. Exactly one match. A marker is\n * drawn, on the wrong element, and NOTHING ANYWHERE HAS A COMPLAINT \u2014 a\n * \"cannot be confidently placed\" rule never fires, because the failure IS a\n * confident single match.\n *\n * A marker on the wrong element does not degrade this feature, it inverts it:\n * the entire value of putting the conversation on the component is that\n * *\"this one, here\"* stops being ambiguous.\n *\n * ===========================================================================\n * SO: A DISCONFIRMING SIGNAL, NOT A UNIQUENESS TEST\n * ===========================================================================\n *\n * Uniqueness is satisfied by every silent failure above, so uniqueness cannot be\n * the test. What the anchor stores instead is the **whole source chain** \u2014\n * `TargetInfo.sourceChain`, every `data-src` from the clicked element up to the\n * root, innermost first, which the capture has carried since A-33 and which the\n * ingest has persisted since A-287 \u2014 and a candidate must match the chain, not\n * just the leaf.\n *\n * A reordered sibling still matches (its ancestors did not change). An element\n * that MOVED does not (its ancestors did). The chain is a claim the DOM can\n * contradict, and that is the only kind of claim worth storing.\n *\n * It does not make repeated siblings distinguishable, and it is not supposed to:\n * two identical cards in one list have identical chains, so an anchor to either\n * resolves `\"ambiguous\"`. That is the SAFE failure \u2014 the marker is withheld and\n * the count says so \u2014 and it is the one an ordinal would have converted into a\n * confident wrong answer.\n *\n * ===========================================================================\n * A TAGGED UNION FROM DAY ONE\n * ===========================================================================\n *\n * Not speculative generality: two capture kinds that cannot carry a usable\n * source ref ALREADY SHIP. `TargetInfo.domPath` is the documented fallback for a\n * page whose elements have no refs, and region captures (A-179) exist, where\n * `sourceChain` is the siblings a rectangle crossed rather than ancestors \u2014\n * a chain that contains nothing of itself and would be silently read as an\n * ancestor chain by anything that assumed one shape.\n *\n * Retrofitting a union onto flat columns after a year of rows is the expensive\n * version of this, and the read response (A-276) is additive-only forever, so\n * `kind` is what lets an older SDK skip a marker it does not understand rather\n * than misplace it.\n */\n\nimport {\n collectSourceChain,\n findAnnotatedAncestor,\n parseSourceRef,\n MAX_CHAIN,\n SRC_ATTR,\n type ElementLike,\n} from \"./target\";\nimport { selectionOf, type SourceRef, type TargetInfo } from \"./protocol\";\n\n/**\n * An element identified by the source location that rendered it, plus the chain\n * of source locations above it.\n *\n * `chain` is innermost-first and INCLUDES the leaf, exactly as\n * `collectSourceChain` produces it \u2014 one array, not a leaf plus a tail, because\n * two representations of one list is a way for them to disagree about whether\n * entry zero is the element or its parent.\n */\nexport interface SourceRefAnchor {\n kind: \"source-ref\";\n file: string;\n line: number;\n column?: number;\n chain: SourceRef[];\n /**\n * The element's index among the leaf-matching candidates at capture time.\n *\n * **Recorded, and deliberately never used to select.** It is here because\n * knowing \"this was the 3rd of 6\" is genuinely useful when a human is looking\n * at an unresolved anchor and asking what happened \u2014 and it is *not* here as a\n * tie-break, for the reason set out at length in this file's header. If you\n * are about to reach for it to turn an `\"ambiguous\"` into an element, that is\n * the bug this whole scheme was rewritten to avoid; `anchor.test.ts` has a\n * test that fails if you do.\n */\n ordinal?: number;\n}\n\n/** A CSS-ish path, for elements no build transform gave a ref. */\nexport interface DomPathAnchor {\n kind: \"dom-path\";\n path: string;\n}\n\n/**\n * \"Something on THIS page.\"\n *\n * First-class rather than a fallback of last resort: it is the honest home for a\n * region capture, for a canvas, for a PDF, and for any product that is not a JSX\n * tree.\n *\n * ===========================================================================\n * `path` IS NOT OPTIONAL DECORATION \u2014 IT IS WHAT MAKES \"THIS PAGE\" MEAN ANYTHING\n * ===========================================================================\n *\n * The first version of this interface had no fields at all and `resolveAnchor`\n * returned `doc.body` unconditionally, with a comment calling it *\"always\n * placeable\"*. A reviewer pointed out that this reintroduces, through the route\n * branch, exactly the failure the source-ref scheme was rewritten to prevent:\n *\n * A capture taken on `/guides/a` resolves CONFIDENTLY on `/guides/b`. One\n * match, marker drawn, wrong page, counted as `placed`. No signal anywhere.\n *\n * That is not a rate to be estimated. `return doc.body` has no input but the\n * document, so under it **every** route anchor placed on **every** page it was\n * shown \u2014 100%, by construction, and there is nothing to measure. The reason it\n * matters is `payload.page.route`: it is the matched PATTERN rather than the\n * URL, so \"the page this came from\" was never pinned in the first place. And\n * `anchorFromTarget` sends every region capture down this branch, so it is the\n * common case rather than the edge.\n *\n * The measured neighbour is the SOURCE-REF branch meeting the same problem:\n * 414 anchors captured on one guide page resolve **identically** after a real\n * navigation to another guide page \u2014 161 placed, 253 ambiguous, 0 refused, the\n * same three numbers on both \u2014 recorded with its method and denominator in\n * `docs/decisions/a-275-anchor-placement.md` \u00A7 *The limit this does not fix*.\n * It is a different branch and a different number, cited here as evidence that\n * the pattern-not-URL problem is real, not as a figure for this one.\n *\n * So a route anchor carries the RESOLVED path it was captured on, and\n * `resolveAnchor` refuses when the document is somewhere else.\n *\n * ===========================================================================\n * AND ABSENT MEANS \"CANNOT PLACE\", NEVER \"PLACE ANYWAY\"\n * ===========================================================================\n *\n * `path` is optional because the field is newer than the wire, and the read-back\n * plan's versioning rule for exactly this case is that a new anchor field is\n * optional and **absent means cannot place** \u2014 the precedent `selection?:` set.\n * A route anchor with no `path`, or a document that cannot say where it is,\n * therefore resolves to `\"none\"`.\n *\n * That is a deliberate choice to under-place rather than mis-place, and it costs\n * nothing today because no route anchor has ever been stored: markers have not\n * shipped. It would be a real cost if this were retrofitted a year from now,\n * which is the argument for doing it here.\n *\n * WHAT IT DOES NOT FIX: a SOURCE-REF anchor still resolves happily on a\n * different `[id]` of the same route pattern \u2014 the markup is identical, so there\n * is nothing for the chain to disagree with, and no amount of anchor design\n * closes it. That one is the read endpoint's (A-276): scope the query on the\n * resolved path, not on `route`. Stated here because an unstated limit gets read\n * as a covered one.\n */\nexport interface RouteAnchor {\n kind: \"route\";\n /** `location.pathname` at capture time. Absent means the anchor cannot be placed. */\n path?: string;\n}\n\nexport type Anchor = SourceRefAnchor | DomPathAnchor | RouteAnchor;\n\n/**\n * Where a marker goes, or why it does not go anywhere.\n *\n * Three outcomes and not two, because `\"none\"` and `\"ambiguous\"` are different\n * facts about the page and a caller counting them together loses the one that\n * says the markup moved.\n */\nexport type AnchorResolution<E extends ElementLike = ElementLike> = E | \"none\" | \"ambiguous\";\n\n/**\n * The narrowest slice of `Document` this module reads. A real `Document`\n * satisfies it, which `anchor.test.ts` asserts at compile time.\n *\n * `location` is here for the route branch above. It is optional because a parsed\n * fixture has no location, and a document that cannot say where it is makes a\n * route anchor unplaceable rather than placeable-by-default.\n */\nexport interface DocumentLike<E extends ElementLike = ElementLike> {\n querySelectorAll(selectors: string): ArrayLike<E>;\n body?: E | null;\n location?: { pathname: string } | null;\n}\n\nfunction sameRef(a: SourceRef, b: SourceRef): boolean {\n if (a.file !== b.file || a.line !== b.line) return false;\n /**\n * Column is compared only when BOTH sides have one.\n *\n * It is optional in `SourceRef` and the ingest drops a malformed one rather\n * than defaulting it (A-287), so an absent column means \"not recorded\" and\n * never \"column zero\". Treating a missing column as a mismatch would make\n * every capture from a build that omits it permanently unplaceable.\n */\n if (a.column === undefined || b.column === undefined) return true;\n return a.column === b.column;\n}\n\n/**\n * Does this candidate's live chain still match the one recorded at capture time?\n *\n * The length rule is the half that does the work, and it is asymmetric on\n * purpose:\n *\n * - A recorded chain SHORTER than `MAX_CHAIN` is complete \u2014 it ran out of\n * ancestors, not out of budget \u2014 so the live chain must be exactly as long.\n * An element that gained an annotated ancestor (a conditional wrapper, a\n * portal boundary, a new layout) is a moved element and must not match.\n * - A recorded chain AT `MAX_CHAIN` was truncated by `collectSourceChain`, so\n * all that can honestly be required is that the recorded frames are a prefix\n * of the live ones.\n *\n * THE SECOND CASE IS NOT WHERE THE REAL WEAKNESS LIVES, and an earlier version\n * of this comment said it was. An ancestor inserted above the eighth frame is\n * invisible because `collectSourceChain` never walked that far \u2014 the frame is\n * missing from the recorded chain AND from the live one, so no comparison here\n * can see it. MEASURED: making this length rule strict for truncated chains too\n * changes no test; raising `MAX_CHAIN` changes four.\n *\n * `anchor.test.ts` pins that ceiling under the name\n * *\"MAX_CHAIN truncation hides an ancestor added above the eighth frame\"*, so it\n * is an executable fact rather than a paragraph.\n */\nfunction chainMatches(recorded: SourceRef[], live: SourceRef[]): boolean {\n if (recorded.length === 0) return false;\n if (recorded.length < MAX_CHAIN) {\n if (live.length !== recorded.length) return false;\n } else if (live.length < recorded.length) {\n return false;\n }\n return recorded.every((ref, i) => { const other = live[i]; return other !== undefined && sameRef(ref, other); });\n}\n\n/**\n * Candidates for a source-ref anchor: every element whose OWN `data-src` is the\n * anchor's leaf, minus the nested repeats.\n *\n * One JSX element frequently produces several nested DOM nodes carrying the same\n * ref. `collectSourceChain` already collapses those when it builds a chain; not\n * collapsing them here would make a perfectly unambiguous element report\n * `\"ambiguous\"` against copies of itself \u2014 a false unplaceable, which is the\n * quiet way a scheme gets abandoned for being useless rather than for being\n * wrong. The outermost node of a repeat group is kept, because that is the one\n * whose box covers the component.\n */\nfunction leafCandidates<E extends ElementLike>(anchor: SourceRefAnchor, doc: DocumentLike<E>): E[] {\n const leaf: SourceRef = { file: anchor.file, line: anchor.line };\n if (anchor.column !== undefined) leaf.column = anchor.column;\n\n const all = doc.querySelectorAll(`[${SRC_ATTR}]`);\n const matched: E[] = [];\n for (let i = 0; i < all.length; i++) {\n const el = all[i] as E;\n const own = parseSourceRef(el.getAttribute(SRC_ATTR));\n if (!own || !sameRef(leaf, own)) continue;\n\n const parentRef = parseSourceRef(\n findAnnotatedAncestor(el.parentElement)?.getAttribute(SRC_ATTR) ?? null,\n );\n if (parentRef && sameRef(parentRef, own)) continue; // a nested repeat of the same ref\n\n matched.push(el);\n }\n return matched;\n}\n\n/**\n * Resolve an anchor against a document.\n *\n * Pure: it reads the document and returns an element or a refusal, and it never\n * mutates, measures layout, or draws anything. That is what lets the same\n * function be a unit test over a checked-in HTML fixture, a number in a\n * measurement run, and the marker layer's placement call.\n *\n * A `kind` this version does not recognise resolves to `\"none\"` \u2014 the read\n * response is additive-only forever (A-276), so an SDK meeting a newer console\n * must SKIP a marker it cannot place rather than guess at one.\n */\nexport function resolveAnchor<E extends ElementLike>(\n anchor: Anchor,\n doc: DocumentLike<E>,\n): AnchorResolution<E> {\n switch (anchor.kind) {\n case \"route\": {\n /**\n * Both sides must say where they are, and they must agree. See\n * `RouteAnchor` for why this is a refusal rather than a default.\n */\n if (!anchor.path) return \"none\";\n const here = doc.location?.pathname;\n if (!here || here !== anchor.path) return \"none\";\n return doc.body ?? \"none\";\n }\n\n case \"dom-path\": {\n if (!anchor.path) return \"none\";\n let found: ArrayLike<E>;\n try {\n found = doc.querySelectorAll(anchor.path);\n } catch {\n /**\n * `domPath` is documented as a hint for a human and explicitly not a\n * selector we promise to re-resolve \u2014 hashed class names can contain\n * characters that make it an invalid selector, and an invalid selector\n * THROWS rather than matching nothing. Refusing is right; letting a\n * `SyntaxError` out of a placement call would take the whole marker\n * layer down over one bad capture.\n */\n return \"none\";\n }\n if (found.length === 0) return \"none\";\n if (found.length > 1) return \"ambiguous\";\n return found[0] as E;\n }\n\n case \"source-ref\": {\n if (anchor.chain.length === 0) return \"none\";\n const matched = leafCandidates(anchor, doc).filter((el) =>\n chainMatches(anchor.chain, collectSourceChain(el)),\n );\n if (matched.length === 0) return \"none\";\n if (matched.length > 1) return \"ambiguous\";\n return matched[0] as E;\n }\n\n default:\n return \"none\";\n }\n}\n\nexport interface AnchorFromTargetOptions {\n /** Document order index among leaf-matching candidates, when the caller has a document. */\n ordinal?: number;\n /**\n * `location.pathname` at capture time \u2014 the RESOLVED path, not the route\n * pattern.\n *\n * Pass it. A route anchor built without it can never be placed, by design; see\n * `RouteAnchor`. It is optional here rather than required because\n * `anchorFromTarget` is also called for element captures, where it is unused.\n */\n path?: string;\n}\n\n/**\n * Build the anchor for a capture.\n *\n * The capture side of the same primitive, here rather than in `target.ts` so the\n * union and the function that produces it cannot drift apart.\n *\n * **A region capture becomes a `route` anchor.** Its `sourceChain` is the\n * siblings a rectangle crossed, which contain nothing of each other; handing\n * that to `chainMatches` would compare a sibling list against an ancestor list\n * and refuse \u2014 the right answer for the wrong reason, and one that would report\n * every region capture as \"the markup moved\". Route-level is what a region\n * capture actually means: something on this page, in that area.\n */\nexport function anchorFromTarget(\n target: Pick<TargetInfo, \"selection\" | \"source\" | \"sourceChain\" | \"domPath\">,\n options: AnchorFromTargetOptions = {},\n): Anchor {\n const routeAnchor = (): RouteAnchor =>\n options.path === undefined ? { kind: \"route\" } : { kind: \"route\", path: options.path };\n\n if (selectionOf(target) === \"region\") return routeAnchor();\n\n const chain = target.sourceChain ?? [];\n const head = chain[0];\n const leaf = target.source ?? head;\n if (leaf && head && sameRef(leaf, head)) {\n const anchor: SourceRefAnchor = {\n kind: \"source-ref\",\n file: leaf.file,\n line: leaf.line,\n chain,\n };\n if (leaf.column !== undefined) anchor.column = leaf.column;\n if (options.ordinal !== undefined) anchor.ordinal = options.ordinal;\n return anchor;\n }\n\n if (target.domPath) return { kind: \"dom-path\", path: target.domPath };\n return routeAnchor();\n}\n\n/**\n * The counts a caller reports, so that \"0 markers\" is never the same string as\n * \"working, nothing here\" (rule 1 of the read-back plan).\n *\n * ===========================================================================\n * `wrong` IS NOT IN HERE AND CANNOT BE, AND THAT IS A GAP RATHER THAN A DESIGN\n * ===========================================================================\n *\n * Whether a resolved element is the RIGHT element is not knowable from the live\n * page alone \u2014 it takes a before/after comparison, which is what A-275's\n * mutation battery does and what no runtime caller can do.\n *\n * So `placed` means \"resolved to exactly one element\", NOT \"resolved\n * correctly\", and there is one measured channel where those differ: a\n * source-ref anchor captured on one `[id]` resolves on another `[id]` of the\n * same route pattern, because the two pages are structurally identical.\n *\n * MEASURED at **161 of 414 anchors** placing on a different `[id]` of the same\n * route pattern, with zero refusals \u2014 indistinguishable, count for count, from\n * resolving against the page they were captured on. The method, the denominator\n * and the pages are in `docs/decisions/a-275-anchor-placement.md` \u00A7 *The limit\n * this does not fix*, and `node anchor-measure.mjs --url \u2026 --compare-url \u2026`\n * re-runs it in one command. Nothing in this module can detect it; the\n * fix is for the read endpoint to scope on the resolved path (A-276), so a\n * caller must not read `placed` as a correctness figure until it does.\n *\n * The route branch closes its own half of that (`RouteAnchor.path`). This\n * comment is the record that the source-ref half is still open.\n */\nexport interface AnchorTally {\n total: number;\n placed: number;\n ambiguous: number;\n unresolved: number;\n}\n\nexport function tallyAnchors<E extends ElementLike>(\n anchors: readonly Anchor[],\n doc: DocumentLike<E>,\n): AnchorTally {\n const tally: AnchorTally = { total: anchors.length, placed: 0, ambiguous: 0, unresolved: 0 };\n for (const anchor of anchors) {\n const result = resolveAnchor(anchor, doc);\n if (result === \"ambiguous\") tally.ambiguous += 1;\n else if (result === \"none\") tally.unresolved += 1;\n else tally.placed += 1;\n }\n return tally;\n}\n", "/**\n * The annotation postMessage protocol (A-36).\n *\n * Mirrors `docs/contracts/types.ts`. That file is the\n * cross-component contract; this is the runtime copy the product bundle ships,\n * because the product cannot import from a docs directory. Changing a shape\n * here is a change to both \u2014 say so in the PR.\n */\n\nexport const SDK_VERSION = \"1\";\n\n/**\n * ===========================================================================\n * THE ATTRIBUTES \u2014 THE OTHER WIRE (A-186)\n * ===========================================================================\n *\n * These live in `protocol.ts`, not in `target.ts` where they are read, because\n * they are a contract between TWO PACKAGES that a consumer installs separately:\n * `@weatherboard/annotation-next` WRITES them at build time and this package\n * READS them at runtime. Two spellings of `data-src` is not a bug anybody\n * catches \u2014 the transform runs, the attributes appear, and every capture comes\n * back with no source ref at all, which is indistinguishable from the transform\n * not running.\n *\n * `annotation-next` imports these from `@weatherboard/annotation/protocol`\n * rather than declaring its own, which is why the subpath has no DOM in it: a\n * build tool importing the page SDK to learn two strings would be absurd.\n */\nexport const SRC_ATTR = \"data-src\";\nexport const NAME_ATTR = \"data-src-name\";\n\nexport interface SourceRef {\n file: string;\n line: number;\n column?: number;\n}\n\nexport interface BuildInfo {\n /** Mandatory. Feedback not pinned to a revision is ambiguous the moment someone merges. */\n gitSha: string;\n /**\n * Where this build came from.\n *\n * `\"development\"` was added in A-37, when the SDK was first mounted in a\n * real app and the two halves turned out not to agree: `resolveBuildInfo` in\n * `resolveBuildInfo` in the product's own Next config package \u2014 the module\n * that stamps the build-env variable, and the only producer of this field \u2014\n * emits\n * `production | preview | development`, mirroring `VERCEL_ENV`. This union\n * instead offered `\"staging\"`, which nothing produces: a staging deploy IS a\n * Vercel preview and reports itself as one. Widening rather than forcing the\n * mount to lie: a locally-annotated build calling itself a preview would put\n * someone's laptop in the corpus as though it were a deployment.\n */\n env: \"production\" | \"preview\" | \"staging\" | \"development\";\n branch?: string;\n /** Set when reviewing an agent's preview deploy, so feedback routes to that run's session. */\n previewRunId?: string;\n}\n\nexport interface ConsoleEntry {\n level: \"error\" | \"warn\";\n message: string;\n stack?: string;\n at: string;\n}\n\nexport interface NetworkEntry {\n url: string;\n method: string;\n status: number;\n at: string;\n}\n\nexport interface TargetInfo {\n /**\n * What the reviewer selected \u2014 one element, or an area (A-179).\n *\n * -------------------------------------------------------------------------\n * WHY THIS EXISTS RATHER THAN BEING INFERRED\n * -------------------------------------------------------------------------\n *\n * A region capture and an element capture are the same SHAPE: a bounding box,\n * a chain of source refs, a DOM path. Nothing in the values distinguishes\n * them, and the two mean opposite things about the chain \u2014 for an element it\n * is ANCESTORS, innermost first, so entry two contains entry one; for a\n * region it is SIBLINGS the rectangle happened to cross, which contain\n * nothing of each other.\n *\n * A reader that guesses will describe a region's siblings as a call-site\n * chain, which is a confident false statement about the page. `describeCapture`\n * hands that description to a model that writes acceptance criteria from it.\n *\n * -------------------------------------------------------------------------\n * WHY IT IS OPTIONAL, AND WHY ABSENT MEANS `element`\n * -------------------------------------------------------------------------\n *\n * The two halves of this protocol live in different repositories and deploy\n * independently (see the note on the legacy parameter names below). Every\n * capture in the store today, and every capture from a product bundle that\n * predates region selection, has no such field \u2014 and all of them are element\n * captures. Absent therefore has to mean `element`, or this field would\n * retroactively make the entire history ambiguous.\n *\n * Required-with-a-default would have the same effect and a worse failure: an\n * older bundle omits it, the type says it is there, and every reader believes\n * a value nobody sent.\n */\n selection?: \"element\" | \"region\";\n source?: SourceRef;\n /**\n * Every `data-src` from the clicked element up to the document root, innermost\n * first \u2014 an addition to the contract, and the reason is structural.\n *\n * Only host elements carry a ref (A-33), so `source` names the file that\n * *writes the markup*. For a composed design-system component that is\n * `MediaCard.tsx`, not the `GuideDetailCard.tsx` a human would say they\n * clicked. The chain is what lets the PM agent and the coding agent see both,\n * and pick the call site over the leaf when the feedback is about content\n * rather than the component itself.\n */\n sourceChain?: SourceRef[];\n componentName?: string;\n /** CSS selector fallback, for when no ancestor carries a ref at all. */\n domPath: string;\n boundingBox: { x: number; y: number; w: number; h: number };\n /** Truncated to 200 characters. */\n textContent?: string;\n}\n\n/**\n * What kind of capture this is, with the default applied once (A-189).\n *\n * `selection` is optional and **absent means `element`** \u2014 every capture taken\n * before A-179, and everything the managed product's live bundle emits today,\n * has no such field. Any other default would retroactively reclassify the whole\n * history as regions, silently.\n *\n * A function rather than a documented convention because the default is the\n * kind of thing two readers implement slightly differently and neither notices:\n * one writes `=== \"region\"`, another writes `?? \"element\"`, a third forgets and\n * treats `undefined` as falsy in a branch that meant something else. This is\n * the protocol's answer, and `compatibility.test.ts` replays every recorded\n * payload through it.\n */\nexport function selectionOf(target: Pick<TargetInfo, \"selection\">): \"element\" | \"region\" {\n return target.selection === \"region\" ? \"region\" : \"element\";\n}\n\nexport interface AnnotationPayload {\n schemaVersion: 1;\n capturedAt: string;\n build: BuildInfo;\n page: {\n url: string;\n /** The matched route pattern, not the resolved URL. */\n route: string;\n viewport: { w: number; h: number; dpr: number };\n userAgent: string;\n };\n target: TargetInfo;\n state: {\n consoleErrors: ConsoleEntry[];\n failedRequests: NetworkEntry[];\n featureFlags: Record<string, unknown>;\n };\n screenshot?: { dataUrl: string; region: \"element\" | \"viewport\" };\n /** The human's words, verbatim. The parent frame fills this in; we never rewrite it. */\n comment: string;\n}\n\nexport type ParentToFrame =\n | { type: \"annotate:enable\" }\n | { type: \"annotate:disable\" }\n | { type: \"annotate:ping\" };\n\nexport type FrameToParent =\n | { type: \"annotate:ready\"; sdkVersion: string; build: BuildInfo }\n | { type: \"annotate:hover\"; target: TargetInfo }\n | { type: \"annotate:capture\"; payload: AnnotationPayload }\n | { type: \"annotate:cancel\" };\n\nconst PARENT_TYPES = new Set([\"annotate:enable\", \"annotate:disable\", \"annotate:ping\"]);\n\n/**\n * Is this a message we recognise?\n *\n * Origin is checked separately and first \u2014 a well-formed message from the wrong\n * origin is the case this guard must not be trusted to catch.\n */\nexport function isParentMessage(data: unknown): data is ParentToFrame {\n if (typeof data !== \"object\" || data === null) return false;\n const type = (data as { type?: unknown }).type;\n return typeof type === \"string\" && PARENT_TYPES.has(type);\n}\n\n/**\n * Reject wildcards outright rather than treating them as \"any origin\".\n *\n * `postMessage(msg, \"*\")` broadcasts the payload to whatever happens to be\n * framing us, and an annotation payload carries page content, console errors and\n * failed request URLs. The spec's rule is no wildcards in either direction; this\n * makes it impossible to configure one by accident.\n */\nexport function assertConcreteOrigin(origin: string): string {\n if (!origin || origin === \"*\") {\n throw new Error(\n \"[annotation] a concrete parent origin is required; '*' would broadcast \" +\n \"annotation payloads to any embedder.\",\n );\n }\n return origin;\n}\n\n/**\n * The query parameter that arms the SDK in a managed product, and the cookie\n * that records it.\n *\n * THESE LIVE IN THE PROTOCOL BECAUSE THE TWO HALVES ARE NOW IN DIFFERENT\n * REPOSITORIES. The managed product's middleware looks for the parameter and\n * sets the cookie; the management app appends the parameter and the SDK reads\n * the cookie. While both halves were one monorepo, a test could read the other\n * side's source and assert the strings matched \u2014 that gate does not survive a\n * repository split, and a mismatch produces no error at all: the frame loads,\n * the cookie is never set, the SDK never boots, and the reviewer sees \"waiting\n * for the page to announce itself\" with nothing to go on.\n *\n * So they stop being two spellings that agree and become one exported\n * constant. A managed product that imports this package cannot drift from it.\n */\nexport const ANNOTATION_TOKEN_PARAM = \"ai_annotate\";\nexport const ANNOTATION_ARMED_COOKIE = \"ai_annotate_armed\";\n\n/**\n * The CAPTURE token's query parameter (A-240).\n *\n * -------------------------------------------------------------------------\n * WHY IT IS HERE AND NOT WHERE IT IS WRITTEN\n * -------------------------------------------------------------------------\n *\n * A second name on the same wire, and a second credential \u2014 see\n * `docs/plans/first-party-annotation.md` \u00A7 *Authentication*. `ai_annotate`\n * answers *should this page offer an annotation UI at all*; this one answers\n * *may this capture become an issue*. Different secrets, different lifetimes,\n * different blast radii, and deliberately not folded into one token.\n *\n * It lives beside `ANNOTATION_TOKEN_PARAM` for that constant's own reason,\n * stated at length above: the console WRITES it into a deep link and the\n * product's bundle READS it, the two halves ship from different repositories,\n * and a mismatch produces no error anywhere \u2014 the reviewer writes a post-it,\n * clicks send, and the ingest rejects an unsigned capture. One exported\n * constant is the only thing that makes those two spellings unable to drift.\n *\n * It has no legacy spelling because it has never had another one: nothing has\n * shipped it yet. It is exported here BEFORE its writer needs it precisely so\n * the writer never has a reason to spell it itself.\n */\nexport const CAPTURE_TOKEN_PARAM = \"ai_capture\";\n\n/**\n * The run under review, when the console knows of one (A-241).\n *\n * Third name on the same wire, here for the reason the two above are: the\n * console writes it and the product's bundle reads it, from two repositories.\n * `apps/manager/src/lib/request-changes.ts` spells it itself today and its own\n * comment asks for exactly this \u2014 the constant to move into the package so the\n * writer has no reason to spell it. **That deletion is not this slice's**\n * (A-243/A-244 are merged and settled), so for now there are two definitions of\n * one string, and `protocol.test.ts` is the only thing standing between them\n * and a silent divergence. Nothing about it is signed: the ingest already\n * treats it as attacker-supplied text and files on it rather than routing on it.\n */\nexport const REVIEW_RUN_PARAM = \"ai_run\";\n\n/**\n * The READ token's query parameter (A-277).\n *\n * ===========================================================================\n * WHY THE MARKER LAYER GETS ITS OWN CREDENTIAL AND NOT `ai_capture`\n * ===========================================================================\n *\n * Fourth name on the same wire, and the reason it is a fourth is A-276's\n * disclosure decision rather than tidiness. The capture token is minted for\n * WRITING and lives four hours so a reviewer can work through a session; reusing\n * it for the read would make one leaked deep link a write capability AND a read\n * capability over every reviewer's comments on that origin for the same window.\n * The scope is a signed field, `verifyCaptureToken` requires an expectation at\n * every call site, and the read endpoint refuses a write claim \u2014 so handing\n * `ai_capture` to the reader does not degrade to a read, it fails.\n *\n * The read claim's TTL is ONE hour rather than four (`READ_TOKEN_TTL_S`), which\n * is the practical consequence a reader of this constant should know: the\n * toolbar outlives the markers, so a reviewer who leaves a tab open all\n * afternoon will find the count line saying it cannot read before they find the\n * Send button broken. That is the intended ordering \u2014 the shorter credential is\n * the one that discloses other people's words.\n *\n * Exported here for the reason the three above are: the console writes it into a\n * deep link and the product's bundle reads it, from two repositories, and a\n * mismatch produces no error anywhere \u2014 just a page with no markers, which is\n * indistinguishable from nine other causes.\n */\nexport const READ_TOKEN_PARAM = \"ai_read\";\n\n/**\n * The arming cookie, as a `Set-Cookie` value (A-241).\n *\n * ===========================================================================\n * IT GOT SIMPLER BY MOVING FIRST-PARTY, AND THAT IS THE WHOLE POINT\n * ===========================================================================\n *\n * Framed, this had to be `SameSite=None; Secure` with no `Partitioned` \u2014 a\n * genuine cross-site cookie, which A-211 records would have broken on its own\n * under Chrome's third-party cookie work, independently of the auth problem\n * that killed the frame. Top-level at the product's own origin it is an\n * ordinary cookie and none of that applies.\n *\n * Each attribute, and why:\n *\n * - **`SameSite=Lax`.** The reviewer arrives by clicking *Request changes* in\n * the console, which is a top-level cross-site GET navigation \u2014 the one case\n * `Lax` still sends on. `Strict` would withhold the cookie on that very first\n * render, so the toolbar would be missing on the page the link opened and\n * appear only after an internal click; that reads as a broken deploy.\n * - **`Secure`.** It is a marker rather than a credential, but a marker that\n * travels in clear is a marker an attacker on the path can set.\n * - **`Path=/`.** Arming survives the reviewer navigating the whole app, which\n * is the point of a cookie rather than a URL parameter.\n * - **No `Max-Age` / `Expires`.** Session-scoped: closing the tab disarms.\n *\n * ===========================================================================\n * WHAT IS *NOT* HERE: `HttpOnly`, AND THE TOKEN\n * ===========================================================================\n *\n * No `HttpOnly`, deliberately. Page script both READS this (`isAnnotationArmed`\n * decides whether a toolbar exists) and CLEARS it (*Done* disarms). An\n * `HttpOnly` arming cookie makes *Done* impossible from the page, which is the\n * one control the reviewer has.\n *\n * That is affordable only because THE VALUE IS A MARKER AND NEVER THE TOKEN.\n * The value is a constant and there is no argument that supplies one: the\n * middleware compares the URL parameter against its secret and then calls this,\n * and what it stores is *yes*, not *what was presented*. The single parameter\n * is the cookie's NAME, and it exists only so a product mid-migration can write\n * the legacy spelling \u2014 it is not a value slot wearing a different label, and\n * `arming.test.ts` pins which side of the `=` it lands on.\n *\n * This is a shape argument, not a guarantee about callers. Nothing stops a\n * determined caller passing a secret as the name; what the signature removes is\n * the ACCIDENT \u2014 the middleware author with a verified token in hand and one\n * parameter available, reaching for the obvious.\n */\nexport const ANNOTATION_ARMED_VALUE = \"1\";\n\nexport function armedCookie(name: string = ANNOTATION_ARMED_COOKIE): string {\n return `${name}=${ANNOTATION_ARMED_VALUE}; Path=/; SameSite=Lax; Secure`;\n}\n\n/**\n * The same cookie, expired \u2014 what *Done* and a disarm write.\n *\n * `Max-Age=0` AND an `Expires` in the past, because they are read by different\n * things and the pair is what every browser honours. The path must match the\n * one set above or the browser stores a second cookie and the first survives \u2014\n * a *Done* button that does nothing and reports success.\n */\nexport function clearedCookie(name: string): string {\n return `${name}=; Path=/; SameSite=Lax; Secure; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT`;\n}\n\n/**\n * The names these used to have (A-98).\n *\n * -------------------------------------------------------------------------\n * WHY THE RENAME, AND WHY IT COULD NOT JUST BE DONE\n * -------------------------------------------------------------------------\n *\n * They were `pits_annotate` and `pits_annotate_armed` \u2014 one managed product's\n * initialism, in a contract every managed product's bundle has to implement.\n * Onboarding a second product meant asking an unrelated codebase to adopt the\n * first product's name in its cookies and its query strings. That is the bug\n * A-98 is about, and it is a bug in a wire protocol rather than in a variable\n * name, which is what makes it expensive.\n *\n * The two halves live in DIFFERENT REPOSITORIES and deploy independently. A\n * clean rename is therefore a breaking change to every product bundle\n * simultaneously, and its failure mode is silence: the frame loads, the cookie\n * is never set, the SDK never boots, and the reviewer sees \"waiting for the\n * page to announce itself\" with nothing to go on. Nothing throws, nothing logs,\n * and the natural reading is that the agent broke the site.\n *\n * -------------------------------------------------------------------------\n * THE MIGRATION: READ BOTH, WRITE BOTH, THEN STOP WRITING THE OLD ONE\n * -------------------------------------------------------------------------\n *\n * 1. **Now.** Every reader accepts either name. Every writer emits BOTH, so a\n * product still running the old bundle arms on the legacy name and one\n * running the new bundle arms on the new one. Deploy order stops mattering,\n * which is the whole point \u2014 there is no window in which a reviewer sees the\n * silent failure above.\n * 2. **After every managed product's bundle is on this version** (A-102). Drop\n * the legacy names from the writers, then from the readers. Two steps, not\n * one: a reader that stops accepting the old name before the writers stop\n * emitting it re-creates the outage in the other direction.\n *\n * The legacy names are exported rather than inlined so the deletion in step 2\n * is `git grep LEGACY_` rather than an archaeology exercise.\n */\nexport const LEGACY_ANNOTATION_TOKEN_PARAM = \"pits_annotate\";\nexport const LEGACY_ANNOTATION_ARMED_COOKIE = \"pits_annotate_armed\";\n\n/**\n * ===========================================================================\n * AND THE NAMES ARE NOT CHANGING AGAIN FOR THE PUBLISHED PACKAGE (A-184)\n * ===========================================================================\n *\n * When this becomes `@weatherboard/annotation` the obvious next thought is that\n * the wire names should match the package \u2014 `weatherboard_annotate`. They\n * should not, and the reason is the migration described above rather than\n * taste.\n *\n * That migration is STILL IN FLIGHT. Readers accept both spellings; writers\n * emit both; step 2 waits on every managed product's bundle being current.\n * A third spelling introduced now does not replace the second, it joins it:\n * every reader accepts three names, every writer emits three, and the window in\n * which a product can be on any of them widens instead of closing.\n *\n * The cost is not the code. It is that each rename buys another instance of the\n * failure this file exists to prevent \u2014 the frame loads, the cookie is never\n * set, the SDK never boots, and the reviewer sees \"waiting for the page to\n * announce itself\" with nothing to go on. Twice is a migration. Three times is\n * a habit, and the third one would be paid by consumers who never asked for\n * either.\n *\n * `ai_annotate` is already product-neutral, which was the entire point of A-98.\n * A published package needs names that name no product; it does not need names\n * that name the package. Nobody reading a query string cares which npm scope\n * the library came from.\n *\n * The one real objection is collision: `ai_` is a common prefix and some other\n * tool could plausibly use it. That is survivable by construction \u2014 arming\n * requires the parameter to carry a token the product compares exactly, so a\n * coincidental `?ai_annotate=` from an unrelated tool arms nothing. A colliding\n * COOKIE cannot false-positive either; `isAnnotationArmed` matches on the\n * delimiter rather than by substring, for exactly this reason.\n *\n * If a rename is ever genuinely warranted, it happens ONCE, after step 2 has\n * landed and the reader accepts one name again \u2014 not layered on top of an\n * unfinished one.\n */\n\n/** Both spellings of the query parameter, current first. */\nexport const ANNOTATION_TOKEN_PARAMS = [\n ANNOTATION_TOKEN_PARAM,\n LEGACY_ANNOTATION_TOKEN_PARAM,\n] as const;\n\n/** Both spellings of the cookie, current first. */\nexport const ANNOTATION_ARMED_COOKIES = [\n ANNOTATION_ARMED_COOKIE,\n LEGACY_ANNOTATION_ARMED_COOKIE,\n] as const;\n\n/**\n * Whether a cookie jar carries the armed cookie, under either name.\n *\n * Delimiter-aware rather than a substring test: a cookie named\n * `not_ai_annotate_armed`, or another cookie whose VALUE contains the name,\n * satisfies `includes` \u2014 and arming an annotation channel on a coincidence is\n * not a failure anyone would think to look for.\n */\nexport function isAnnotationArmed(cookie: string): boolean {\n return cookie\n .split(\";\")\n .some((entry) => {\n const trimmed = entry.trimStart();\n return ANNOTATION_ARMED_COOKIES.some((name) => trimmed.startsWith(`${name}=`));\n });\n}\n\n/**\n * The arming token from a URL's query string, under either name.\n *\n * Current name wins when both are present. They should never disagree \u2014 the\n * management app writes both from one value \u2014 but if they ever do, the one this\n * version of the protocol owns is the one to believe.\n */\nexport function readAnnotationToken(params: URLSearchParams): string | null {\n for (const name of ANNOTATION_TOKEN_PARAMS) {\n const value = params.get(name);\n if (value !== null && value.length > 0) return value;\n }\n return null;\n}\n", "import { NAME_ATTR, SRC_ATTR, type SourceRef, type TargetInfo } from \"./protocol\";\n\n/**\n * Turning a clicked DOM element into something a coding agent can act on.\n *\n * Everything here is written against the narrowest possible slice of the DOM so\n * it can be tested without a browser \u2014 see `ElementLike`. The parts that need a\n * real browser (hit-testing, layout) live in `sdk.ts`.\n */\n\n/**\n * Re-exported, not declared. They moved to `protocol.ts` (A-186) because the\n * build transform in `@weatherboard/annotation-next` writes what this file\n * reads, and the two packages install separately. Kept exported from here so\n * every existing importer is unaffected.\n */\nexport { NAME_ATTR, SRC_ATTR };\n\nexport const MAX_TEXT = 200;\n/** Deep trees are common; a chain long enough to be useless is not worth sending. */\nexport const MAX_CHAIN = 8;\n\n/** The subset of `Element` this module reads. */\nexport interface ElementLike {\n tagName: string;\n id?: string;\n getAttribute(name: string): string | null;\n parentElement: ElementLike | null;\n classList?: { value?: string } | ArrayLike<string>;\n textContent?: string | null;\n}\n\n/**\n * Parse `path/to/File.tsx:42:7` into its parts.\n *\n * Split from the right: the line and column never contain a colon, and a path\n * conceivably might. Returns null rather than a half-parsed ref \u2014 a ref we\n * cannot read is worse than no ref, because downstream will believe it.\n */\nexport function parseSourceRef(value: string | null): SourceRef | null {\n if (!value) return null;\n\n const colIdx = value.lastIndexOf(\":\");\n if (colIdx <= 0) return null;\n const lineIdx = value.lastIndexOf(\":\", colIdx - 1);\n if (lineIdx <= 0) return null;\n\n const file = value.slice(0, lineIdx);\n const line = Number(value.slice(lineIdx + 1, colIdx));\n const column = Number(value.slice(colIdx + 1));\n\n if (!file || !Number.isFinite(line) || !Number.isFinite(column)) return null;\n return { file, line, column };\n}\n\n/**\n * Every source ref from `el` upwards, innermost first.\n *\n * Consecutive duplicates are collapsed: one JSX element often produces several\n * nested DOM nodes carrying the same ref, and repeating it says nothing.\n */\nexport function collectSourceChain(el: ElementLike | null, max = MAX_CHAIN): SourceRef[] {\n const chain: SourceRef[] = [];\n let node: ElementLike | null = el;\n\n while (node && chain.length < max) {\n const ref = parseSourceRef(node.getAttribute(SRC_ATTR));\n if (ref) {\n const prev = chain[chain.length - 1];\n const isRepeat = prev && prev.file === ref.file && prev.line === ref.line;\n if (!isRepeat) chain.push(ref);\n }\n node = node.parentElement;\n }\n\n return chain;\n}\n\n/** The nearest ancestor (or self) carrying a ref, which is the element a human means. */\nexport function findAnnotatedAncestor(el: ElementLike | null): ElementLike | null {\n let node: ElementLike | null = el;\n while (node) {\n if (parseSourceRef(node.getAttribute(SRC_ATTR))) return node;\n node = node.parentElement;\n }\n return null;\n}\n\nfunction classTokens(el: ElementLike): string[] {\n const list = el.classList as { value?: string } | undefined;\n const raw = typeof list?.value === \"string\" ? list.value : \"\";\n return raw.split(/\\s+/).filter(Boolean);\n}\n\n/**\n * A CSS-ish path to the element, used only when no ancestor carries a ref.\n *\n * Deliberately not guaranteed unique. It is a hint for a human reading the\n * payload, not a selector we promise to re-resolve \u2014 StyleX class names are\n * hashed and change between builds, so a path that looks precise would be\n * quietly wrong on the next deploy. IDs are kept because they survive; classes\n * are capped at two for readability.\n */\nexport function domPath(el: ElementLike | null, maxDepth = 6): string {\n const parts: string[] = [];\n let node: ElementLike | null = el;\n\n while (node && parts.length < maxDepth) {\n const tag = (node.tagName || \"\").toLowerCase();\n if (!tag || tag === \"html\") break;\n\n let part = tag;\n if (node.id) {\n // An id is unique on the page, so nothing above it adds information.\n parts.unshift(`${tag}#${node.id}`);\n return parts.join(\" > \");\n }\n const classes = classTokens(node).slice(0, 2);\n if (classes.length > 0) part += `.${classes.join(\".\")}`;\n parts.unshift(part);\n\n if (tag === \"body\") break;\n node = node.parentElement;\n }\n\n return parts.join(\" > \");\n}\n\n/** Collapse whitespace and truncate, so the payload carries a label rather than a page. */\nexport function summariseText(text: string | null | undefined): string | undefined {\n if (!text) return undefined;\n const collapsed = text.replace(/\\s+/g, \" \").trim();\n if (!collapsed) return undefined;\n return collapsed.length > MAX_TEXT ? `${collapsed.slice(0, MAX_TEXT - 1)}\u2026` : collapsed;\n}\n\nexport interface ResolveTargetOptions {\n boundingBox: { x: number; y: number; w: number; h: number };\n}\n\n/**\n * Build the `TargetInfo` for a clicked or hovered element.\n *\n * `source` is the nearest ref, which names the file that writes the markup \u2014\n * for a composed design-system component that is the design-system file, not\n * the call site. `sourceChain` carries the rest so the agent can choose.\n */\nexport function resolveTarget(el: ElementLike, options: ResolveTargetOptions): TargetInfo {\n const annotated = findAnnotatedAncestor(el);\n const chain = collectSourceChain(el);\n const source = chain[0];\n\n const target: TargetInfo = {\n domPath: domPath(el),\n boundingBox: options.boundingBox,\n };\n\n if (source) target.source = source;\n if (chain.length > 0) target.sourceChain = chain;\n\n const componentName = annotated?.getAttribute(NAME_ATTR);\n if (componentName) target.componentName = componentName;\n\n const text = summariseText(el.textContent);\n if (text) target.textContent = text;\n\n return target;\n}\n"],
5
+ "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,sBAAAE,EAAA,kBAAAC,EAAA,iBAAAC,IAAA,eAAAC,EAAAL,GC4BO,IAAMM,EAAW,WAqHjB,SAASC,EAAYC,EAA6D,CACvF,OAAOA,EAAO,YAAc,SAAW,SAAW,SACpD,CC/HO,IAAMC,EAAY,EAmBlB,SAASC,EAAeC,EAAwC,CACrE,GAAI,CAACA,EAAO,OAAO,KAEnB,IAAMC,EAASD,EAAM,YAAY,GAAG,EACpC,GAAIC,GAAU,EAAG,OAAO,KACxB,IAAMC,EAAUF,EAAM,YAAY,IAAKC,EAAS,CAAC,EACjD,GAAIC,GAAW,EAAG,OAAO,KAEzB,IAAMC,EAAOH,EAAM,MAAM,EAAGE,CAAO,EAC7BE,EAAO,OAAOJ,EAAM,MAAME,EAAU,EAAGD,CAAM,CAAC,EAC9CI,EAAS,OAAOL,EAAM,MAAMC,EAAS,CAAC,CAAC,EAE7C,MAAI,CAACE,GAAQ,CAAC,OAAO,SAASC,CAAI,GAAK,CAAC,OAAO,SAASC,CAAM,EAAU,KACjE,CAAE,KAAAF,EAAM,KAAAC,EAAM,OAAAC,CAAO,CAC9B,CAQO,SAASC,EAAmBC,EAAwBC,EAAMV,EAAwB,CACvF,IAAMW,EAAqB,CAAC,EACxBC,EAA2BH,EAE/B,KAAOG,GAAQD,EAAM,OAASD,GAAK,CACjC,IAAMG,EAAMZ,EAAeW,EAAK,aAAaE,CAAQ,CAAC,EACtD,GAAID,EAAK,CACP,IAAME,EAAOJ,EAAMA,EAAM,OAAS,CAAC,EAClBI,GAAQA,EAAK,OAASF,EAAI,MAAQE,EAAK,OAASF,EAAI,MACtDF,EAAM,KAAKE,CAAG,CAC/B,CACAD,EAAOA,EAAK,aACd,CAEA,OAAOD,CACT,CAGO,SAASK,EAAsBP,EAA4C,CAChF,IAAIG,EAA2BH,EAC/B,KAAOG,GAAM,CACX,GAAIX,EAAeW,EAAK,aAAaE,CAAQ,CAAC,EAAG,OAAOF,EACxDA,EAAOA,EAAK,aACd,CACA,OAAO,IACT,CFkJA,SAASK,EAAQC,EAAcC,EAAuB,CACpD,OAAID,EAAE,OAASC,EAAE,MAAQD,EAAE,OAASC,EAAE,KAAa,GAS/CD,EAAE,SAAW,QAAaC,EAAE,SAAW,OAAkB,GACtDD,EAAE,SAAWC,EAAE,MACxB,CA2BA,SAASC,EAAaC,EAAuBC,EAA4B,CACvE,GAAID,EAAS,SAAW,EAAG,MAAO,GAClC,GAAIA,EAAS,OAASE,GACpB,GAAID,EAAK,SAAWD,EAAS,OAAQ,MAAO,WACnCC,EAAK,OAASD,EAAS,OAChC,MAAO,GAET,OAAOA,EAAS,MAAM,CAACG,EAAKC,IAAM,CAAE,IAAMC,EAAQJ,EAAKG,CAAC,EAAG,OAAOC,IAAU,QAAaT,EAAQO,EAAKE,CAAK,CAAG,CAAC,CACjH,CAcA,SAASC,EAAsCC,EAAyBC,EAA2B,CACjG,IAAMC,EAAkB,CAAE,KAAMF,EAAO,KAAM,KAAMA,EAAO,IAAK,EAC3DA,EAAO,SAAW,SAAWE,EAAK,OAASF,EAAO,QAEtD,IAAMG,EAAMF,EAAI,iBAAiB,IAAIG,CAAQ,GAAG,EAC1CC,EAAe,CAAC,EACtB,QAAS,EAAI,EAAG,EAAIF,EAAI,OAAQ,IAAK,CACnC,IAAMG,EAAKH,EAAI,CAAC,EACVI,EAAMC,EAAeF,EAAG,aAAaF,CAAQ,CAAC,EACpD,GAAI,CAACG,GAAO,CAAClB,EAAQa,EAAMK,CAAG,EAAG,SAEjC,IAAME,EAAYD,EAChBE,EAAsBJ,EAAG,aAAa,GAAG,aAAaF,CAAQ,GAAK,IACrE,EACIK,GAAapB,EAAQoB,EAAWF,CAAG,GAEvCF,EAAQ,KAAKC,CAAE,CACjB,CACA,OAAOD,CACT,CAcO,SAASM,EACdX,EACAC,EACqB,CACrB,OAAQD,EAAO,KAAM,CACnB,IAAK,QAAS,CAKZ,GAAI,CAACA,EAAO,KAAM,MAAO,OACzB,IAAMY,EAAOX,EAAI,UAAU,SAC3B,MAAI,CAACW,GAAQA,IAASZ,EAAO,KAAa,OACnCC,EAAI,MAAQ,MACrB,CAEA,IAAK,WAAY,CACf,GAAI,CAACD,EAAO,KAAM,MAAO,OACzB,IAAIa,EACJ,GAAI,CACFA,EAAQZ,EAAI,iBAAiBD,EAAO,IAAI,CAC1C,MAAQ,CASN,MAAO,MACT,CACA,OAAIa,EAAM,SAAW,EAAU,OAC3BA,EAAM,OAAS,EAAU,YACtBA,EAAM,CAAC,CAChB,CAEA,IAAK,aAAc,CACjB,GAAIb,EAAO,MAAM,SAAW,EAAG,MAAO,OACtC,IAAMK,EAAUN,EAAeC,EAAQC,CAAG,EAAE,OAAQK,GAClDd,EAAaQ,EAAO,MAAOc,EAAmBR,CAAE,CAAC,CACnD,EACA,OAAID,EAAQ,SAAW,EAAU,OAC7BA,EAAQ,OAAS,EAAU,YACxBA,EAAQ,CAAC,CAClB,CAEA,QACE,MAAO,MACX,CACF,CA6BO,SAASU,EACdC,EACAC,EAAmC,CAAC,EAC5B,CACR,IAAMC,EAAc,IAClBD,EAAQ,OAAS,OAAY,CAAE,KAAM,OAAQ,EAAI,CAAE,KAAM,QAAS,KAAMA,EAAQ,IAAK,EAEvF,GAAIE,EAAYH,CAAM,IAAM,SAAU,OAAOE,EAAY,EAEzD,IAAME,EAAQJ,EAAO,aAAe,CAAC,EAC/BK,EAAOD,EAAM,CAAC,EACdlB,EAAOc,EAAO,QAAUK,EAC9B,GAAInB,GAAQmB,GAAQhC,EAAQa,EAAMmB,CAAI,EAAG,CACvC,IAAMrB,EAA0B,CAC9B,KAAM,aACN,KAAME,EAAK,KACX,KAAMA,EAAK,KACX,MAAAkB,CACF,EACA,OAAIlB,EAAK,SAAW,SAAWF,EAAO,OAASE,EAAK,QAChDe,EAAQ,UAAY,SAAWjB,EAAO,QAAUiB,EAAQ,SACrDjB,CACT,CAEA,OAAIgB,EAAO,QAAgB,CAAE,KAAM,WAAY,KAAMA,EAAO,OAAQ,EAC7DE,EAAY,CACrB,CAsCO,SAASI,EACdC,EACAtB,EACa,CACb,IAAMuB,EAAqB,CAAE,MAAOD,EAAQ,OAAQ,OAAQ,EAAG,UAAW,EAAG,WAAY,CAAE,EAC3F,QAAWvB,KAAUuB,EAAS,CAC5B,IAAME,EAASd,EAAcX,EAAQC,CAAG,EACpCwB,IAAW,YAAaD,EAAM,WAAa,EACtCC,IAAW,OAAQD,EAAM,YAAc,EAC3CA,EAAM,QAAU,CACvB,CACA,OAAOA,CACT",
6
+ "names": ["anchor_exports", "__export", "anchorFromTarget", "resolveAnchor", "tallyAnchors", "__toCommonJS", "SRC_ATTR", "selectionOf", "target", "MAX_CHAIN", "parseSourceRef", "value", "colIdx", "lineIdx", "file", "line", "column", "collectSourceChain", "el", "max", "chain", "node", "ref", "SRC_ATTR", "prev", "findAnnotatedAncestor", "sameRef", "a", "b", "chainMatches", "recorded", "live", "MAX_CHAIN", "ref", "i", "other", "leafCandidates", "anchor", "doc", "leaf", "all", "SRC_ATTR", "matched", "el", "own", "parseSourceRef", "parentRef", "findAnnotatedAncestor", "resolveAnchor", "here", "found", "collectSourceChain", "anchorFromTarget", "target", "options", "routeAnchor", "selectionOf", "chain", "head", "tallyAnchors", "anchors", "tally", "result"]
7
+ }
@@ -0,0 +1,295 @@
1
+ /**
2
+ * Putting a capture back on the element it came from (A-275).
3
+ *
4
+ * ===========================================================================
5
+ * WHY THIS IS A PACKAGE EXPORT AND NOT A MEASUREMENT HARNESS
6
+ * ===========================================================================
7
+ *
8
+ * The slice that produced this file was originally scoped as "measure whether
9
+ * anchoring can work", with rendering explicitly out of scope. That was wrong,
10
+ * and the reason is A-268's shape: resolving an anchor against a live DOM **is**
11
+ * the marker-placement code. Measuring with one implementation and shipping
12
+ * another later gives two implementations of one primitive, and two
13
+ * implementations of one primitive is a way for them to disagree — which is the
14
+ * principle `capture-token.ts` already names, and the defect A-268 already was.
15
+ *
16
+ * So `resolveAnchor` is the export the marker layer (A-277) imports, and the
17
+ * measurement in A-275 is that same function called on staging pages.
18
+ *
19
+ * **The measurement and the decision it produced are in
20
+ * `docs/decisions/a-275-anchor-placement.md`**, and `anchor-measure.mjs` runs it
21
+ * again. Read the decision before changing anything here.
22
+ *
23
+ * Every figure in this file is quoted from that document with its denominator,
24
+ * or is a property of the code rather than a measurement and says so. That rule
25
+ * exists because it was broken here: two comments claimed `MEASURED: 105 of 200`
26
+ * — a stale figure, from a SAMPLE the decision document explicitly retires, for a
27
+ * branch it was not even a statistic about. **A number labelled MEASURED that no
28
+ * checked-in artifact can reproduce is worse than no number**, which this
29
+ * package's own size-budget note already says about a different number.
30
+ *
31
+ * The headline, so it is not paraphrased loosely elsewhere: **139 of 546
32
+ * annotated elements on the staging home page resolve to exactly one element,
33
+ * and 0 of 546 resolve to the wrong one.** Every plausible improvement to the
34
+ * first figure is a way of trading the second one away.
35
+ *
36
+ * ===========================================================================
37
+ * WHY `source_file:source_line` IS NOT AN ANCHOR
38
+ * ===========================================================================
39
+ *
40
+ * A source ref identifies a **component**, not an **instance**. Six cards
41
+ * rendered from one `<PubCard/>` all carry the same `data-src`, and the file and
42
+ * line say nothing about which one a reviewer clicked.
43
+ *
44
+ * The first draft of this scheme fixed that with an ordinal — the element's
45
+ * index among the matches, in document order. A reviewer showed that this is
46
+ * **wrong rather than merely incomplete**, and the argument is worth keeping
47
+ * because it is not obvious:
48
+ *
49
+ * An ordinal is POSITIONAL. Delete the second card, and a capture anchored to
50
+ * ordinal 3 resolves to what used to be card 4. Exactly one match. A marker is
51
+ * drawn, on the wrong element, and NOTHING ANYWHERE HAS A COMPLAINT — a
52
+ * "cannot be confidently placed" rule never fires, because the failure IS a
53
+ * confident single match.
54
+ *
55
+ * A marker on the wrong element does not degrade this feature, it inverts it:
56
+ * the entire value of putting the conversation on the component is that
57
+ * *"this one, here"* stops being ambiguous.
58
+ *
59
+ * ===========================================================================
60
+ * SO: A DISCONFIRMING SIGNAL, NOT A UNIQUENESS TEST
61
+ * ===========================================================================
62
+ *
63
+ * Uniqueness is satisfied by every silent failure above, so uniqueness cannot be
64
+ * the test. What the anchor stores instead is the **whole source chain** —
65
+ * `TargetInfo.sourceChain`, every `data-src` from the clicked element up to the
66
+ * root, innermost first, which the capture has carried since A-33 and which the
67
+ * ingest has persisted since A-287 — and a candidate must match the chain, not
68
+ * just the leaf.
69
+ *
70
+ * A reordered sibling still matches (its ancestors did not change). An element
71
+ * that MOVED does not (its ancestors did). The chain is a claim the DOM can
72
+ * contradict, and that is the only kind of claim worth storing.
73
+ *
74
+ * It does not make repeated siblings distinguishable, and it is not supposed to:
75
+ * two identical cards in one list have identical chains, so an anchor to either
76
+ * resolves `"ambiguous"`. That is the SAFE failure — the marker is withheld and
77
+ * the count says so — and it is the one an ordinal would have converted into a
78
+ * confident wrong answer.
79
+ *
80
+ * ===========================================================================
81
+ * A TAGGED UNION FROM DAY ONE
82
+ * ===========================================================================
83
+ *
84
+ * Not speculative generality: two capture kinds that cannot carry a usable
85
+ * source ref ALREADY SHIP. `TargetInfo.domPath` is the documented fallback for a
86
+ * page whose elements have no refs, and region captures (A-179) exist, where
87
+ * `sourceChain` is the siblings a rectangle crossed rather than ancestors —
88
+ * a chain that contains nothing of itself and would be silently read as an
89
+ * ancestor chain by anything that assumed one shape.
90
+ *
91
+ * Retrofitting a union onto flat columns after a year of rows is the expensive
92
+ * version of this, and the read response (A-276) is additive-only forever, so
93
+ * `kind` is what lets an older SDK skip a marker it does not understand rather
94
+ * than misplace it.
95
+ */
96
+ import { type ElementLike } from "./target.cjs";
97
+ import { type SourceRef, type TargetInfo } from "./protocol.cjs";
98
+ /**
99
+ * An element identified by the source location that rendered it, plus the chain
100
+ * of source locations above it.
101
+ *
102
+ * `chain` is innermost-first and INCLUDES the leaf, exactly as
103
+ * `collectSourceChain` produces it — one array, not a leaf plus a tail, because
104
+ * two representations of one list is a way for them to disagree about whether
105
+ * entry zero is the element or its parent.
106
+ */
107
+ export interface SourceRefAnchor {
108
+ kind: "source-ref";
109
+ file: string;
110
+ line: number;
111
+ column?: number;
112
+ chain: SourceRef[];
113
+ /**
114
+ * The element's index among the leaf-matching candidates at capture time.
115
+ *
116
+ * **Recorded, and deliberately never used to select.** It is here because
117
+ * knowing "this was the 3rd of 6" is genuinely useful when a human is looking
118
+ * at an unresolved anchor and asking what happened — and it is *not* here as a
119
+ * tie-break, for the reason set out at length in this file's header. If you
120
+ * are about to reach for it to turn an `"ambiguous"` into an element, that is
121
+ * the bug this whole scheme was rewritten to avoid; `anchor.test.ts` has a
122
+ * test that fails if you do.
123
+ */
124
+ ordinal?: number;
125
+ }
126
+ /** A CSS-ish path, for elements no build transform gave a ref. */
127
+ export interface DomPathAnchor {
128
+ kind: "dom-path";
129
+ path: string;
130
+ }
131
+ /**
132
+ * "Something on THIS page."
133
+ *
134
+ * First-class rather than a fallback of last resort: it is the honest home for a
135
+ * region capture, for a canvas, for a PDF, and for any product that is not a JSX
136
+ * tree.
137
+ *
138
+ * ===========================================================================
139
+ * `path` IS NOT OPTIONAL DECORATION — IT IS WHAT MAKES "THIS PAGE" MEAN ANYTHING
140
+ * ===========================================================================
141
+ *
142
+ * The first version of this interface had no fields at all and `resolveAnchor`
143
+ * returned `doc.body` unconditionally, with a comment calling it *"always
144
+ * placeable"*. A reviewer pointed out that this reintroduces, through the route
145
+ * branch, exactly the failure the source-ref scheme was rewritten to prevent:
146
+ *
147
+ * A capture taken on `/guides/a` resolves CONFIDENTLY on `/guides/b`. One
148
+ * match, marker drawn, wrong page, counted as `placed`. No signal anywhere.
149
+ *
150
+ * That is not a rate to be estimated. `return doc.body` has no input but the
151
+ * document, so under it **every** route anchor placed on **every** page it was
152
+ * shown — 100%, by construction, and there is nothing to measure. The reason it
153
+ * matters is `payload.page.route`: it is the matched PATTERN rather than the
154
+ * URL, so "the page this came from" was never pinned in the first place. And
155
+ * `anchorFromTarget` sends every region capture down this branch, so it is the
156
+ * common case rather than the edge.
157
+ *
158
+ * The measured neighbour is the SOURCE-REF branch meeting the same problem:
159
+ * 414 anchors captured on one guide page resolve **identically** after a real
160
+ * navigation to another guide page — 161 placed, 253 ambiguous, 0 refused, the
161
+ * same three numbers on both — recorded with its method and denominator in
162
+ * `docs/decisions/a-275-anchor-placement.md` § *The limit this does not fix*.
163
+ * It is a different branch and a different number, cited here as evidence that
164
+ * the pattern-not-URL problem is real, not as a figure for this one.
165
+ *
166
+ * So a route anchor carries the RESOLVED path it was captured on, and
167
+ * `resolveAnchor` refuses when the document is somewhere else.
168
+ *
169
+ * ===========================================================================
170
+ * AND ABSENT MEANS "CANNOT PLACE", NEVER "PLACE ANYWAY"
171
+ * ===========================================================================
172
+ *
173
+ * `path` is optional because the field is newer than the wire, and the read-back
174
+ * plan's versioning rule for exactly this case is that a new anchor field is
175
+ * optional and **absent means cannot place** — the precedent `selection?:` set.
176
+ * A route anchor with no `path`, or a document that cannot say where it is,
177
+ * therefore resolves to `"none"`.
178
+ *
179
+ * That is a deliberate choice to under-place rather than mis-place, and it costs
180
+ * nothing today because no route anchor has ever been stored: markers have not
181
+ * shipped. It would be a real cost if this were retrofitted a year from now,
182
+ * which is the argument for doing it here.
183
+ *
184
+ * WHAT IT DOES NOT FIX: a SOURCE-REF anchor still resolves happily on a
185
+ * different `[id]` of the same route pattern — the markup is identical, so there
186
+ * is nothing for the chain to disagree with, and no amount of anchor design
187
+ * closes it. That one is the read endpoint's (A-276): scope the query on the
188
+ * resolved path, not on `route`. Stated here because an unstated limit gets read
189
+ * as a covered one.
190
+ */
191
+ export interface RouteAnchor {
192
+ kind: "route";
193
+ /** `location.pathname` at capture time. Absent means the anchor cannot be placed. */
194
+ path?: string;
195
+ }
196
+ export type Anchor = SourceRefAnchor | DomPathAnchor | RouteAnchor;
197
+ /**
198
+ * Where a marker goes, or why it does not go anywhere.
199
+ *
200
+ * Three outcomes and not two, because `"none"` and `"ambiguous"` are different
201
+ * facts about the page and a caller counting them together loses the one that
202
+ * says the markup moved.
203
+ */
204
+ export type AnchorResolution<E extends ElementLike = ElementLike> = E | "none" | "ambiguous";
205
+ /**
206
+ * The narrowest slice of `Document` this module reads. A real `Document`
207
+ * satisfies it, which `anchor.test.ts` asserts at compile time.
208
+ *
209
+ * `location` is here for the route branch above. It is optional because a parsed
210
+ * fixture has no location, and a document that cannot say where it is makes a
211
+ * route anchor unplaceable rather than placeable-by-default.
212
+ */
213
+ export interface DocumentLike<E extends ElementLike = ElementLike> {
214
+ querySelectorAll(selectors: string): ArrayLike<E>;
215
+ body?: E | null;
216
+ location?: {
217
+ pathname: string;
218
+ } | null;
219
+ }
220
+ /**
221
+ * Resolve an anchor against a document.
222
+ *
223
+ * Pure: it reads the document and returns an element or a refusal, and it never
224
+ * mutates, measures layout, or draws anything. That is what lets the same
225
+ * function be a unit test over a checked-in HTML fixture, a number in a
226
+ * measurement run, and the marker layer's placement call.
227
+ *
228
+ * A `kind` this version does not recognise resolves to `"none"` — the read
229
+ * response is additive-only forever (A-276), so an SDK meeting a newer console
230
+ * must SKIP a marker it cannot place rather than guess at one.
231
+ */
232
+ export declare function resolveAnchor<E extends ElementLike>(anchor: Anchor, doc: DocumentLike<E>): AnchorResolution<E>;
233
+ export interface AnchorFromTargetOptions {
234
+ /** Document order index among leaf-matching candidates, when the caller has a document. */
235
+ ordinal?: number;
236
+ /**
237
+ * `location.pathname` at capture time — the RESOLVED path, not the route
238
+ * pattern.
239
+ *
240
+ * Pass it. A route anchor built without it can never be placed, by design; see
241
+ * `RouteAnchor`. It is optional here rather than required because
242
+ * `anchorFromTarget` is also called for element captures, where it is unused.
243
+ */
244
+ path?: string;
245
+ }
246
+ /**
247
+ * Build the anchor for a capture.
248
+ *
249
+ * The capture side of the same primitive, here rather than in `target.ts` so the
250
+ * union and the function that produces it cannot drift apart.
251
+ *
252
+ * **A region capture becomes a `route` anchor.** Its `sourceChain` is the
253
+ * siblings a rectangle crossed, which contain nothing of each other; handing
254
+ * that to `chainMatches` would compare a sibling list against an ancestor list
255
+ * and refuse — the right answer for the wrong reason, and one that would report
256
+ * every region capture as "the markup moved". Route-level is what a region
257
+ * capture actually means: something on this page, in that area.
258
+ */
259
+ export declare function anchorFromTarget(target: Pick<TargetInfo, "selection" | "source" | "sourceChain" | "domPath">, options?: AnchorFromTargetOptions): Anchor;
260
+ /**
261
+ * The counts a caller reports, so that "0 markers" is never the same string as
262
+ * "working, nothing here" (rule 1 of the read-back plan).
263
+ *
264
+ * ===========================================================================
265
+ * `wrong` IS NOT IN HERE AND CANNOT BE, AND THAT IS A GAP RATHER THAN A DESIGN
266
+ * ===========================================================================
267
+ *
268
+ * Whether a resolved element is the RIGHT element is not knowable from the live
269
+ * page alone — it takes a before/after comparison, which is what A-275's
270
+ * mutation battery does and what no runtime caller can do.
271
+ *
272
+ * So `placed` means "resolved to exactly one element", NOT "resolved
273
+ * correctly", and there is one measured channel where those differ: a
274
+ * source-ref anchor captured on one `[id]` resolves on another `[id]` of the
275
+ * same route pattern, because the two pages are structurally identical.
276
+ *
277
+ * MEASURED at **161 of 414 anchors** placing on a different `[id]` of the same
278
+ * route pattern, with zero refusals — indistinguishable, count for count, from
279
+ * resolving against the page they were captured on. The method, the denominator
280
+ * and the pages are in `docs/decisions/a-275-anchor-placement.md` § *The limit
281
+ * this does not fix*, and `node anchor-measure.mjs --url … --compare-url …`
282
+ * re-runs it in one command. Nothing in this module can detect it; the
283
+ * fix is for the read endpoint to scope on the resolved path (A-276), so a
284
+ * caller must not read `placed` as a correctness figure until it does.
285
+ *
286
+ * The route branch closes its own half of that (`RouteAnchor.path`). This
287
+ * comment is the record that the source-ref half is still open.
288
+ */
289
+ export interface AnchorTally {
290
+ total: number;
291
+ placed: number;
292
+ ambiguous: number;
293
+ unresolved: number;
294
+ }
295
+ export declare function tallyAnchors<E extends ElementLike>(anchors: readonly Anchor[], doc: DocumentLike<E>): AnchorTally;