Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

feat(extract): add a model-free schema extractor that resolves flat JSON-schema fields against snapshot nodes (PIN-391)

Luigi Agosti68c7dc56b171
diff --git a/docs/architecture/extract.md b/docs/architecture/extract.md
new file mode 100644
index 00000000..aabc1033
--- /dev/null
+++ b/docs/architecture/extract.md
@@ -0,0 +1,116 @@
+# Extract Architecture
+
+`internal/extract` fills a flat JSON schema against a captured accessibility
+snapshot. It sits between `find` (one element) and `scrape` (a whole site): an
+agent hands over a schema and gets typed data back, with per-field confidence so
+it can fall back to `find` where a field is uncertain.
+
+It is model-free and browserless. It reuses the same semantic matcher that backs
+`find` (`github.com/pinchtab/semantic`, lexical + feature-hash embedding, no
+network, no model download) over a node list it is handed. It never touches CDP.
+
+## Pipeline
+
+```text
+JSON schema ──ParseSchema──► Schema (ordered properties, resolved hints)
+node list ──canonical order (by ref)──► descriptors (semdesc.Build)
+ │
+ per property: build query ──► matcher.Find (TopK 1) ──► best ref + score
+ │
+ read value (Value|Text|Name, Checked for bool) ──► coerce to type
+ │
+ data + per-field {ref, score, confidence, source, reason}
+```
+
+## Schema subset
+
+The accepted schema is an `object` with `properties`. Each property is one of
+`string`, `number`, `integer`, `boolean`, or `array`. Per property the extractor
+honours:
+
+- `description` — matched alongside the property name as query text.
+- `required` — a required field that cannot be filled is listed in `missing`,
+ never invented.
+- `x-pinchtab-hint` — an explicit query or selector that overrides the
+ name-based query (see below).
+
+`ParseSchema` returns a typed `*UnsupportedError` naming the offending path for
+constructs outside the subset:
+
+- a non-`object` root (`type: array is not supported`),
+- a property typed `object` (`properties.price.type: object is not supported`),
+- an unknown type (`properties.price.type: decimal is not supported`),
+- nested `properties` on a property (`properties.price.properties: ...`),
+- a `css:` or `xpath:` hint, which needs a browser
+ (`properties.price.x-pinchtab-hint: ...`).
+
+`array` parses successfully but resolves to a missing field with reason
+`unsupported`; array-of-object resolution is a follow-up task.
+
+Property order is alphabetical, so `missing` and iteration are deterministic.
+
+## Field resolution
+
+For each property the extractor builds a query and takes the single best node
+above the threshold (default `0.3`, same as `find`):
+
+1. **Query.** A resolved `x-pinchtab-hint` wins. Otherwise the query is the
+ property name joined with its description.
+2. **Match.** The query runs through the shared combined matcher against the
+ descriptors. `best_ref` and `score` come straight from the matcher.
+3. **Read.** The matched node's value is read in priority order `Value`, `Text`,
+ `Name`; booleans consult the accessibility `Checked` state first.
+4. **Coerce.** The raw string is coerced to the schema type. A coercion failure
+ leaves the field missing with a reason — never a wrong-typed value.
+
+### Hints
+
+`x-pinchtab-hint` accepts either a bare query or a selector, restricted to the
+kinds a node list can answer without a browser:
+
+- a bare string → used verbatim as the query,
+- `find:` → the natural-language query,
+- `role:`, `label:`, `placeholder:`, `alt:`, `title:`, `testid:` → routed
+ through `selector.SemanticQuery` so the grammar stays single-sourced with the
+ action and `find` paths,
+- `text:` → the text as a query,
+- `ref:` (or a bare `eN`) → selects that node verbatim; a ref that is not in the
+ node list leaves the field missing with reason `ref_not_found`,
+- `css:` / `xpath:` → rejected by `ParseSchema` (they need a live DOM).
+
+A hint that resolves beats the name-based query, so an agent can pin an ambiguous
+field (e.g. a sale price among several prices) without renaming the schema.
+
+## Coercion rules
+
+- **string** — the trimmed raw value.
+- **number / integer** — currency symbols, thousands separators, and trailing
+ units are stripped; sign and decimal are kept. Both ASCII `-` and the Unicode
+ minus `−` (U+2212) are honoured. `integer` truncates toward zero. Examples:
+ `"$1,299.00"` → `1299`, `"−3.5 kg"` → `-3.5`, `"call for price"` → missing
+ with reason `not_numeric`.
+- **boolean** — the accessibility `Checked` state (`true`/`false`) first, then
+ the words `yes`/`no`/`true`/`false` in the read value. A `mixed` checkbox or an
+ unrelated string leaves the field missing with reason `not_boolean`.
+
+## Confidence
+
+Each field carries `ref`, `score`, and `confidence`. The confidence band comes
+from `semantic.CalibrateConfidence` — `high` (score ≥ 0.8), `medium` (≥ 0.6),
+`low` (below) — the same bands `find` reports, so the two cannot drift. An agent
+can fall back to `find` on a `low` field.
+
+## Determinism
+
+`Resolve` is deterministic. Before matching, the node list is copied and stably
+sorted into document order by ref (snapshot refs `e1`, `e2`, … are assigned in
+pre-order, so numeric ref order is document order). The same schema over the same
+nodes — in any input order — yields identical output; ties break on document
+order.
+
+## Descriptors
+
+Nodes are converted to matcher descriptors by `internal/semdesc`, the single
+source of the node-to-descriptor mapping shared with the `find` handler. The
+extractor has no browser, so it skips the DOM-metadata enrichment `find` applies
+to live snapshots and matches the node list as handed over.
diff --git a/internal/extract/coerce.go b/internal/extract/coerce.go
new file mode 100644
index 00000000..9e74333f
--- /dev/null
+++ b/internal/extract/coerce.go
@@ -0,0 +1,70 @@
+package extract
+
+import (
+ "strconv"
+ "strings"
+
+ "github.com/pinchtab/pinchtab/internal/bridge/observe"
+)
+
+// coerceNumber parses a display string into a float64, stripping currency
+// symbols, thousands separators, and trailing units while keeping sign and
+// decimal. "$1,299.00" -> 1299, "−3.5 kg" -> -3.5 (Unicode minus honoured),
+// "call for price" -> not numeric. ok is false when no digit is present.
+func coerceNumber(s string) (float64, bool) {
+ var b strings.Builder
+ sign := ""
+ seenDigit := false
+ seenDot := false
+ for _, r := range s {
+ switch {
+ case r >= '0' && r <= '9':
+ b.WriteRune(r)
+ seenDigit = true
+ case r == '.' && !seenDot:
+ b.WriteRune('.')
+ seenDot = true
+ case isMinus(r) && !seenDigit && sign == "":
+ sign = "-"
+ case r == '+' && !seenDigit && sign == "":
+ sign = "+"
+ default:
+ // currency, letters, spaces, thousands separators: dropped
+ }
+ }
+ if !seenDigit {
+ return 0, false
+ }
+ f, err := strconv.ParseFloat(sign+b.String(), 64)
+ if err != nil {
+ return 0, false
+ }
+ return f, true
+}
+
+// isMinus reports whether r is an ASCII hyphen-minus or the Unicode minus sign
+// (U+2212), which price and weight strings use interchangeably.
+func isMinus(r rune) bool {
+ return r == '-' || r == '−'
+}
+
+// coerceBool reads a boolean from a node: its accessibility checked state first,
+// then yes/no/true/false words in the read value. ok is false when neither
+// yields a decision (a mixed checkbox or an unrelated string).
+func coerceBool(node observe.A11yNode, value string) (bool, bool) {
+ switch node.Checked {
+ case observe.CheckedTrue:
+ return true, true
+ case observe.CheckedFalse:
+ return false, true
+ case observe.CheckedMixed:
+ return false, false
+ }
+ switch strings.ToLower(strings.TrimSpace(value)) {
+ case "true", "yes":
+ return true, true
+ case "false", "no":
+ return false, true
+ }
+ return false, false
+}
diff --git a/internal/extract/extract_test.go b/internal/extract/extract_test.go
new file mode 100644
index 00000000..82ba9cb4
--- /dev/null
+++ b/internal/extract/extract_test.go
@@ -0,0 +1,379 @@
+package extract
+
+import (
+ "encoding/json"
+ "math/rand"
+ "os"
+ "path/filepath"
+ "reflect"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/bridge/observe"
+)
+
+func loadSnapshot(t *testing.T, name string) []observe.A11yNode {
+ t.Helper()
+ data, err := os.ReadFile(filepath.Join("testdata", name))
+ if err != nil {
+ t.Fatalf("read testdata: %v", err)
+ }
+ var snap struct {
+ Nodes []observe.A11yNode `json:"nodes"`
+ }
+ if err := json.Unmarshal(data, &snap); err != nil {
+ t.Fatalf("decode testdata: %v", err)
+ }
+ return snap.Nodes
+}
+
+func TestResolve_FromSnapshotFixtures(t *testing.T) {
+ t.Run("product", func(t *testing.T) {
+ schema := mustSchema(t, `{"type":"object","required":["name","price","in_stock"],"properties":{
+ "name":{"type":"string","description":"product name","x-pinchtab-hint":"role:heading"},
+ "price":{"type":"number","description":"product price"},
+ "rating":{"type":"string","description":"product rating"},
+ "in_stock":{"type":"boolean","description":"in stock availability"},
+ "description":{"type":"string","description":"product description"}}}`)
+ got := Resolve(schema, loadSnapshot(t, "extract-product.json"), Options{})
+ want := map[string]any{
+ "name": "Sony WH-1000XM5 Wireless Headphones",
+ "price": 1299.0,
+ "rating": "4.7 out of 5",
+ "in_stock": true,
+ }
+ for k, v := range want {
+ if got.Data[k] != v {
+ t.Errorf("data[%q] = %#v, want %#v (%+v)", k, got.Data[k], v, got.Fields[k])
+ }
+ }
+ if len(got.Missing) != 0 {
+ t.Errorf("unexpected missing: %v", got.Missing)
+ }
+ })
+
+ t.Run("article", func(t *testing.T) {
+ schema := mustSchema(t, `{"type":"object","required":["title","author","date"],"properties":{
+ "title":{"type":"string","description":"article title","x-pinchtab-hint":"role:heading"},
+ "author":{"type":"string","description":"author name"},
+ "date":{"type":"string","description":"date published"}}}`)
+ got := Resolve(schema, loadSnapshot(t, "extract-article.json"), Options{})
+ want := map[string]any{
+ "title": "The Rise of Model-Free Extraction",
+ "author": "Jane Doe",
+ "date": "2026-09-12",
+ }
+ for k, v := range want {
+ if got.Data[k] != v {
+ t.Errorf("data[%q] = %#v, want %#v (%+v)", k, got.Data[k], v, got.Fields[k])
+ }
+ }
+ })
+}
+
+func productNodes() []observe.A11yNode {
+ return []observe.A11yNode{
+ {Ref: "e1", Role: "region", Name: "Product", Depth: 0},
+ {Ref: "e2", Role: "heading", Name: "Product name", Text: "Sony WH-1000XM5 Wireless Headphones", Depth: 1},
+ {Ref: "e3", Role: "text", Name: "Price", Text: "$1,299.00", Depth: 1},
+ {Ref: "e4", Role: "checkbox", Name: "In stock", Checked: observe.CheckedTrue, Depth: 1},
+ {Ref: "e5", Role: "text", Name: "Colour", Text: "Midnight Black", Depth: 1},
+ }
+}
+
+func articleNodes() []observe.A11yNode {
+ return []observe.A11yNode{
+ {Ref: "e1", Role: "article", Name: "Story", Depth: 0},
+ {Ref: "e2", Role: "heading", Name: "Article title", Text: "The Rise of Model-Free Extraction", Depth: 1},
+ {Ref: "e3", Role: "text", Name: "Author", Text: "Jane Doe", Depth: 1},
+ {Ref: "e4", Role: "text", Name: "Date published", Text: "2026-09-12", Depth: 1},
+ {Ref: "e5", Role: "text", Name: "Body", Text: "Lorem ipsum dolor sit amet.", Depth: 1},
+ }
+}
+
+func formNodes() []observe.A11yNode {
+ return []observe.A11yNode{
+ {Ref: "e1", Role: "form", Name: "Signup", Depth: 0},
+ {Ref: "e2", Role: "textbox", Name: "Email address", Value: "[email protected]", Depth: 1},
+ {Ref: "e3", Role: "textbox", Name: "Full name", Value: "Ada Lovelace", Depth: 1},
+ {Ref: "e4", Role: "checkbox", Name: "Subscribe to newsletter", Checked: observe.CheckedFalse, Depth: 1},
+ }
+}
+
+func mustSchema(t *testing.T, doc string) Schema {
+ t.Helper()
+ s, err := ParseSchema([]byte(doc))
+ if err != nil {
+ t.Fatalf("ParseSchema: %v", err)
+ }
+ return s
+}
+
+func TestResolve_TableFixtures(t *testing.T) {
+ tests := []struct {
+ name string
+ schema string
+ nodes []observe.A11yNode
+ wantData map[string]any
+ wantRefs map[string]string
+ missing []string
+ }{
+ {
+ name: "product page",
+ schema: `{"type":"object","required":["name","price","in_stock"],"properties":{
+ "name":{"type":"string","description":"product name"},
+ "price":{"type":"number","description":"product price"},
+ "in_stock":{"type":"boolean","description":"in stock availability"}}}`,
+ nodes: productNodes(),
+ wantData: map[string]any{
+ "name": "Sony WH-1000XM5 Wireless Headphones",
+ "price": 1299.0,
+ "in_stock": true,
+ },
+ wantRefs: map[string]string{"name": "e2", "price": "e3", "in_stock": "e4"},
+ },
+ {
+ name: "article",
+ schema: `{"type":"object","required":["title","author","date"],"properties":{
+ "title":{"type":"string","description":"article title"},
+ "author":{"type":"string","description":"author name"},
+ "date":{"type":"string","description":"date published"}}}`,
+ nodes: articleNodes(),
+ wantData: map[string]any{
+ "title": "The Rise of Model-Free Extraction",
+ "author": "Jane Doe",
+ "date": "2026-09-12",
+ },
+ wantRefs: map[string]string{"title": "e2", "author": "e3", "date": "e4"},
+ },
+ {
+ name: "form values and checkbox",
+ schema: `{"type":"object","required":["email","full_name","subscribe"],"properties":{
+ "email":{"type":"string","description":"email address"},
+ "full_name":{"type":"string","description":"full name"},
+ "subscribe":{"type":"boolean","description":"subscribe to newsletter"}}}`,
+ nodes: formNodes(),
+ wantData: map[string]any{
+ "email": "[email protected]",
+ "full_name": "Ada Lovelace",
+ "subscribe": false,
+ },
+ wantRefs: map[string]string{"email": "e2", "full_name": "e3", "subscribe": "e4"},
+ },
+ {
+ name: "required field absent",
+ schema: `{"type":"object","required":["title","telephone"],"properties":{
+ "title":{"type":"string","description":"article title"},
+ "telephone":{"type":"string","description":"telephone contact number"}}}`,
+ nodes: articleNodes(),
+ wantData: map[string]any{"title": "The Rise of Model-Free Extraction"},
+ wantRefs: map[string]string{"title": "e2"},
+ missing: []string{"telephone"},
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ schema := mustSchema(t, tc.schema)
+ got := Resolve(schema, tc.nodes, Options{})
+
+ for k, want := range tc.wantData {
+ if got.Data[k] != want {
+ t.Errorf("data[%q] = %#v, want %#v (field: %+v)", k, got.Data[k], want, got.Fields[k])
+ }
+ }
+ for k, want := range tc.wantRefs {
+ fr := got.Fields[k]
+ if fr.Ref != want {
+ t.Errorf("field[%q].Ref = %q, want %q (score %.3f, reason %q)", k, fr.Ref, want, fr.Score, fr.Reason)
+ }
+ if fr.Confidence == "" {
+ t.Errorf("field[%q].Confidence is empty", k)
+ }
+ }
+ if len(got.Missing) != len(tc.missing) || (len(got.Missing) > 0 && !reflect.DeepEqual(got.Missing, tc.missing)) {
+ t.Errorf("missing = %v, want %v", got.Missing, tc.missing)
+ }
+ for _, m := range tc.missing {
+ if _, present := got.Data[m]; present {
+ t.Errorf("missing field %q must not appear in data", m)
+ }
+ }
+ })
+ }
+}
+
+func TestResolve_FieldsCarryRefScoreConfidence(t *testing.T) {
+ schema := mustSchema(t, `{"type":"object","properties":{
+ "price":{"type":"number","description":"product price"}}}`)
+ got := Resolve(schema, productNodes(), Options{})
+ fr := got.Fields["price"]
+ if fr.Ref == "" {
+ t.Fatalf("expected a ref for price, got %+v", fr)
+ }
+ if fr.Score < 0.3 {
+ t.Errorf("expected score >= threshold, got %.3f", fr.Score)
+ }
+ switch fr.Confidence {
+ case "high", "medium", "low":
+ default:
+ t.Errorf("confidence band %q is not high/medium/low", fr.Confidence)
+ }
+}
+
+func TestCoerceNumber(t *testing.T) {
+ tests := []struct {
+ in string
+ want float64
+ ok bool
+ }{
+ {"$1,299.00", 1299, true},
+ {"−3.5 kg", -3.5, true}, // Unicode minus U+2212
+ {"-3.5 kg", -3.5, true}, // ASCII hyphen
+ {"call for price", 0, false},
+ {"42", 42, true},
+ {"1,000,000", 1000000, true},
+ {"", 0, false},
+ }
+ for _, tc := range tests {
+ got, ok := coerceNumber(tc.in)
+ if ok != tc.ok || (ok && got != tc.want) {
+ t.Errorf("coerceNumber(%q) = %v,%v; want %v,%v", tc.in, got, ok, tc.want, tc.ok)
+ }
+ }
+}
+
+func TestResolve_NotNumericLeavesFieldMissing(t *testing.T) {
+ nodes := []observe.A11yNode{
+ {Ref: "e1", Role: "region", Name: "Product", Depth: 0},
+ {Ref: "e2", Role: "text", Name: "Price", Text: "call for price", Depth: 1},
+ }
+ schema := mustSchema(t, `{"type":"object","required":["price"],"properties":{
+ "price":{"type":"number","description":"product price"}}}`)
+ got := Resolve(schema, nodes, Options{})
+ if _, present := got.Data["price"]; present {
+ t.Fatalf("price must be missing, got %#v", got.Data["price"])
+ }
+ if got.Fields["price"].Reason != reasonNotNumeric {
+ t.Errorf("reason = %q, want %q", got.Fields["price"].Reason, reasonNotNumeric)
+ }
+ if len(got.Missing) != 1 || got.Missing[0] != "price" {
+ t.Errorf("missing = %v, want [price]", got.Missing)
+ }
+}
+
+func TestResolve_HintSelectorBeatsName(t *testing.T) {
+ // Two plausible price-ish nodes; the name-based query would prefer the one
+ // literally named "Price", but the hint points at the sale price by role/name.
+ nodes := []observe.A11yNode{
+ {Ref: "e1", Role: "region", Name: "Product", Depth: 0},
+ {Ref: "e2", Role: "text", Name: "Price", Text: "$1,299.00", Depth: 1},
+ {Ref: "e3", Role: "text", Name: "Sale price", Text: "$999.00", Depth: 1},
+ }
+ withHint := mustSchema(t, `{"type":"object","properties":{
+ "price":{"type":"number","description":"product price","x-pinchtab-hint":"role:text Sale price"}}}`)
+ got := Resolve(withHint, nodes, Options{})
+ if got.Fields["price"].Ref != "e3" {
+ t.Fatalf("hint should select e3 (sale price), got %q (%.3f)", got.Fields["price"].Ref, got.Fields["price"].Score)
+ }
+ if got.Data["price"] != 999.0 {
+ t.Errorf("price = %#v, want 999", got.Data["price"])
+ }
+
+ // A bare query hint is used verbatim.
+ bare := mustSchema(t, `{"type":"object","properties":{
+ "price":{"type":"number","x-pinchtab-hint":"Sale price"}}}`)
+ if got := Resolve(bare, nodes, Options{}); got.Fields["price"].Ref != "e3" {
+ t.Errorf("bare hint should select e3, got %q", got.Fields["price"].Ref)
+ }
+}
+
+func TestResolve_Deterministic(t *testing.T) {
+ schema := mustSchema(t, `{"type":"object","required":["name","price","in_stock"],"properties":{
+ "name":{"type":"string","description":"product name"},
+ "price":{"type":"number","description":"product price"},
+ "in_stock":{"type":"boolean","description":"in stock availability"}}}`)
+
+ base := productNodes()
+ first := Resolve(schema, base, Options{})
+ second := Resolve(schema, base, Options{})
+ if !reflect.DeepEqual(first, second) {
+ t.Fatalf("Resolve is not stable across runs:\n%+v\n%+v", first, second)
+ }
+
+ shuffled := make([]observe.A11yNode, len(base))
+ copy(shuffled, base)
+ rng := rand.New(rand.NewSource(7))
+ rng.Shuffle(len(shuffled), func(i, j int) { shuffled[i], shuffled[j] = shuffled[j], shuffled[i] })
+ third := Resolve(schema, shuffled, Options{})
+ if !reflect.DeepEqual(first, third) {
+ t.Fatalf("Resolve differs under shuffled node order:\n%+v\n%+v", first, third)
+ }
+}
+
+func TestResolve_ArrayReportsUnsupported(t *testing.T) {
+ schema := mustSchema(t, `{"type":"object","required":["tags"],"properties":{
+ "tags":{"type":"array","description":"tag list"}}}`)
+ got := Resolve(schema, productNodes(), Options{})
+ if got.Fields["tags"].Reason != reasonUnsupported {
+ t.Errorf("array reason = %q, want %q", got.Fields["tags"].Reason, reasonUnsupported)
+ }
+ if _, present := got.Data["tags"]; present {
+ t.Errorf("unsupported array must not appear in data")
+ }
+ if len(got.Missing) != 1 || got.Missing[0] != "tags" {
+ t.Errorf("missing = %v, want [tags]", got.Missing)
+ }
+}
+
+func TestParseSchema_UnsupportedConstructs(t *testing.T) {
+ tests := []struct {
+ name string
+ doc string
+ wantPath string
+ }{
+ {"object property", `{"type":"object","properties":{"price":{"type":"object"}}}`, "properties.price.type"},
+ {"nested properties", `{"type":"object","properties":{"price":{"type":"string","properties":{"x":{"type":"string"}}}}}`, "properties.price.properties"},
+ {"unknown type", `{"type":"object","properties":{"price":{"type":"decimal"}}}`, "properties.price.type"},
+ {"non-object root", `{"type":"array","properties":{"price":{"type":"string"}}}`, "type"},
+ {"css hint", `{"type":"object","properties":{"price":{"type":"number","x-pinchtab-hint":"css:.price"}}}`, "properties.price.x-pinchtab-hint"},
+ {"xpath hint", `{"type":"object","properties":{"price":{"type":"number","x-pinchtab-hint":"xpath://span"}}}`, "properties.price.x-pinchtab-hint"},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ _, err := ParseSchema([]byte(tc.doc))
+ ue, ok := err.(*UnsupportedError)
+ if !ok {
+ t.Fatalf("expected *UnsupportedError, got %T (%v)", err, err)
+ }
+ if ue.Path != tc.wantPath {
+ t.Errorf("path = %q, want %q (full: %q)", ue.Path, tc.wantPath, ue.Error())
+ }
+ })
+ }
+}
+
+func TestParseSchema_ValidFlatSchema(t *testing.T) {
+ s := mustSchema(t, `{"type":"object","required":["name"],"properties":{
+ "name":{"type":"string","description":"product name"},
+ "price":{"type":"number","x-pinchtab-hint":"role:text Price"},
+ "in_stock":{"type":"boolean"}}}`)
+ if len(s.Properties) != 3 {
+ t.Fatalf("expected 3 properties, got %d", len(s.Properties))
+ }
+ // Deterministic (alphabetical) property order.
+ wantOrder := []string{"in_stock", "name", "price"}
+ for i, p := range s.Properties {
+ if p.Name != wantOrder[i] {
+ t.Errorf("property[%d] = %q, want %q", i, p.Name, wantOrder[i])
+ }
+ }
+ var name Property
+ for _, p := range s.Properties {
+ if p.Name == "name" {
+ name = p
+ }
+ }
+ if !name.Required {
+ t.Errorf("name should be required")
+ }
+}
diff --git a/internal/extract/resolve.go b/internal/extract/resolve.go
new file mode 100644
index 00000000..6fe7f837
--- /dev/null
+++ b/internal/extract/resolve.go
@@ -0,0 +1,298 @@
+package extract
+
+import (
+ "context"
+ "math"
+ "sort"
+ "strconv"
+ "strings"
+ "sync"
+
+ "github.com/pinchtab/pinchtab/internal/bridge/observe"
+ "github.com/pinchtab/pinchtab/internal/semdesc"
+ "github.com/pinchtab/semantic"
+)
+
+// Reasons a field is left missing rather than filled with a wrong-typed value.
+const (
+ reasonNoMatch = "no_match"
+ reasonNotNumeric = "not_numeric"
+ reasonNotBoolean = "not_boolean"
+ reasonUnsupported = "unsupported"
+ reasonRefNotFound = "ref_not_found"
+)
+
+// Field value sources, in the order they are tried.
+const (
+ sourceValue = "value"
+ sourceText = "text"
+ sourceName = "name"
+ sourceChecked = "checked"
+)
+
+// Options tunes resolution. Zero values fall back to the same defaults /find
+// uses (threshold 0.3, the shared combined matcher).
+type Options struct {
+ Threshold float64
+ LexicalWeight float64
+ EmbeddingWeight float64
+ // Matcher overrides the default combined matcher; nil uses the shared one.
+ Matcher semantic.ElementMatcher
+}
+
+// FieldResult is the per-field outcome. Ref/Score/Confidence let an agent fall
+// back to /find on a low-confidence field; Reason explains a missing field.
+type FieldResult struct {
+ Ref string `json:"ref,omitempty"`
+ Score float64 `json:"score"`
+ Confidence string `json:"confidence"`
+ Source string `json:"source,omitempty"`
+ Reason string `json:"reason,omitempty"`
+}
+
+// Result is the extraction outcome: typed data, per-field diagnostics, and the
+// required fields that could not be filled (never invented).
+type Result struct {
+ Data map[string]any `json:"data"`
+ Fields map[string]FieldResult `json:"fields"`
+ Missing []string `json:"missing"`
+}
+
+var (
+ defaultMatcherOnce sync.Once
+ defaultMatcher semantic.ElementMatcher
+)
+
+func sharedMatcher() semantic.ElementMatcher {
+ defaultMatcherOnce.Do(func() {
+ defaultMatcher = semantic.NewCombinedMatcher(semantic.NewHashingEmbedder(128))
+ })
+ return defaultMatcher
+}
+
+// Resolve fills each schema property against the node list. It is deterministic:
+// nodes are canonicalised to document order (by ref) before matching, so the
+// same schema over the same nodes — in any input order — yields identical output.
+func Resolve(schema Schema, nodes []observe.A11yNode, opts Options) Result {
+ if opts.Threshold <= 0 {
+ opts.Threshold = 0.3
+ }
+ matcher := opts.Matcher
+ if matcher == nil {
+ matcher = sharedMatcher()
+ }
+
+ ordered := canonicalOrder(nodes)
+ byRef := make(map[string]observe.A11yNode, len(ordered))
+ for _, n := range ordered {
+ byRef[n.Ref] = n
+ }
+ descs := semdesc.Build(ordered)
+
+ result := Result{
+ Data: map[string]any{},
+ Fields: map[string]FieldResult{},
+ }
+ for _, prop := range schema.Properties {
+ fr, value, ok := resolveField(prop, descs, byRef, matcher, opts)
+ result.Fields[prop.Name] = fr
+ if ok {
+ result.Data[prop.Name] = value
+ } else if prop.Required {
+ result.Missing = append(result.Missing, prop.Name)
+ }
+ }
+ sort.Strings(result.Missing)
+ return result
+}
+
+func resolveField(prop Property, descs []semantic.ElementDescriptor, byRef map[string]observe.A11yNode, matcher semantic.ElementMatcher, opts Options) (FieldResult, any, bool) {
+ if prop.Type == TypeArray {
+ return FieldResult{Confidence: semantic.CalibrateConfidence(0), Reason: reasonUnsupported}, nil, false
+ }
+
+ node, fr, ok := matchNode(prop, descs, byRef, matcher, opts)
+ if !ok {
+ return fr, nil, false
+ }
+
+ value, source, ok := readValue(prop.Type, node)
+ fr.Source = source
+ if !ok {
+ fr.Reason = coercionReason(prop.Type)
+ return fr, nil, false
+ }
+ return fr, value, true
+}
+
+// matchNode finds the best node for a property: a ref hint selects verbatim,
+// otherwise the matcher scores the name+description(+hint) query.
+func matchNode(prop Property, descs []semantic.ElementDescriptor, byRef map[string]observe.A11yNode, matcher semantic.ElementMatcher, opts Options) (observe.A11yNode, FieldResult, bool) {
+ if prop.hintKindResolved == hintRef {
+ node, found := byRef[prop.hintValue]
+ fr := FieldResult{Ref: prop.hintValue, Score: 1, Confidence: semantic.CalibrateConfidence(1), Source: "hint"}
+ if !found {
+ fr.Score = 0
+ fr.Confidence = semantic.CalibrateConfidence(0)
+ fr.Reason = reasonRefNotFound
+ return observe.A11yNode{}, fr, false
+ }
+ return node, fr, true
+ }
+
+ // TopK spans every descriptor and the winner is chosen here, not taken from
+ // res.BestRef: the combined matcher merges its lexical and embedding halves
+ // concurrently, so its tie ordering is not stable. Per-ref scores are, so a
+ // deterministic pick (score desc, then document order) makes Resolve stable.
+ res, err := matcher.Find(context.Background(), fieldQuery(prop), descs, semantic.FindOptions{
+ Threshold: opts.Threshold,
+ TopK: len(descs),
+ LexicalWeight: opts.LexicalWeight,
+ EmbeddingWeight: opts.EmbeddingWeight,
+ })
+ best, ok := pickBest(res.Matches)
+ score := roundScore(best.Score)
+ fr := FieldResult{Score: score, Confidence: semantic.CalibrateConfidence(score)}
+ if err != nil || !ok {
+ fr.Reason = reasonNoMatch
+ return observe.A11yNode{}, fr, false
+ }
+ fr.Ref = best.Ref
+ node, found := byRef[best.Ref]
+ if !found {
+ fr.Reason = reasonNoMatch
+ return observe.A11yNode{}, fr, false
+ }
+ return node, fr, true
+}
+
+// pickBest chooses the winning match deterministically: highest score, ties
+// broken by document order (numeric ref ascending). Scores are compared rounded
+// because the combined matcher's concurrent merge is only stable to ~1 ULP, so
+// two matches within rounding are a tie the ref order settles. ok is false when
+// empty.
+func pickBest(matches []semantic.ElementMatch) (semantic.ElementMatch, bool) {
+ best, ok := semantic.ElementMatch{}, false
+ var bestScore float64
+ for _, m := range matches {
+ s := roundScore(m.Score)
+ switch {
+ case !ok, s > bestScore, s == bestScore && refLess(m.Ref, best.Ref):
+ best, bestScore, ok = m, s, true
+ }
+ }
+ return best, ok
+}
+
+// roundScore quantises a heuristic score to 6 decimals so equal-in-practice
+// scores compare equal across runs despite the matcher's 1-ULP jitter.
+func roundScore(s float64) float64 {
+ return math.Round(s*1e6) / 1e6
+}
+
+// fieldQuery builds the matcher query. A resolved hint query wins over the
+// name-based query; otherwise name and description are combined.
+func fieldQuery(prop Property) string {
+ if prop.hintKindResolved == hintQuery {
+ return prop.hintValue
+ }
+ return strings.TrimSpace(prop.Name + " " + prop.Description)
+}
+
+// readValue reads the node's value for a type and coerces it. Priority is
+// Value, Text, Name; booleans consult Checked first. A coercion failure returns
+// ok=false so the field is left missing rather than wrong-typed.
+func readValue(t Type, node observe.A11yNode) (any, string, bool) {
+ if t == TypeBoolean {
+ if node.Checked == observe.CheckedTrue || node.Checked == observe.CheckedFalse || node.Checked == observe.CheckedMixed {
+ if b, ok := coerceBool(node, ""); ok {
+ return b, sourceChecked, true
+ }
+ return nil, sourceChecked, false
+ }
+ }
+
+ raw, source := rawValue(node)
+ if raw == "" {
+ return nil, "", false
+ }
+
+ switch t {
+ case TypeString:
+ return strings.TrimSpace(raw), source, true
+ case TypeNumber:
+ if f, ok := coerceNumber(raw); ok {
+ return f, source, true
+ }
+ return nil, source, false
+ case TypeInteger:
+ if f, ok := coerceNumber(raw); ok {
+ return int64(f), source, true
+ }
+ return nil, source, false
+ case TypeBoolean:
+ if b, ok := coerceBool(node, raw); ok {
+ return b, source, true
+ }
+ return nil, source, false
+ }
+ return nil, source, false
+}
+
+func rawValue(node observe.A11yNode) (string, string) {
+ switch {
+ case strings.TrimSpace(node.Value) != "":
+ return node.Value, sourceValue
+ case strings.TrimSpace(node.Text) != "":
+ return node.Text, sourceText
+ case strings.TrimSpace(node.Name) != "":
+ return node.Name, sourceName
+ }
+ return "", ""
+}
+
+func coercionReason(t Type) string {
+ switch t {
+ case TypeNumber, TypeInteger:
+ return reasonNotNumeric
+ case TypeBoolean:
+ return reasonNotBoolean
+ default:
+ return reasonNoMatch
+ }
+}
+
+// canonicalOrder returns a copy of nodes sorted into document order by ref, so
+// resolution is invariant to input node order. Snapshot refs ("e5", "e12") are
+// assigned in pre-order, so their numeric order is document order.
+func canonicalOrder(nodes []observe.A11yNode) []observe.A11yNode {
+ ordered := make([]observe.A11yNode, len(nodes))
+ copy(ordered, nodes)
+ sort.SliceStable(ordered, func(i, j int) bool {
+ return refLess(ordered[i].Ref, ordered[j].Ref)
+ })
+ return ordered
+}
+
+func refLess(a, b string) bool {
+ na, oka := refNum(a)
+ nb, okb := refNum(b)
+ if oka && okb {
+ return na < nb
+ }
+ if oka != okb {
+ return oka // numeric refs sort before non-numeric ones
+ }
+ return a < b
+}
+
+func refNum(ref string) (int, bool) {
+ if len(ref) < 2 || ref[0] != 'e' {
+ return 0, false
+ }
+ n, err := strconv.Atoi(ref[1:])
+ if err != nil {
+ return 0, false
+ }
+ return n, true
+}
diff --git a/internal/extract/schema.go b/internal/extract/schema.go
new file mode 100644
index 00000000..98f64d04
--- /dev/null
+++ b/internal/extract/schema.go
@@ -0,0 +1,185 @@
+// Package extract fills a flat JSON-schema against a captured accessibility
+// snapshot using the same semantic matcher that backs /find. It is model-free:
+// no network, no model download, no browser. Given a schema and a node list it
+// returns typed data plus per-field ref/score/confidence so an agent can fall
+// back to /find on a low-confidence field.
+package extract
+
+import (
+ "encoding/json"
+ "fmt"
+ "sort"
+ "strings"
+
+ "github.com/pinchtab/pinchtab/internal/selector"
+)
+
+// Type is a supported JSON-schema property type.
+type Type string
+
+const (
+ TypeString Type = "string"
+ TypeNumber Type = "number"
+ TypeInteger Type = "integer"
+ TypeBoolean Type = "boolean"
+ TypeArray Type = "array"
+)
+
+// hintKind classifies how a resolved x-pinchtab-hint drives matching.
+type hintKind int
+
+const (
+ hintNone hintKind = iota
+ hintQuery // a natural-language query string for the matcher
+ hintRef // a direct ref to select verbatim
+)
+
+// Property is one resolved schema property, ready to match.
+type Property struct {
+ Name string
+ Type Type
+ Description string
+ Required bool
+ Hint string
+
+ // hintKindResolved and hintValue are computed by ParseSchema so Resolve
+ // never re-parses the hint (and so hint errors surface at parse time).
+ hintKindResolved hintKind
+ hintValue string
+}
+
+// Schema is a parsed object schema with properties in a deterministic order.
+type Schema struct {
+ Properties []Property
+}
+
+// UnsupportedError names the schema path that carries an unsupported construct.
+type UnsupportedError struct {
+ Path string
+ Reason string
+}
+
+func (e *UnsupportedError) Error() string {
+ return fmt.Sprintf("%s: %s", e.Path, e.Reason)
+}
+
+// rawSchema mirrors the accepted JSON-schema subset for decoding.
+type rawSchema struct {
+ Type string `json:"type"`
+ Required []string `json:"required"`
+ Properties map[string]rawProperty `json:"properties"`
+}
+
+type rawProperty struct {
+ Type string `json:"type"`
+ Description string `json:"description"`
+ Hint string `json:"x-pinchtab-hint"`
+ Properties json.RawMessage `json:"properties"`
+}
+
+// ParseSchema parses a flat object schema. Unsupported constructs return an
+// *UnsupportedError naming the offending path (e.g.
+// "properties.price.type: object is not supported"). Arrays parse successfully
+// and are reported as unsupported at resolution time, per the follow-up task.
+func ParseSchema(data []byte) (Schema, error) {
+ var raw rawSchema
+ if err := json.Unmarshal(data, &raw); err != nil {
+ return Schema{}, fmt.Errorf("parse schema: %w", err)
+ }
+ if raw.Type != "" && raw.Type != "object" {
+ return Schema{}, &UnsupportedError{Path: "type", Reason: raw.Type + " is not supported"}
+ }
+ if len(raw.Properties) == 0 {
+ return Schema{}, &UnsupportedError{Path: "properties", Reason: "an object schema with properties is required"}
+ }
+
+ required := make(map[string]bool, len(raw.Required))
+ for _, name := range raw.Required {
+ required[name] = true
+ }
+
+ names := make([]string, 0, len(raw.Properties))
+ for name := range raw.Properties {
+ names = append(names, name)
+ }
+ sort.Strings(names)
+
+ props := make([]Property, 0, len(names))
+ for _, name := range names {
+ rp := raw.Properties[name]
+ prop, err := parseProperty(name, rp, required[name])
+ if err != nil {
+ return Schema{}, err
+ }
+ props = append(props, prop)
+ }
+ return Schema{Properties: props}, nil
+}
+
+func parseProperty(name string, rp rawProperty, required bool) (Property, error) {
+ path := "properties." + name
+ switch Type(rp.Type) {
+ case TypeString, TypeNumber, TypeInteger, TypeBoolean, TypeArray:
+ // supported (array resolves to unsupported, but parses)
+ case "":
+ return Property{}, &UnsupportedError{Path: path + ".type", Reason: "a property type is required"}
+ default:
+ return Property{}, &UnsupportedError{Path: path + ".type", Reason: rp.Type + " is not supported"}
+ }
+ if len(rp.Properties) > 0 {
+ return Property{}, &UnsupportedError{Path: path + ".properties", Reason: "nested object properties are not supported"}
+ }
+
+ prop := Property{
+ Name: name,
+ Type: Type(rp.Type),
+ Description: strings.TrimSpace(rp.Description),
+ Required: required,
+ Hint: strings.TrimSpace(rp.Hint),
+ }
+ if err := resolveHint(&prop, path); err != nil {
+ return Property{}, err
+ }
+ return prop, nil
+}
+
+// resolveHint validates x-pinchtab-hint against the selector kinds a node list
+// can answer and caches the matcher-ready form. css:/xpath: need a browser and
+// return an *UnsupportedError naming the property path.
+func resolveHint(prop *Property, path string) error {
+ hint := prop.Hint
+ if hint == "" {
+ prop.hintKindResolved = hintNone
+ return nil
+ }
+
+ hintPath := path + ".x-pinchtab-hint"
+ if !selector.HasKnownPrefix(hint) {
+ // A bare hint is a natural-language query verbatim.
+ prop.hintKindResolved = hintQuery
+ prop.hintValue = hint
+ return nil
+ }
+
+ sel := selector.Parse(hint)
+ switch sel.Kind {
+ case selector.KindCSS, selector.KindXPath:
+ return &UnsupportedError{Path: hintPath, Reason: string(sel.Kind) + " selectors need a browser and are not supported"}
+ case selector.KindText:
+ prop.hintKindResolved = hintQuery
+ prop.hintValue = sel.Value
+ return nil
+ case selector.KindRef:
+ prop.hintKindResolved = hintRef
+ prop.hintValue = sel.Value
+ return nil
+ }
+
+ query, ok := sel.SemanticQuery()
+ if !ok {
+ return &UnsupportedError{Path: hintPath, Reason: string(sel.Kind) + " hints are not supported"}
+ }
+ prop.hintKindResolved = hintQuery
+ prop.hintValue = query
+ return nil
+}
diff --git a/internal/extract/testdata/README.md b/internal/extract/testdata/README.md
new file mode 100644
index 00000000..587d7d13
--- /dev/null
+++ b/internal/extract/testdata/README.md
@@ -0,0 +1,19 @@
+# extract testdata
+
+Accessibility snapshots used by `TestResolve_FromSnapshotFixtures`. Each file is
+the `nodes` array of a `pinchtab snap --json` capture, so the unit tests run
+against the same node shape the e2e fixtures produce.
+
+| testdata file | fixture |
+| ---------------------- | ---------------------------------------- |
+| `extract-product.json` | `tests/e2e/fixtures/extract-product.html` |
+| `extract-article.json` | `tests/e2e/fixtures/extract-article.html` |
+
+Authored to mirror the committed fixtures at PinchTab commit `c906674b`
+(the HEAD when PIN-391 landed). Refresh from a Docker run when a snapshot
+changes shape:
+
+```
+pinchtab open http://fixtures/extract-product.html
+pinchtab snap --json > internal/extract/testdata/extract-product.json
+```
diff --git a/internal/extract/testdata/extract-article.json b/internal/extract/testdata/extract-article.json
new file mode 100644
index 00000000..bd3fc251
--- /dev/null
+++ b/internal/extract/testdata/extract-article.json
@@ -0,0 +1,11 @@
+{
+ "url": "http://fixtures/extract-article.html",
+ "title": "The Rise of Model-Free Extraction",
+ "nodes": [
+ {"ref": "e1", "role": "article", "name": "Story", "depth": 0},
+ {"ref": "e2", "role": "heading", "name": "The Rise of Model-Free Extraction", "depth": 1},
+ {"ref": "e3", "role": "paragraph", "name": "Author", "text": "Jane Doe", "depth": 1},
+ {"ref": "e4", "role": "paragraph", "name": "Date published", "text": "2026-09-12", "depth": 1},
+ {"ref": "e5", "role": "paragraph", "name": "Body", "text": "Agents have long needed a step between finding one element and scraping a whole page. A schema-driven extractor fills that gap without a model.", "depth": 1}
+ ]
+}
diff --git a/internal/extract/testdata/extract-product.json b/internal/extract/testdata/extract-product.json
new file mode 100644
index 00000000..381c71d6
--- /dev/null
+++ b/internal/extract/testdata/extract-product.json
@@ -0,0 +1,12 @@
+{
+ "url": "http://fixtures/extract-product.html",
+ "title": "Product — Sony WH-1000XM5",
+ "nodes": [
+ {"ref": "e1", "role": "main", "name": "Product", "depth": 0},
+ {"ref": "e2", "role": "heading", "name": "Sony WH-1000XM5 Wireless Headphones", "depth": 1},
+ {"ref": "e3", "role": "paragraph", "name": "Price", "text": "$1,299.00", "depth": 1},
+ {"ref": "e4", "role": "paragraph", "name": "Rating", "text": "4.7 out of 5", "depth": 1},
+ {"ref": "e5", "role": "checkbox", "name": "In stock", "checked": "true", "depth": 1},
+ {"ref": "e6", "role": "paragraph", "name": "Description", "text": "Industry-leading noise cancellation with up to 30 hours of battery life.", "depth": 1}
+ ]
+}
diff --git a/internal/handlers/semantic_descriptors.go b/internal/handlers/semantic_descriptors.go
index 614164b5..7a59515a 100644
--- a/internal/handlers/semantic_descriptors.go
+++ b/internal/handlers/semantic_descriptors.go
@@ -1,151 +1,15 @@
package handlers
import (
- "strings"
-
"github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/semdesc"
"github.com/pinchtab/semantic"
)
-// descriptorFromNode builds a descriptor from a single node's direct fields,
-// without the cross-node positional/parent/section context that
-// semanticDescriptorsFromNodes computes over the whole tree. Used where only the
-// element's own attributes are needed (e.g. recovery intent, read via Composite).
func descriptorFromNode(node bridge.A11yNode) semantic.ElementDescriptor {
- return semantic.ElementDescriptor{
- Ref: node.Ref,
- Role: node.Role,
- Name: node.Name,
- Value: node.Value,
- Label: node.Label,
- Placeholder: node.Placeholder,
- Alt: node.Alt,
- Title: node.Title,
- TestID: node.TestID,
- Text: node.Text,
- Tag: node.Tag,
- Interactive: bridge.InteractiveRoles[node.Role],
- }
+ return semdesc.FromNode(node)
}
func semanticDescriptorsFromNodes(nodes []bridge.A11yNode) []semantic.ElementDescriptor {
- descs := make([]semantic.ElementDescriptor, len(nodes))
- if len(nodes) == 0 {
- return descs
- }
-
- parentIdx := make([]int, len(nodes))
- for i := range parentIdx {
- parentIdx[i] = -1
- }
-
- stackByDepth := make(map[int]int)
- for i, node := range nodes {
- depth := node.Depth
- if depth < 0 {
- depth = 0
- }
- if depth > 0 {
- if parent, ok := stackByDepth[depth-1]; ok {
- parentIdx[i] = parent
- }
- }
- stackByDepth[depth] = i
- for knownDepth := range stackByDepth {
- if knownDepth > depth {
- delete(stackByDepth, knownDepth)
- }
- }
- }
-
- type siblingKey struct {
- parent int
- depth int
- }
- siblingIndex := make([]int, len(nodes))
- siblingCounts := make(map[siblingKey]int)
- keys := make([]siblingKey, len(nodes))
- for i, node := range nodes {
- key := siblingKey{parent: parentIdx[i], depth: node.Depth}
- keys[i] = key
- siblingIndex[i] = siblingCounts[key]
- siblingCounts[key]++
- }
-
- for i, node := range nodes {
- desc := semantic.ElementDescriptor{
- Ref: node.Ref,
- Role: node.Role,
- Name: node.Name,
- Value: node.Value,
- Label: node.Label,
- Placeholder: node.Placeholder,
- Alt: node.Alt,
- Title: node.Title,
- TestID: node.TestID,
- Text: node.Text,
- Tag: node.Tag,
- Interactive: bridge.InteractiveRoles[node.Role],
- DocumentIdx: i,
- Positional: semantic.PositionalHints{
- Depth: node.Depth,
- SiblingIndex: siblingIndex[i],
- SiblingCount: siblingCounts[keys[i]],
- },
- }
-
- if parent := parentIdx[i]; parent >= 0 {
- desc.Parent = semanticContextLabel(nodes[parent])
- if isLabelledContainer(nodes[parent].Role) {
- desc.Positional.LabelledBy = nodes[parent].Name
- }
- }
- if section := nearestSemanticSection(nodes, parentIdx, i); section != "" {
- desc.Section = section
- }
-
- descs[i] = desc
- }
-
- return descs
-}
-
-func semanticContextLabel(node bridge.A11yNode) string {
- role := strings.TrimSpace(node.Role)
- name := strings.TrimSpace(node.Name)
- switch {
- case role != "" && name != "":
- return role + ": " + name
- case name != "":
- return name
- default:
- return role
- }
-}
-
-func nearestSemanticSection(nodes []bridge.A11yNode, parentIdx []int, idx int) string {
- for parent := parentIdx[idx]; parent >= 0; parent = parentIdx[parent] {
- if isSectionRole(nodes[parent].Role) {
- return semanticContextLabel(nodes[parent])
- }
- }
- return ""
-}
-
-func isLabelledContainer(role string) bool {
- switch strings.ToLower(strings.TrimSpace(role)) {
- case "form", "group", "region", "dialog", "tabpanel":
- return true
- default:
- return false
- }
-}
-
-func isSectionRole(role string) bool {
- switch strings.ToLower(strings.TrimSpace(role)) {
- case "form", "region", "dialog", "navigation", "main", "banner", "contentinfo", "group", "tabpanel":
- return true
- default:
- return false
- }
+ return semdesc.Build(nodes)
}
diff --git a/internal/semdesc/semdesc.go b/internal/semdesc/semdesc.go
new file mode 100644
index 00000000..196c319c
--- /dev/null
+++ b/internal/semdesc/semdesc.go
@@ -0,0 +1,156 @@
+// Package semdesc converts accessibility snapshot nodes into semantic element
+// descriptors. It is the single source of the node-to-descriptor mapping so the
+// /find handler and the model-free extractor score against identical inputs and
+// cannot drift.
+package semdesc
+
+import (
+ "strings"
+
+ "github.com/pinchtab/pinchtab/internal/bridge/observe"
+ "github.com/pinchtab/semantic"
+)
+
+// FromNode builds a descriptor from a single node's direct fields, without the
+// cross-node positional/parent/section context that Build computes over the
+// whole tree. Used where only the element's own attributes are needed.
+func FromNode(node observe.A11yNode) semantic.ElementDescriptor {
+ return semantic.ElementDescriptor{
+ Ref: node.Ref,
+ Role: node.Role,
+ Name: node.Name,
+ Value: node.Value,
+ Label: node.Label,
+ Placeholder: node.Placeholder,
+ Alt: node.Alt,
+ Title: node.Title,
+ TestID: node.TestID,
+ Text: node.Text,
+ Tag: node.Tag,
+ Interactive: observe.InteractiveRoles[node.Role],
+ }
+}
+
+// Build maps a flat pre-order node list to descriptors, computing tree context
+// (parent, sibling index/count, nearest section, LabelledBy) from Depth.
+func Build(nodes []observe.A11yNode) []semantic.ElementDescriptor {
+ descs := make([]semantic.ElementDescriptor, len(nodes))
+ if len(nodes) == 0 {
+ return descs
+ }
+
+ parentIdx := make([]int, len(nodes))
+ for i := range parentIdx {
+ parentIdx[i] = -1
+ }
+
+ stackByDepth := make(map[int]int)
+ for i, node := range nodes {
+ depth := node.Depth
+ if depth < 0 {
+ depth = 0
+ }
+ if depth > 0 {
+ if parent, ok := stackByDepth[depth-1]; ok {
+ parentIdx[i] = parent
+ }
+ }
+ stackByDepth[depth] = i
+ for knownDepth := range stackByDepth {
+ if knownDepth > depth {
+ delete(stackByDepth, knownDepth)
+ }
+ }
+ }
+
+ type siblingKey struct {
+ parent int
+ depth int
+ }
+ siblingIndex := make([]int, len(nodes))
+ siblingCounts := make(map[siblingKey]int)
+ keys := make([]siblingKey, len(nodes))
+ for i, node := range nodes {
+ key := siblingKey{parent: parentIdx[i], depth: node.Depth}
+ keys[i] = key
+ siblingIndex[i] = siblingCounts[key]
+ siblingCounts[key]++
+ }
+
+ for i, node := range nodes {
+ desc := semantic.ElementDescriptor{
+ Ref: node.Ref,
+ Role: node.Role,
+ Name: node.Name,
+ Value: node.Value,
+ Label: node.Label,
+ Placeholder: node.Placeholder,
+ Alt: node.Alt,
+ Title: node.Title,
+ TestID: node.TestID,
+ Text: node.Text,
+ Tag: node.Tag,
+ Interactive: observe.InteractiveRoles[node.Role],
+ DocumentIdx: i,
+ Positional: semantic.PositionalHints{
+ Depth: node.Depth,
+ SiblingIndex: siblingIndex[i],
+ SiblingCount: siblingCounts[keys[i]],
+ },
+ }
+
+ if parent := parentIdx[i]; parent >= 0 {
+ desc.Parent = contextLabel(nodes[parent])
+ if isLabelledContainer(nodes[parent].Role) {
+ desc.Positional.LabelledBy = nodes[parent].Name
+ }
+ }
+ if section := nearestSection(nodes, parentIdx, i); section != "" {
+ desc.Section = section
+ }
+
+ descs[i] = desc
+ }
+
+ return descs
+}
+
+func contextLabel(node observe.A11yNode) string {
+ role := strings.TrimSpace(node.Role)
+ name := strings.TrimSpace(node.Name)
+ switch {
+ case role != "" && name != "":
+ return role + ": " + name
+ case name != "":
+ return name
+ default:
+ return role
+ }
+}
+
+func nearestSection(nodes []observe.A11yNode, parentIdx []int, idx int) string {
+ for parent := parentIdx[idx]; parent >= 0; parent = parentIdx[parent] {
+ if isSectionRole(nodes[parent].Role) {
+ return contextLabel(nodes[parent])
+ }
+ }
+ return ""
+}
+
+func isLabelledContainer(role string) bool {
+ switch strings.ToLower(strings.TrimSpace(role)) {
+ case "form", "group", "region", "dialog", "tabpanel":
+ return true
+ default:
+ return false
+ }
+}
+
+func isSectionRole(role string) bool {
+ switch strings.ToLower(strings.TrimSpace(role)) {
+ case "form", "region", "dialog", "navigation", "main", "banner", "contentinfo", "group", "tabpanel":
+ return true
+ default:
+ return false
+ }
+}
diff --git a/tests/e2e/fixtures/extract-article.html b/tests/e2e/fixtures/extract-article.html
new file mode 100644
index 00000000..fd611780
--- /dev/null
+++ b/tests/e2e/fixtures/extract-article.html
@@ -0,0 +1,16 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <title>The Rise of Model-Free Extraction</title>
+</head>
+<body>
+ <article aria-label="Story">
+ <h1>The Rise of Model-Free Extraction</h1>
+ <p aria-label="Author">Jane Doe</p>
+ <p aria-label="Date published">2026-09-12</p>
+ <p aria-label="Body">Agents have long needed a step between finding one element and
+ scraping a whole page. A schema-driven extractor fills that gap without a model.</p>
+ </article>
+</body>
+</html>
diff --git a/tests/e2e/fixtures/extract-product.html b/tests/e2e/fixtures/extract-product.html
new file mode 100644
index 00000000..9650ec35
--- /dev/null
+++ b/tests/e2e/fixtures/extract-product.html
@@ -0,0 +1,16 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <title>Product — Sony WH-1000XM5</title>
+</head>
+<body>
+ <main aria-label="Product">
+ <h1>Sony WH-1000XM5 Wireless Headphones</h1>
+ <p aria-label="Price">$1,299.00</p>
+ <p aria-label="Rating">4.7 out of 5</p>
+ <p><input type="checkbox" checked disabled aria-label="In stock"> In stock</p>
+ <p aria-label="Description">Industry-leading noise cancellation with up to 30 hours of battery life.</p>
+ </main>
+</body>
+</html>