Skip to content

fix(cli): stop build ranking partial query matches above full ones - #5614

Merged
ernestt merged 1 commit into
mainfrom
fix/build-retrieval-scoring
Aug 27, 2026
Merged

ernestt merged 1 commit into
mainfrom
fix/build-retrieval-scoring

Conversation

@ernestt

@ernestt ernestt commented Aug 27, 2026

Copy link
Copy Markdown
Contributor

Summary

astryx build "file browser" returns two form wizards above the actual file browser — and reports one as a confident direct match, so an agent scaffolds the wrong template:

form-wizard-vertical  98  matches 1/2 terms: file
import-wizard         98  matches 1/2 terms: file
file-explorer         97  matches 2/2 terms: file, browser

After this change:

file-explorer  117  matches 2/2 terms: file, browser
ide             58  matches 1/2 terms: file
shell-nav       58  matches 1/2 terms: file

Three independent causes in the retrieval path.

1. Multi-token scoring was not monotonic

scoreQuery averaged over matched tokens (sum / matched), so a second, weaker hit could pull the mean down further than the coverage bonus pushed it up. Solving the aggregation: against a first hit of s1, a second hit only helps if it scores above s1 − 39. So against a 90-point keyword a second term has to beat 51 — and a description hit is exactly 50. Matching fewer terms well beat matching more terms partially.

The score is now based on the strongest matched concept plus the existing per-concept and coverage bonuses. That preserves the reason the mean was there in the first place — a verbose, low-fidelity prompt is still scored on the concepts it did hit, rather than divided across every token — while making the score monotonic: a candidate matching a superset of another's terms can no longer rank below it.

2. TypeScript generics were indexed as rendered components

extractComponents' tag regex /<(XDS)?([A-Z]\w+)/g matched generic argument lists. useState<ReadonlySet<string>>, ComponentType<SVGProps<SVGSVGElement>> and Record<string, Phase> were all reported as rendered components — 82 bogus entries across the 51 page templates, including Record (9 templates), ReadonlySet (5), Array (5), and every local type alias (TaskRow, Severity, Segment, …).

A lookbehind now requires the < not to follow an identifier character. Since template <name> and template --skeleton share this extractor, it also cleans up their user-facing "components used" output.

3. Derived keywords scored the same as authored ones

Every component a page rendered became a full-strength keyword (90), with no penalty for how many a template had. Breadth is not relevance: theme-showcase accrues 50 and settings-dialog 45 against a median of 14, so the broadest pages became noise magnets and won queries they had nothing to do with.

Derived signal now lands in a separate weakKeywords tier capped at 60 — below PAGE_DIRECT (95) on its own, so one incidental component match cannot produce a confidently wrong answer, but above PAGE_FLOOR (50), so it still surfaces as a reference. Authored signal (a block's componentsUsed, a page's category words) keeps its 90.

Measurements

36-query battery, same template set, baseline = this branch's merge base:

top-1 top-3 MRR false-confident no results
before 15/36 23/36 0.509 8/36 1/36
after 17/36 26/36 0.574 6/36 3/36

"false-confident" = build reports directMatch on the wrong template, which is the failure mode that actively misleads an agent.

Both queries that now return nothing previously returned wrong pages — three dashboards for "collecting information across several steps with a progress indicator", and a confidently-wrong dashboard-executive-summary for "drag and drop builder where you assemble a layout". Returning nothing is the honest answer; getting them right is a description problem, not a scoring one.

I swept the derived tier rather than picking 60 by feel:

tier top-1 top-3 MRR false-confident
90 (before) 15 23 0.509 8
60 (this PR) 17 26 0.574 6
65 / 70 18 27 0.602 7
80 17 25 0.560 9

65/70 buy one top-1 for one false-confident. That is inside this battery's authoring noise (±2 queries), so I took the conservative end: at 60 two derived matches still cannot clear the confidence gate, at 70 they can. Trivial to change if you'd rather have the ranking.

Test plan

  • vitest run packages/cli/api/search/search.test.mjs packages/cli/foundation/discovery/template-adapter.test.mjs — 26 pass
  • New scoring tests: the file browser inversion, a superset-never-ranks-lower property, and a verbose-prompt guard for the behaviour the mean was protecting
  • New template-adapter.test.mjs — first coverage for extractComponents: generics excluded, JSX tags and closing tags still handled
  • New derived-vs-authored tier assertions, pinned against PAGE_DIRECT / PAGE_FLOOR
  • astryx build "file browser" returns file-explorer as the direct match
  • eslint clean; full pre-commit gate (check:sync, check:package-boundaries, check:changesets, check:cli-structure, …) green

Caveats

The 36-query battery is one author's, so the absolute rates reflect that battery rather than a population, and each ranking delta is 1–3 queries. The two things that are exact and independently reproducible are the file browser inversion and the 82 bogus keywords. The battery harness is not in this PR to keep it reviewable — happy to land it separately if it's useful to you.

`astryx build "file browser"` returned two form wizards that matched
only "file" (98) above the actual file browser that matched both terms
(97). 98 clears the PAGE_DIRECT gate, so `build` reported the wizard as
a confident direct match and told the agent to scaffold it.

Three causes, all in the retrieval path:

- Multi-token scores were averaged over MATCHED tokens, so a second,
  weaker hit could pull the mean down further than the coverage bonus
  pushed it up: matching fewer terms well beat matching more terms
  partially. Base the score on the strongest matched concept instead.
  That keeps verbose prompts scored on the concepts they did hit (the
  reason the mean was chosen) while making the score monotonic — a
  candidate matching a superset of another's terms can no longer rank
  below it.

- extractComponents matched TypeScript generic argument lists as if
  they were JSX tags, indexing `Record`, `SVGProps`, `ReadonlySet` and
  every local type alias as rendered components: 82 bogus entries
  across the 51 page templates, which also leaked into the "components
  used" output of `template <name>` and `--skeleton`.

- Auto-derived keywords scored identically to authored ones (90), with
  no penalty for how many a template had, so a page rendering one of
  everything got an independent full-strength shot per component. Split
  derived signal into a `weakKeywords` tier capped at 60, below the
  confident-match gate on its own but still above the page floor.

Measured over a 36-query battery on the same template set: top-1 15->17,
top-3 23->26, MRR 0.509->0.574, false-confident results 8->6.

Co-authored-by: Cursor <[email protected]>
@vercel

vercel Bot commented Aug 27, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
astryx Ready Ready Preview Aug 27, 2026 9:40pm

Request Review

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Aug 27, 2026

@josephfarina josephfarina left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

:shipit:

@github-actions

Copy link
Copy Markdown
Contributor

PR Analysis Report

📚 Storybook Preview

View Storybook for this PR
GitHub Pages may take up to a minute to hydrate after deploy.

🧪 Sandbox Preview

View Sandbox for this PR
GitHub Pages may take up to a minute to hydrate after deploy.

No new or modified components detected.

Bundle Size Summary

No component packages changed.

Accessibility Audit

Status: No accessibility violations detected.


Generated by PR Enrichment workflow | Storybook | Sandbox | View full report

github-actions Bot added a commit that referenced this pull request Aug 27, 2026
@ernestt
ernestt merged commit c6041cf into main Aug 27, 2026
25 of 26 checks passed
ernestt added a commit that referenced this pull request Aug 27, 2026
Review feedback on the first pass: the differentiator slot was leaning on
content-type nouns, and data is interchangeable. "Customer and address
summary, line items with quantities, totals with discount, shipping and
tax" describes the fixture `detail-page` happens to ship, not the
template. Someone building an invoice, a shipment or a job record needs
exactly that layout and would never match it, while the words carry no
information about what makes it unlike its siblings.

Descriptions now differentiate on four structural lenses:

  layout      split, centered, two-column, rail, stacked, masonry
  container   modal, panel, card, drawer, inline, full-bleed
  data shape  flat rows, grouped, hierarchical, time series, one record
  behaviour   drag, resize, collapse, filter, drill down, step through

Domain nouns are demoted to interchangeable examples rather than the
identity: `detail-page` is now "the shape for any record holding
children plus a history — a customer order with shipping, an invoice, a
transaction, or a job". The noun is illustration, the structure is the
claim, and listing several signals that none is definitional.

This also matches how the retrieval actually behaves. Structural
vocabulary is what a builder types when they don't know the template
name ("collapsible sections with an inspector", "a collapsible left
rail"), and stacked with the scoring fix it is worth far more than
domain nouns were: 32/36 top-1 against 23/36 for the noun-led pass.

Measured over the 36-query battery:

  main today                       top-1 15  top-3 23  MRR 0.509  false-conf 8
  noun-led descriptions            top-1 21  top-3 32  MRR 0.704  false-conf 9
  structural descriptions          top-1 22  top-3 32  MRR 0.727  false-conf 10
  structural + scoring fix (#5614) top-1 32  top-3 32  MRR 0.889  false-conf 2

Descriptions alone raise false-confident results, because richer text
pushes more candidates over the gate; #5614 is what converts that into
precision. The two want to land together.

Co-authored-by: Cursor <[email protected]>
@github-actions
github-actions Bot deleted the fix/build-retrieval-scoring branch August 28, 2026 09:14
ernestt added a commit that referenced this pull request Aug 28, 2026
#5615)

* docs(cli): rewrite page template descriptions so build can find them

`description` is the only template metadata field that carries retrieval
weight it hasn't already earned elsewhere. A 36-query field ablation put
top-1 at 15/36 with descriptions and 9/36 without — the largest single
contribution of any field, and larger than name and category combined.
Most descriptions weren't doing that work: the mean was 17 words, seven
were under eight, and `table` shipped "Data table with actions", which
is three content words for the most-requested archetype in the catalog.

Every page description now follows the same four slots:

  archetype     what kind of surface, in a builder's words
  job           the verb — what someone is actually doing here
  distinctive   the 3-5 nouns that separate it from its siblings
  synonyms      the other words people literally type

Written against the scorer rather than for prose. Descriptions match on
a stemmed whole word for 50 points, so: synonyms are spelled out (the
SYNONYM map discounts to 43, under the 50-point floor that lets a token
count in a multi-word query, so relying on it scores nothing); words are
in base form; stopwords like "page", "view" and "app" are not spent; and
component names are left out, since those are already in the keyword
pool. The long entries were cut, not extended — `dashboard-project-status`
went from 79 words to 34, because a description that mentions everything
matches everything.

Measured over the same 36-query battery: top-1 15->21, top-3 23->32,
MRR 0.509->0.704. Mean length 17.4 -> 27.3 words, none under eight.

Co-authored-by: Cursor <[email protected]>

* docs(cli): describe templates by structure, not by their sample data

Review feedback on the first pass: the differentiator slot was leaning on
content-type nouns, and data is interchangeable. "Customer and address
summary, line items with quantities, totals with discount, shipping and
tax" describes the fixture `detail-page` happens to ship, not the
template. Someone building an invoice, a shipment or a job record needs
exactly that layout and would never match it, while the words carry no
information about what makes it unlike its siblings.

Descriptions now differentiate on four structural lenses:

  layout      split, centered, two-column, rail, stacked, masonry
  container   modal, panel, card, drawer, inline, full-bleed
  data shape  flat rows, grouped, hierarchical, time series, one record
  behaviour   drag, resize, collapse, filter, drill down, step through

Domain nouns are demoted to interchangeable examples rather than the
identity: `detail-page` is now "the shape for any record holding
children plus a history — a customer order with shipping, an invoice, a
transaction, or a job". The noun is illustration, the structure is the
claim, and listing several signals that none is definitional.

This also matches how the retrieval actually behaves. Structural
vocabulary is what a builder types when they don't know the template
name ("collapsible sections with an inspector", "a collapsible left
rail"), and stacked with the scoring fix it is worth far more than
domain nouns were: 32/36 top-1 against 23/36 for the noun-led pass.

Measured over the 36-query battery:

  main today                       top-1 15  top-3 23  MRR 0.509  false-conf 8
  noun-led descriptions            top-1 21  top-3 32  MRR 0.704  false-conf 9
  structural descriptions          top-1 22  top-3 32  MRR 0.727  false-conf 10
  structural + scoring fix (#5614) top-1 32  top-3 32  MRR 0.889  false-conf 2

Descriptions alone raise false-confident results, because richer text
pushes more candidates over the gate; #5614 is what converts that into
precision. The two want to land together.

Co-authored-by: Cursor <[email protected]>

---------

Co-authored-by: Cursor <[email protected]>
josephfarina pushed a commit that referenced this pull request Sep 2, 2026
…in kit

Rebased onto main, which landed integration search (#5259) and the
scorer-level false-direct-match fix (#5614) while this was open. Both are
main's implementations and are untouched: this branch no longer rewrites
gatherComponents, so the two regressions that rewrite caused go with it — an
integration result reports its own package again, and a broken config no
longer turns a Core `button` search into an empty success.

What is left is the part that did not land. A page template's keywords include
every component its source renders, so `build "actionable warning banner"`
returned login, contact-form and documentation-design at 95 apiece on an exact
hit for "banner" alone. Coverage now gates the pages group instead of
garnishing the score, and a thin kit names the browse commands rather than
reading as "the package has nothing".

scoreQuery reports the coverage it already computed as matchedTerms /
queryTerms, because a single strong hit and a broad weak one land on the same
score and the gate cannot tell them apart otherwise.

The guidance-tier indexing goes up separately, as asked.
josephfarina pushed a commit that referenced this pull request Sep 3, 2026
…in kit

Rebased onto main, which landed integration search (#5259) and the
scorer-level false-direct-match fix (#5614) while this was open. Both are
main's implementations and are untouched: this branch no longer rewrites
gatherComponents, so the two regressions that rewrite caused go with it — an
integration result reports its own package again, and a broken config no
longer turns a Core `button` search into an empty success.

What is left is the part that did not land. A page template's keywords include
every component its source renders, so `build "actionable warning banner"`
returned login, contact-form and documentation-design at 95 apiece on an exact
hit for "banner" alone. Coverage now gates the pages group instead of
garnishing the score, and a thin kit names the browse commands rather than
reading as "the package has nothing".

scoreQuery reports the coverage it already computed as matchedTerms /
queryTerms, because a single strong hit and a broad weak one land on the same
score and the gate cannot tell them apart otherwise.

The guidance-tier indexing goes up separately, as asked.
josephfarina added a commit that referenced this pull request Sep 3, 2026
… word a match (#5320)

* fix(cli): gate the build pages group on query coverage, and hint a thin kit

Rebased onto main, which landed integration search (#5259) and the
scorer-level false-direct-match fix (#5614) while this was open. Both are
main's implementations and are untouched: this branch no longer rewrites
gatherComponents, so the two regressions that rewrite caused go with it — an
integration result reports its own package again, and a broken config no
longer turns a Core `button` search into an empty success.

What is left is the part that did not land. A page template's keywords include
every component its source renders, so `build "actionable warning banner"`
returned login, contact-form and documentation-design at 95 apiece on an exact
hit for "banner" alone. Coverage now gates the pages group instead of
garnishing the score, and a thin kit names the browse commands rather than
reading as "the package has nothing".

scoreQuery reports the coverage it already computed as matchedTerms /
queryTerms, because a single strong hit and a broad weak one land on the same
score and the gate cannot tell them apart otherwise.

The guidance-tier indexing goes up separately, as asked.

* refactor(cli): move the thin-kit hint out to its own PR

Review asked for the guidance indexing and the thin-kit hint as separate small
PRs. The hint is now #5938 and the guidance tier is #5937, so this branch keeps
only the coverage gate on the build pages group and the matchedTerms/queryTerms
plumbing that gate needs.

No behaviour change to the gate itself.

---------

Co-authored-by: Joey Farina <[email protected]>
AKnassa added a commit to AKnassa/astryx that referenced this pull request Sep 7, 2026
… mechanism

Main independently landed the derived-keyword fix (meta#5614, weakKeywords
capped below the confident-match gate), superseding this branch's
length-normalized derivedKeywords. Resolution:

- search.mjs: taken byte-identical from main — one mechanism, main's.
  A naive automerge would have stitched BOTH scoring paths in.
- search.test.mjs: main's tests, plus this branch's three end-to-end
  regression tests pinning the symptom (table page top-3 on
  'customer list'; theme-showcase off the top for 'list of users';
  runner-up band separated by score, not alphabetical tie). The
  derivedKeywords unit tests are dropped — main's cover that ground.
  The band test now compares pages[1] vs pages[5]: index 0 escaped
  the historical tie, so the old assertion passed even with the bug.
- changeset removed: no behavior change ships from this branch now.
- theme-showcase doc comment kept, reworded for main's model.

Verified: search file 38/38; full cli suite 3254 passed with the same
7 environment-dependent failures as a main-checkout control run; all
four cli typechecks green after core + theme-neutral rebuilds.

This branch was successfully deployed

1 active deployment
Preview — de901398 Deployed Aug 27, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants