@nac3/runtime 2.3.0 → 2.4.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,114 @@
1
1
  # Changelog
2
2
 
3
+ ## 2.4.0 -- 2026-05-21
4
+
5
+ NAC3 v2.4.0 is a **behavior-of-contract change**: id / verb / qualifier
6
+ resolution becomes strict. Backwards-compatible with code paths that
7
+ already supplied unambiguous arguments, **NOT** backwards-compatible
8
+ with code paths that depended on the previous lenient (`indexOf`)
9
+ fallback to resolve to the first near-match.
10
+
11
+ ### Why this changed (the principle, not a feature)
12
+
13
+ The lenient resolution in 2.3.x violated the spec's 0-silent-damage
14
+ invariant. Specifically, `click_by_verb(plugin, verb, { qualifier })`
15
+ would, on a no-exact-suffix match, fall through to an `indexOf(qualifier)`
16
+ substring search and resolve silently to whatever element happened to
17
+ contain the qualifier string anywhere in its id. The H4 benchmark on the
18
+ Conduit case study (2026-05-21) showed that **12 of 18 "model failures"
19
+ on the canonical flows were actually silent runtime damage** — the
20
+ agent emitted an invalid qualifier, the runtime sent it to the wrong
21
+ element, the agent looped against the wrong page state. Strict
22
+ resolution rescues those 12 (see `nac-spec/conduit/H4_STRICT_NAC_REPORT.md`).
23
+
24
+ For an assistive-software use case (the principal driver of this
25
+ project), a silent dispatch to the wrong element with no recovery path
26
+ is a safety blocker. Strict resolution closes that gap.
27
+
28
+ ### New error model — disambiguation contract
29
+
30
+ When `click_by_verb` / `tab` / `tab_by_label` cannot resolve a request
31
+ unambiguously, the runtime now:
32
+
33
+ 1. Emits `nac:disambiguation_requested` on `document` with a
34
+ structured detail payload (see below).
35
+ 2. Throws `NacError` with `err.code` ∈ `{no_matching_instance,
36
+ ambiguous_qualifier, ambiguous_tab, ambiguous_label}` AND
37
+ `err.candidates: [{nac_id, label}, ...]` pre-validated against the
38
+ live DOM.
39
+
40
+ Detail / candidates payload:
41
+ ```js
42
+ {
43
+ method: 'click_by_verb' | 'tab' | 'tab_by_label',
44
+ plugin: string | null,
45
+ query: { verb?, qualifier?, label?, id? },
46
+ reason: 'no_matching_instance' | 'ambiguous_qualifier' | 'ambiguous_tab' |
47
+ 'ambiguous_label' | 'ambiguous_label_exact' | 'ambiguous_label_fuzzy' |
48
+ 'no_matching_label',
49
+ candidates: [{ nac_id: string, label: string }, ...]
50
+ }
51
+ ```
52
+
53
+ A reactive host (chat UI / voice agent / screen-reader) can listen
54
+ on the event and present the options to the user as *"did you
55
+ mean A or B?"*. A synchronous catcher can read `err.candidates`
56
+ directly. An autonomous agent (Pilot, etc.) can inject the candidates
57
+ into the next turn's prompt so the LLM picks from a DOM-validated
58
+ list instead of re-guessing a qualifier.
59
+
60
+ ### What changed in the resolvers
61
+
62
+ - **`click_by_verb` with qualifier:** only exact-equality or anchored
63
+ suffix (`id === qualifier || id.endsWith('__' + qualifier)`)
64
+ resolves. Multiple matches → `ambiguous_qualifier`. Zero matches →
65
+ `no_matching_instance`. **The `indexOf` substring fallback is
66
+ removed.**
67
+ - **`tab` single-arg form:** bare id resolves to exact match in DOM. If
68
+ no exact, exactly one anchored-prefix instance
69
+ (`id.startsWith(bare + '__')`) resolves; multiple → `ambiguous_tab`;
70
+ zero → `no_matching_instance`.
71
+ - **`tab_by_label`:** two-tier strict — exact label match first
72
+ (errors if multiple), then substring match (errors if multiple).
73
+ Fuzzy match preserved for voice/assistive use case; ambiguity
74
+ caught.
75
+
76
+ ### Verification
77
+
78
+ - `packages/nac/test/stage2-disambiguation.mjs` — pre-existing
79
+ tab_by_label cases still PASS (B1–B4).
80
+ - `packages/nac/test/stage7-strict-resolution.mjs` (new) — 9/9
81
+ invariants pass under JSDOM shim.
82
+ - `nac3-bench/bench/scripts/stage7_strict_nac.mjs` (new) — 9/9
83
+ invariants pass under Playwright against a live page.
84
+ - `nac3-bench/bench/h4_results/h4_2026-05-21T19-01-19-040Z.json` —
85
+ cheap-model benchmark with strict NAC: 48/54 = 89% (vs 36/54 = 67%
86
+ under lenient).
87
+
88
+ ### Migration guide
89
+
90
+ If your code was passing fuzzy qualifiers and depending on the runtime
91
+ to pick "something close", the upgrade requires you to:
92
+ - Either supply the full `nac_id` directly (always unambiguous), OR
93
+ - Pass the exact `__suffix` of the instance you want, OR
94
+ - Listen for `nac:disambiguation_requested` / catch `NacError` with
95
+ `err.candidates` and pick from the returned list.
96
+
97
+ Most users won't be affected — the only callers that broke during the
98
+ internal regression were the ones that were already broken silently in
99
+ 2.3.x but happened to land on the wrong-but-related element instead of
100
+ failing.
101
+
102
+ ---
103
+
104
+ ## 2.3.1 -- 2026-05-13 (stable, blank republish)
105
+
106
+ Identical source to 2.3.0. The 2.3.0 tag had already been published to
107
+ npm as a preview; 2.3.1 is the first installable stable version. No
108
+ behavioural changes.
109
+
110
+ ---
111
+
3
112
  ## 2.3.0 -- 2026-05-13 (stable)
4
113
 
5
114
  NAC3 v2.3.0 is the first stable release of the payload-bearing
package/README.md CHANGED
@@ -117,9 +117,14 @@ import '@nac3/runtime/chat-client'; // reference voice + chat client
117
117
 
118
118
  ## Status
119
119
 
120
- - v2.1 stable.
121
- - v2.2 in design (constructor becomes a strict validator -- see
122
- `docs/NAC_V22_ROADMAP.md` in the spec repo).
120
+ - **v2.4.0 stable** (2026-05-21). Zero-silent-damage strict resolution
121
+ + disambiguation contract: `click_by_verb` / `tab` / `tab_by_label`
122
+ throw `NacError` with `err.candidates` and emit
123
+ `nac:disambiguation_requested` instead of guessing the wrong element.
124
+ See `CHANGELOG.md` for the full migration note.
125
+ - Previous stable: v2.3.1 (payload-bearing actions, F1-F7).
126
+ - Earlier: v2.2 (strict validator, bindAction), v2.1 (data-table),
127
+ v2.0 (scope tree + ephemeral capture).
123
128
 
124
129
  ## Spec
125
130
 
package/SPEC.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # NAC3 -- Native Agent Contract
2
2
 
3
- **Version:** 2.3.0-alpha.1 (preview; payload-bearing actions land here)
4
- **Status:** v2.2.x stable + v2.3 preview
3
+ **Version:** 2.4.0 (stable; zero silent damage via strict resolution + disambiguation contract)
4
+ **Status:** v2.4.0 stable -- supersedes 2.3.x
5
5
  **License:** Apache-2.0
6
6
  **Editor:** Yujin (rpaforce.com)
7
7
 
@@ -1,13 +1,12 @@
1
1
  // Generated by build.mjs -- do not edit. Source: yujin.app/nac-spec/js/nac.js
2
2
  /* =====================================================================
3
- NAC v1.9.0 -- Native Accessibility Contract / Navegabilidad Automatica
4
- Compliance.
5
- Reference JavaScript implementation. Spec: spec/NAC-v1.0.md.
3
+ NAC3 (Native Agent Contract v3) -- reference JavaScript runtime.
4
+ Spec: packages/nac/SPEC.md. Public docs: yujin.app/nac-spec/.
6
5
  MIT License -- Pablo Adrian Kuschniroff + Sumi, 2026.
7
6
  =====================================================================
8
7
 
9
8
  AUTHORITATIVE VERSION CONSTANT: see the global.NAC export at the
10
- bottom of this file. `version: '1.9.0', spec_version: '1.9'` is
9
+ bottom of this file. `version: '2.4.0', spec_version: '2.4'` is
11
10
  the normative declaration. The dated changelog sections below are
12
11
  historical notes; if they ever drift from the export, the export
13
12
  wins.
@@ -324,6 +323,43 @@
324
323
  return e;
325
324
  }
326
325
 
326
+ /* H1.v7 (2026-05-21): structured disambiguation contract.
327
+ When the runtime cannot resolve an id/verb/qualifier/label
328
+ unambiguously, it MUST emit `nac:disambiguation_requested` with
329
+ a structured candidate list so reactive hosts (chat UI, voice
330
+ agent, assistive software) can present the choices to the user.
331
+ The error thrown alongside carries the same candidates on
332
+ err.candidates so synchronous catchers can also recover.
333
+
334
+ Detail shape:
335
+ method: 'click_by_verb' | 'tab' | 'tab_by_label' | ...
336
+ plugin: string | null
337
+ query: { verb, qualifier, label, id, ... } (whatever applies)
338
+ candidates: [{ nac_id: '...', label: '...' }, ...]
339
+
340
+ Hosts SHOULD listen on document and reply by re-dispatching
341
+ with a more specific qualifier/id. Voice agents SHOULD speak
342
+ "Did you mean A or B?" using the labels. */
343
+ function _emitDisambiguationRequested(detail) {
344
+ if (typeof document === 'undefined' || !document.dispatchEvent) return;
345
+ try {
346
+ document.dispatchEvent(new CustomEvent('nac:disambiguation_requested', {
347
+ detail: detail,
348
+ }));
349
+ } catch (e) { /* tolerated -- runtime should still throw */ }
350
+ }
351
+
352
+ function _candidateLabel(el) {
353
+ /* Best-effort human label for a DOM element. Used in
354
+ candidates[].label so voice/asistive can re-prompt. */
355
+ if (!el) return '';
356
+ const al = el.getAttribute && el.getAttribute('aria-label');
357
+ if (al) return String(al).trim();
358
+ const tx = (el.textContent || '').replace(/\s+/g, ' ').trim();
359
+ if (tx) return tx.slice(0, 120);
360
+ return el.getAttribute && el.getAttribute('data-nac-id') || '';
361
+ }
362
+
327
363
  /* ---------- v1.8.0: skip-validate, command-events, dedup ------- */
328
364
 
329
365
  /* Spec sec 5: data-nac-validate="skip" marks a subtree (typically
@@ -2360,13 +2396,43 @@
2360
2396
  const ft = el.getAttribute('data-nac-field-type');
2361
2397
 
2362
2398
  if (ft === 'checkbox' || ft === 'radio') {
2363
- el.checked = !!value;
2399
+ /* React tracks `checked` similarly to `value`; use the native
2400
+ setter so controlled checkboxes/radios update state. */
2401
+ var nativeCheckedSetter = Object.getOwnPropertyDescriptor(
2402
+ window.HTMLInputElement.prototype, 'checked'
2403
+ );
2404
+ if (nativeCheckedSetter && nativeCheckedSetter.set) {
2405
+ nativeCheckedSetter.set.call(el, !!value);
2406
+ } else {
2407
+ el.checked = !!value;
2408
+ }
2364
2409
  } else if (el.tagName === 'SELECT') {
2365
- el.value = String(value);
2410
+ var nativeSelectSetter = Object.getOwnPropertyDescriptor(
2411
+ window.HTMLSelectElement.prototype, 'value'
2412
+ );
2413
+ if (nativeSelectSetter && nativeSelectSetter.set) {
2414
+ nativeSelectSetter.set.call(el, String(value));
2415
+ } else {
2416
+ el.value = String(value);
2417
+ }
2366
2418
  } else if (el.hasAttribute('contenteditable')) {
2367
2419
  el.textContent = String(value == null ? '' : value);
2368
2420
  } else {
2369
- el.value = String(value == null ? '' : value);
2421
+ /* React + controlled inputs: setting el.value directly is silently
2422
+ reverted on the next render because React's synthetic event system
2423
+ tracks the original property setter on HTMLInputElement.prototype.
2424
+ Use the native setter so React's onChange receives the new value
2425
+ and updates its state. Works on plain DOM inputs unchanged. */
2426
+ var proto = (el.tagName === 'TEXTAREA')
2427
+ ? window.HTMLTextAreaElement.prototype
2428
+ : window.HTMLInputElement.prototype;
2429
+ var nativeValueSetter = Object.getOwnPropertyDescriptor(proto, 'value');
2430
+ var newVal = String(value == null ? '' : value);
2431
+ if (nativeValueSetter && nativeValueSetter.set) {
2432
+ nativeValueSetter.set.call(el, newVal);
2433
+ } else {
2434
+ el.value = newVal;
2435
+ }
2370
2436
  }
2371
2437
 
2372
2438
  el.dispatchEvent(new Event('input', { bubbles: true }));
@@ -2407,6 +2473,81 @@
2407
2473
  }
2408
2474
 
2409
2475
  async function tab(plugin, tab_key) {
2476
+ /* H1.v5 (2026-05-20): single-arg ergonomic form. When the caller
2477
+ passes only a full nac_id (e.g. "conduit.tab.feed__your_feed"),
2478
+ resolve it directly against the DOM without requiring the
2479
+ caller to split plugin + tab_key. The two-arg form remains
2480
+ the canonical contract; this is a back-compat ergonomic. */
2481
+ if (tab_key === undefined && typeof plugin === 'string' && plugin.indexOf('.') >= 0) {
2482
+ const bareId = plugin;
2483
+ let tabEl = document.querySelector(
2484
+ '[data-nac-role="tab"][data-nac-id="' + bareId + '"]'
2485
+ );
2486
+ /* H1.v7 (2026-05-21): strict resolution. If the bare id is not
2487
+ in DOM, try the qualified-instance fallback ONLY when the
2488
+ match is unambiguous: exactly one element whose id starts
2489
+ with bareId + "__". Zero matches throws no_matching_instance;
2490
+ multiple matches throws ambiguous_tab. No silent resolution
2491
+ to "the first one that looks similar" -- assistive users
2492
+ landing on the wrong tab from a near-match is the exact
2493
+ failure mode the protocol forbids. */
2494
+ if (!tabEl) {
2495
+ const cands = document.querySelectorAll('[data-nac-role="tab"][data-nac-id]');
2496
+ const exact = [];
2497
+ for (let i = 0; i < cands.length; i++) {
2498
+ const id = cands[i].getAttribute('data-nac-id') || '';
2499
+ if (id.indexOf(bareId + '__') === 0) exact.push(cands[i]);
2500
+ }
2501
+ if (exact.length === 1) {
2502
+ tabEl = exact[0];
2503
+ } else if (exact.length > 1) {
2504
+ const candidates = [];
2505
+ for (let i = 0; i < exact.length; i++) {
2506
+ candidates.push({
2507
+ nac_id: exact[i].getAttribute('data-nac-id'),
2508
+ label: _candidateLabel(exact[i]),
2509
+ });
2510
+ }
2511
+ _emitDisambiguationRequested({
2512
+ method: 'tab', plugin: null,
2513
+ query: { id: bareId },
2514
+ reason: 'ambiguous_tab',
2515
+ candidates: candidates,
2516
+ });
2517
+ throw NacError('ambiguous_tab',
2518
+ 'tab id="' + bareId + '" is not in DOM and ' + exact.length +
2519
+ ' qualified instances match the "' + bareId + '__" prefix: ' +
2520
+ candidates.map(function (c) { return c.nac_id; }).join(', ') +
2521
+ ' -- pass the full qualified id',
2522
+ { candidates: candidates });
2523
+ }
2524
+ }
2525
+ if (!tabEl) {
2526
+ /* No exact, no qualified instance. Build the list of all tabs
2527
+ in DOM so the agent / voice / assistive can re-ask. */
2528
+ const all = document.querySelectorAll('[data-nac-role="tab"][data-nac-id]');
2529
+ const available = [];
2530
+ for (let i = 0; i < all.length; i++) {
2531
+ available.push({
2532
+ nac_id: all[i].getAttribute('data-nac-id'),
2533
+ label: _candidateLabel(all[i]),
2534
+ });
2535
+ }
2536
+ _emitDisambiguationRequested({
2537
+ method: 'tab', plugin: null,
2538
+ query: { id: bareId },
2539
+ reason: 'no_matching_instance',
2540
+ candidates: available,
2541
+ });
2542
+ throw NacError('no_matching_instance', 'tab id="' + bareId +
2543
+ '" not in DOM (no exact match, no "' + bareId + '__" qualified instance)',
2544
+ { candidates: available });
2545
+ }
2546
+ _focusElement(tabEl);
2547
+ tabEl.click();
2548
+ try { await wait_for('nac:tab:changed', 1500); } catch (e) { /* tolerated */ }
2549
+ return { ok: true };
2550
+ }
2410
2551
  const root = document.querySelector('[data-nac-plugin="' + plugin + '"]');
2411
2552
  if (!root) throw NacError('not_found', 'plugin ' + plugin + ' not mounted');
2412
2553
  const tabEl = root.querySelector(
@@ -2434,6 +2575,20 @@
2434
2575
  if (!verb) throw NacError('invalid', 'click_by_verb requires a verb');
2435
2576
  /* Resolve plugin: explicit arg, or active plugin if null. */
2436
2577
  const targetPlugin = plugin || _activePlugin();
2578
+ /* H2 (2026-05-20): qualifier / qualifier_ordinal disambiguate
2579
+ among multiple DOM nodes that share a verb. Forge --ai-apply
2580
+ can decorate a reusable React component (e.g. <NavItem>) with
2581
+ a base nac_id and let the bake-time JSX add the qualifier
2582
+ suffix (e.g. "conduit.navigation.nav_item__sign_in"). The
2583
+ resolver below prefers an exact suffix match for opts.qualifier,
2584
+ falls back to a contains match, and supports
2585
+ opts.qualifier_ordinal as positional selection across all
2586
+ elements sharing the verb in DOM order. Back-compat: with no
2587
+ qualifier / qualifier_ordinal, behavior matches pre-H2. */
2588
+ const qualifier = opts && opts.qualifier;
2589
+ const qualifierOrdinal = opts && (typeof opts.qualifier_ordinal === 'number')
2590
+ ? opts.qualifier_ordinal : null;
2591
+
2437
2592
  /* Search the manifest first for an action with matching verb. */
2438
2593
  let matched = null;
2439
2594
  if (targetPlugin && _manifests[targetPlugin]) {
@@ -2445,22 +2600,112 @@
2445
2600
  }
2446
2601
  }
2447
2602
  }
2603
+ /* When a qualifier is provided we always fall through to the DOM
2604
+ scan -- the manifest's flat top-level actions[] entries don't
2605
+ carry per-instance suffixes; only the DOM does. */
2606
+ if (qualifier || qualifierOrdinal !== null) matched = null;
2607
+
2608
+ /* H1.v5 (2026-05-20): if the manifest matched but the matched.nac_id
2609
+ has no live DOM element, the manifest entry is a per-instance
2610
+ template (e.g. data-nac-id={`conduit.action.delete_article__${slug}`}).
2611
+ Fall through to the DOM scan so we pick whichever qualified
2612
+ instance is actually mounted. */
2613
+ if (matched && matched.nac_id) {
2614
+ const probe = document.querySelector('[data-nac-id="' + matched.nac_id + '"]');
2615
+ if (!probe) matched = null;
2616
+ }
2617
+
2448
2618
  if (!matched) {
2449
2619
  /* Fallback: scan DOM within plugin scope for [data-nac-action]. */
2450
2620
  const root = targetPlugin
2451
2621
  ? document.querySelector('[data-nac-plugin="' + targetPlugin + '"]')
2452
2622
  : document;
2453
2623
  if (root) {
2454
- const el = root.querySelector(
2455
- '[data-nac-action="' + verb + '"]');
2456
- if (el && el.getAttribute('data-nac-id')) {
2457
- matched = { nac_id: el.getAttribute('data-nac-id'), verb: verb };
2624
+ if (qualifier) {
2625
+ /* H1.v7 (2026-05-21): strict resolution. The previous
2626
+ implementation had a second-pass `indexOf(qualifier)`
2627
+ fallback that resolved silently to any element whose
2628
+ id CONTAINED the qualifier as a substring. That
2629
+ violated NAC's 0-silent-damage invariant: an invalid
2630
+ qualifier (e.g. "article") would match an unrelated
2631
+ element (e.g. "...nav_item__new_article") and report
2632
+ the dispatch as success. Now: only EXACT id match or
2633
+ SUFFIX after the "__" separator counts. Zero matches
2634
+ throws no_matching_instance; multiple matches throw
2635
+ ambiguous_qualifier. No silent resolution. */
2636
+ const cands = root.querySelectorAll('[data-nac-action="' + verb + '"]');
2637
+ const exact = [];
2638
+ for (let i = 0; i < cands.length; i++) {
2639
+ const id = cands[i].getAttribute('data-nac-id') || '';
2640
+ if (id === qualifier || id.endsWith('__' + qualifier)) exact.push(cands[i]);
2641
+ }
2642
+ if (exact.length === 0) {
2643
+ /* Build the list of AVAILABLE qualifiers for this verb so
2644
+ the agent / voice / assistive can re-ask with one that
2645
+ exists. This is the "no_matching" companion to
2646
+ ambiguous: in both cases we surface the option set. */
2647
+ const available = [];
2648
+ for (let i = 0; i < cands.length; i++) {
2649
+ available.push({
2650
+ nac_id: cands[i].getAttribute('data-nac-id'),
2651
+ label: _candidateLabel(cands[i]),
2652
+ });
2653
+ }
2654
+ _emitDisambiguationRequested({
2655
+ method: 'click_by_verb', plugin: targetPlugin || null,
2656
+ query: { verb: verb, qualifier: qualifier },
2657
+ reason: 'no_matching_instance',
2658
+ candidates: available,
2659
+ });
2660
+ throw NacError('no_matching_instance',
2661
+ 'No element with data-nac-action="' + verb +
2662
+ '" matches qualifier="' + qualifier + '" by exact id or __suffix' +
2663
+ ' in plugin "' + (targetPlugin || '<active>') + '"',
2664
+ { candidates: available });
2665
+ }
2666
+ if (exact.length > 1) {
2667
+ const candidates = [];
2668
+ for (let i = 0; i < exact.length; i++) {
2669
+ candidates.push({
2670
+ nac_id: exact[i].getAttribute('data-nac-id'),
2671
+ label: _candidateLabel(exact[i]),
2672
+ });
2673
+ }
2674
+ _emitDisambiguationRequested({
2675
+ method: 'click_by_verb', plugin: targetPlugin || null,
2676
+ query: { verb: verb, qualifier: qualifier },
2677
+ reason: 'ambiguous_qualifier',
2678
+ candidates: candidates,
2679
+ });
2680
+ throw NacError('ambiguous_qualifier',
2681
+ 'qualifier="' + qualifier + '" matches ' + exact.length +
2682
+ ' elements with verb="' + verb + '": ' +
2683
+ candidates.map(function (c) { return c.nac_id; }).join(', ') +
2684
+ ' -- supply a more specific qualifier or use opts.qualifier_ordinal',
2685
+ { candidates: candidates });
2686
+ }
2687
+ matched = { nac_id: exact[0].getAttribute('data-nac-id'), verb: verb };
2688
+ } else if (qualifierOrdinal !== null) {
2689
+ const cands = root.querySelectorAll('[data-nac-action="' + verb + '"]');
2690
+ const el = cands[qualifierOrdinal];
2691
+ if (el && el.getAttribute('data-nac-id')) {
2692
+ matched = { nac_id: el.getAttribute('data-nac-id'), verb: verb };
2693
+ }
2694
+ } else {
2695
+ /* Default: first match in DOM order. */
2696
+ const el = root.querySelector('[data-nac-action="' + verb + '"]');
2697
+ if (el && el.getAttribute('data-nac-id')) {
2698
+ matched = { nac_id: el.getAttribute('data-nac-id'), verb: verb };
2699
+ }
2458
2700
  }
2459
2701
  }
2460
2702
  }
2461
2703
  if (!matched || !matched.nac_id) {
2704
+ const qInfo = qualifier ? ' (qualifier="' + qualifier + '")'
2705
+ : qualifierOrdinal !== null ? ' (qualifier_ordinal=' + qualifierOrdinal + ')'
2706
+ : '';
2462
2707
  throw NacError('not_found',
2463
- 'No action with verb="' + verb + '" found in plugin "'
2708
+ 'No action with verb="' + verb + '"' + qInfo + ' found in plugin "'
2464
2709
  + (targetPlugin || '<active>') + '"');
2465
2710
  }
2466
2711
  return await click(matched.nac_id,
@@ -2672,58 +2917,159 @@
2672
2917
  }
2673
2918
  }
2674
2919
  }
2675
- let matched = null;
2676
- for (let i = 0; i < tabSources.length; i++) {
2677
- const t = tabSources[i];
2678
- const candidates = [];
2679
- if (t.label) candidates.push(t.label);
2920
+ /* H1.v7 (2026-05-21): two-tier strict resolution. The voice /
2921
+ assistive use case requires fuzzy substring matching (a user
2922
+ saying "feed" should reach "Global Feed") -- but it must NEVER
2923
+ resolve silently to the first lucky match when multiple tabs
2924
+ satisfy the same fuzzy query. For a disabled user a wrong-tab
2925
+ activation without signal is exactly the failure mode the
2926
+ protocol forbids.
2927
+
2928
+ Tier 1: exact-normalized equality. If exactly 1 source has
2929
+ _norm(candidate) === _norm(query) -> resolve. If 0, try tier 2.
2930
+ If >1 -> ambiguous_label (multiple tabs share the same name).
2931
+ Tier 2: substring containment in either direction. Collect ALL
2932
+ tabs that match by substring. If exactly 1 -> resolve. If 0,
2933
+ try DOM fallback. If >1 -> ambiguous_label (the agent must
2934
+ re-ask with a more specific phrase). */
2935
+ function _candidatesFor(t) {
2936
+ const out = [];
2937
+ if (t.label) out.push(t.label);
2680
2938
  if (t.label_i18n && typeof t.label_i18n === 'object') {
2681
2939
  for (const k in t.label_i18n) {
2682
- if (typeof t.label_i18n[k] === 'string') {
2683
- candidates.push(t.label_i18n[k]);
2684
- }
2940
+ if (typeof t.label_i18n[k] === 'string') out.push(t.label_i18n[k]);
2685
2941
  }
2686
2942
  }
2687
- if (t.nac_id) candidates.push(t.nac_id);
2688
- if (t.id) candidates.push(t.id);
2943
+ if (t.nac_id) out.push(t.nac_id);
2944
+ if (t.id) out.push(t.id);
2945
+ return out;
2946
+ }
2947
+ const exactMatches = [];
2948
+ const fuzzyMatches = [];
2949
+ for (let i = 0; i < tabSources.length; i++) {
2950
+ const t = tabSources[i];
2951
+ const candidates = _candidatesFor(t);
2952
+ let isExact = false, isFuzzy = false;
2689
2953
  for (let j = 0; j < candidates.length; j++) {
2690
2954
  const cand = _norm(candidates[j]);
2691
2955
  if (!cand) continue;
2692
- if (cand === lc
2693
- || (lc.length >= 3 && cand.indexOf(lc) >= 0)
2694
- || (cand.length >= 3 && lc.indexOf(cand) >= 0)) {
2695
- matched = { nac_id: t.nac_id || t.id };
2696
- break;
2697
- }
2956
+ if (cand === lc) { isExact = true; break; }
2957
+ if ((lc.length >= 3 && cand.indexOf(lc) >= 0) ||
2958
+ (cand.length >= 3 && lc.indexOf(cand) >= 0)) isFuzzy = true;
2698
2959
  }
2699
- if (matched) break;
2960
+ const id = t.nac_id || t.id;
2961
+ if (isExact && id) exactMatches.push({ id: id, label: t.label || id });
2962
+ else if (isFuzzy && id) fuzzyMatches.push({ id: id, label: t.label || id });
2963
+ }
2964
+ let matched = null;
2965
+ if (exactMatches.length === 1) {
2966
+ matched = { nac_id: exactMatches[0].id };
2967
+ } else if (exactMatches.length > 1) {
2968
+ _emitDisambiguationRequested({
2969
+ method: 'tab_by_label', plugin: targetPlugin,
2970
+ query: { label: label },
2971
+ reason: 'ambiguous_label_exact',
2972
+ candidates: exactMatches.map(function (m) {
2973
+ return { nac_id: m.id, label: m.label };
2974
+ }),
2975
+ });
2976
+ throw NacError('ambiguous_label',
2977
+ 'tab_by_label: ' + exactMatches.length + ' tabs share the exact label "' + label + '": ' +
2978
+ exactMatches.map(function (m) { return m.id; }).join(', ') +
2979
+ ' -- the manifest has duplicate labels; deduplicate or pass the nac_id directly',
2980
+ { candidates: exactMatches.map(function (m) { return { nac_id: m.id, label: m.label }; }) });
2981
+ } else if (fuzzyMatches.length === 1) {
2982
+ matched = { nac_id: fuzzyMatches[0].id };
2983
+ } else if (fuzzyMatches.length > 1) {
2984
+ const candidates = fuzzyMatches.map(function (m) {
2985
+ return { nac_id: m.id, label: m.label };
2986
+ });
2987
+ _emitDisambiguationRequested({
2988
+ method: 'tab_by_label', plugin: targetPlugin,
2989
+ query: { label: label },
2990
+ reason: 'ambiguous_label_fuzzy',
2991
+ candidates: candidates,
2992
+ });
2993
+ throw NacError('ambiguous_label',
2994
+ 'tab_by_label: query "' + label + '" matches ' + fuzzyMatches.length +
2995
+ ' tabs by substring: ' + fuzzyMatches.map(function (m) {
2996
+ return m.id + ' (' + m.label + ')';
2997
+ }).join(', ') + ' -- supply a more specific phrase or the nac_id',
2998
+ { candidates: candidates });
2700
2999
  }
2701
3000
  /* DOM fallback uses the canonical role only. Match against
2702
3001
  aria-label and textContent with parens stripped (the parens
2703
3002
  normalisation is legitimate -- LLMs quoting visible button
2704
3003
  text often include the parenthetical context "(collection)"
2705
- that humans wouldn't say aloud). */
3004
+ that humans wouldn't say aloud). Same two-tier strict logic. */
2706
3005
  if (!matched) {
2707
3006
  const root = document.querySelector(
2708
3007
  '[data-nac-plugin="' + targetPlugin + '"]');
2709
3008
  if (root) {
2710
3009
  const tabs = Array.prototype.slice.call(
2711
3010
  root.querySelectorAll('[data-nac-role="tab"]'));
3011
+ const domExact = [];
3012
+ const domFuzzy = [];
2712
3013
  for (let i = 0; i < tabs.length; i++) {
2713
- const txt = _norm(tabs[i].getAttribute('aria-label')
2714
- || tabs[i].textContent || '');
2715
- if (txt && (txt === lc || txt.indexOf(lc) >= 0
2716
- || lc.indexOf(txt) >= 0)) {
2717
- matched = { nac_id: tabs[i].getAttribute('data-nac-id') };
2718
- break;
2719
- }
3014
+ const txt = _norm(tabs[i].getAttribute('aria-label') || tabs[i].textContent || '');
3015
+ const id = tabs[i].getAttribute('data-nac-id');
3016
+ if (!txt || !id) continue;
3017
+ if (txt === lc) domExact.push({ id: id, label: txt });
3018
+ else if ((lc.length >= 3 && txt.indexOf(lc) >= 0) ||
3019
+ (txt.length >= 3 && lc.indexOf(txt) >= 0)) domFuzzy.push({ id: id, label: txt });
3020
+ }
3021
+ if (domExact.length === 1) {
3022
+ matched = { nac_id: domExact[0].id };
3023
+ } else if (domExact.length > 1) {
3024
+ const cand = domExact.map(function (m) { return { nac_id: m.id, label: m.label }; });
3025
+ _emitDisambiguationRequested({
3026
+ method: 'tab_by_label', plugin: targetPlugin,
3027
+ query: { label: label },
3028
+ reason: 'ambiguous_label_exact_dom',
3029
+ candidates: cand,
3030
+ });
3031
+ throw NacError('ambiguous_label',
3032
+ 'tab_by_label DOM: ' + domExact.length + ' visible tabs share the exact label "' +
3033
+ label + '" -- pass the nac_id directly',
3034
+ { candidates: cand });
3035
+ } else if (domFuzzy.length === 1) {
3036
+ matched = { nac_id: domFuzzy[0].id };
3037
+ } else if (domFuzzy.length > 1) {
3038
+ const cand = domFuzzy.map(function (m) { return { nac_id: m.id, label: m.label }; });
3039
+ _emitDisambiguationRequested({
3040
+ method: 'tab_by_label', plugin: targetPlugin,
3041
+ query: { label: label },
3042
+ reason: 'ambiguous_label_fuzzy_dom',
3043
+ candidates: cand,
3044
+ });
3045
+ throw NacError('ambiguous_label',
3046
+ 'tab_by_label DOM: query "' + label + '" matches ' + domFuzzy.length +
3047
+ ' visible tabs by substring: ' + domFuzzy.map(function (m) {
3048
+ return m.id + ' (' + m.label + ')';
3049
+ }).join(', ') + ' -- supply a more specific phrase or the nac_id',
3050
+ { candidates: cand });
2720
3051
  }
2721
3052
  }
2722
3053
  }
2723
3054
  if (!matched || !matched.nac_id) {
3055
+ /* No exact, no fuzzy, no DOM match: surface ALL visible tabs as
3056
+ options so voice / assistive can re-prompt. */
3057
+ const all = document.querySelectorAll('[data-nac-role="tab"][data-nac-id]');
3058
+ const available = [];
3059
+ for (let i = 0; i < all.length; i++) {
3060
+ const id = all[i].getAttribute('data-nac-id');
3061
+ available.push({ nac_id: id, label: _candidateLabel(all[i]) });
3062
+ }
3063
+ _emitDisambiguationRequested({
3064
+ method: 'tab_by_label', plugin: targetPlugin,
3065
+ query: { label: label },
3066
+ reason: 'no_matching_label',
3067
+ candidates: available,
3068
+ });
2724
3069
  throw NacError('not_found',
2725
3070
  'No tab matching label="' + label + '" in plugin "'
2726
- + targetPlugin + '"');
3071
+ + targetPlugin + '"',
3072
+ { candidates: available });
2727
3073
  }
2728
3074
  return await tab(targetPlugin, matched.nac_id);
2729
3075
  }
@@ -5438,8 +5784,8 @@
5438
5784
 
5439
5785
  global.NAC = {
5440
5786
  __nac_v1_installed: true,
5441
- version: '2.3.0',
5442
- spec_version: '2.3',
5787
+ version: '2.4.0',
5788
+ spec_version: '2.4',
5443
5789
  /* v2.2.0 (V22-01) -- strict validation toggle. When true,
5444
5790
  NAC.register throws on findings (manifest_role_unknown,
5445
5791
  tab_id_manifest_role_drift, manifest_dom_role_mismatch).