@nac3/runtime 2.6.0 → 2.9.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.
@@ -6,7 +6,7 @@
6
6
  =====================================================================
7
7
 
8
8
  AUTHORITATIVE VERSION CONSTANT: see the global.NAC export at the
9
- bottom of this file. `version: '2.6.0', spec_version: '2.6'`
9
+ bottom of this file. `version: '2.9.0', spec_version: '2.9'`
10
10
  is the normative declaration. The dated changelog sections below are
11
11
  historical notes; if they ever drift from the export, the export
12
12
  wins.
@@ -313,6 +313,12 @@
313
313
 
314
314
  if (global.NAC && global.NAC.__nac_v1_installed) return;
315
315
 
316
+ /* The tier this runtime declares when a host does not override it.
317
+ ONE declaration: the versioning gate and the NAC export both read
318
+ it. See the long note at the `conformance_tier` export for why a
319
+ tier is not a level, and RFC V24-04 sec 6 for the vocabulary. */
320
+ const DEFAULT_CONFORMANCE_TIER = 'NAC-3-versioned';
321
+
316
322
  /* ---------- Errors ---------------------------------------------- */
317
323
 
318
324
  function NacError(code, message, extra) {
@@ -323,6 +329,29 @@
323
329
  return e;
324
330
  }
325
331
 
332
+ /* 2.7.0 (SPEC sec 19.3) -- fail closed where there is no document.
333
+
334
+ The DOM primitives of sections 1-14 address NODES: they resolve a
335
+ name by querying the document. Called where no document exists --
336
+ Node, a worker, an SSR build, a screenless assistant -- they used
337
+ to throw a raw "ReferenceError: document is not defined" from
338
+ whatever line happened to touch it first, which tells the caller
339
+ nothing about the contract and is not a code anybody can branch
340
+ on. validate_global was worse: it returned {ok: true} for a tree
341
+ that does not exist, which is a false green.
342
+
343
+ So they refuse by name. The headless profile (sec 19) is the other
344
+ half of the same rule: a surface with no document is reached
345
+ through the extension contract (sec 15), never through these. */
346
+ function _nac_requireDocument(where) {
347
+ if (typeof document !== 'undefined' && document) return;
348
+ throw NacError('no_document',
349
+ 'NAC.' + where + ': no document in this context, so there is no node to resolve. ' +
350
+ 'Reach a declared surface through the extension contract -- NAC.call / NAC.read / ' +
351
+ 'NAC.subscribe (SPEC sec 15) -- and see the headless profile (SPEC sec 19).',
352
+ { primitive: where });
353
+ }
354
+
326
355
  /* ================================================================
327
356
  v2.5 / RFC V24-01: Plugin slug uniqueness gate (spec sec 7.4)
328
357
  ================================================================
@@ -718,13 +747,58 @@
718
747
  over the canonical bytes, truncated to the leading 128 bits
719
748
  (16 bytes), encoded as 32 lowercase hex chars. */
720
749
 
721
- function _hashIsEffectivelyVisible(el) {
722
- /* Cheap visibility check: offsetParent + style.display +
723
- style.visibility + aria-hidden. */
750
+ /* ONE definition of "visible" (TF-A12).
751
+
752
+ Until 2.7.0 there were two, both published, and they disagreed:
753
+
754
+ _hashIsEffectivelyVisible fed the `visible` key of the
755
+ concurrency hash. Looked at
756
+ aria-hidden and offsetParent. Did
757
+ NOT look at opacity.
758
+ _isVisible fed the `visible` key the AGENT
759
+ reads from a state snapshot. Looked
760
+ at opacity. Did NOT look at
761
+ aria-hidden.
762
+
763
+ So an element with `opacity: 0` was visible to one and invisible
764
+ to the other, and one with `aria-hidden="true"` was the reverse.
765
+ Two answers to one word, in one runtime, both shipped -- and the
766
+ word is load-bearing twice over: an agent decides whether to act
767
+ on an element by it, and the optimistic-concurrency gate decides
768
+ whether the page moved under the agent by it.
769
+
770
+ There was a third difference, and it was a crash rather than a
771
+ disagreement: _isVisible reached el.ownerDocument.defaultView
772
+ .getComputedStyle with NO GUARD, while this one checked for
773
+ window.getComputedStyle first. In an environment without a
774
+ defaultView -- a detached document, a server-side render, a test
775
+ harness -- one threw and the other did not.
776
+
777
+ THE DECISION, and the reasoning rather than just the outcome. The
778
+ union is the right answer, and specifically the agent's question
779
+ is the one that governs: "can this be perceived and acted on?"
780
+ Every one of the five conditions below answers no to it.
781
+ aria-hidden belongs in it because NAC3 sits next to the
782
+ accessibility tree and an element explicitly removed from that
783
+ tree is not something an agent may act on. opacity: 0 belongs in
784
+ it because a user cannot see it.
785
+
786
+ The hash gets the same predicate, which makes it slightly
787
+ stricter: a control fading to opacity 0 now changes the hash.
788
+ That is more correct for a concurrency check, not less -- it IS a
789
+ change in the observable state, which is exactly what the hash
790
+ exists to notice.
791
+
792
+ Cheap first, expensive last: the attribute and the layout box are
793
+ free, getComputedStyle is not. */
794
+ function _isPerceivable(el) {
724
795
  if (!el || el.nodeType !== 1) return false;
796
+ /* 1. explicitly removed from the accessibility tree */
725
797
  if (el.getAttribute && el.getAttribute('aria-hidden') === 'true') return false;
798
+ /* 2. not laid out. position:fixed legitimately has no
799
+ offsetParent, so a zero-sized rect is what decides, not the
800
+ null parent on its own. */
726
801
  if (typeof el.offsetParent === 'object' && el.offsetParent === null) {
727
- /* position:fixed escapes offsetParent=null. Use rect fallback. */
728
802
  if (typeof el.getBoundingClientRect === 'function') {
729
803
  const r = el.getBoundingClientRect();
730
804
  if (r.width === 0 && r.height === 0) return false;
@@ -732,13 +806,35 @@
732
806
  return false;
733
807
  }
734
808
  }
735
- if (typeof window !== 'undefined' && window.getComputedStyle) {
736
- const cs = window.getComputedStyle(el);
737
- if (cs && (cs.display === 'none' || cs.visibility === 'hidden')) return false;
809
+ /* 3. a zero-sized box, however it got that way */
810
+ if (typeof el.getBoundingClientRect === 'function') {
811
+ const r = el.getBoundingClientRect();
812
+ if (r.width === 0 && r.height === 0) return false;
813
+ }
814
+ /* 4..5. display / visibility / opacity, if anyone can tell us.
815
+ GUARDED on both paths: the document's own view first, the
816
+ global second, and neither is assumed to exist. Returning true
817
+ when nothing can be computed is deliberate -- an element we
818
+ cannot measure is reported as present rather than silently
819
+ vanishing from a snapshot. */
820
+ const view = (el.ownerDocument && el.ownerDocument.defaultView)
821
+ || (typeof window !== 'undefined' ? window : null);
822
+ if (view && typeof view.getComputedStyle === 'function') {
823
+ const cs = view.getComputedStyle(el);
824
+ if (cs && (cs.display === 'none' || cs.visibility === 'hidden' || cs.opacity === '0')) {
825
+ return false;
826
+ }
738
827
  }
739
828
  return true;
740
829
  }
741
830
 
831
+ /* Kept as a name because the hash code reads better with it, and
832
+ because a reader looking for the old function should land on the
833
+ explanation above rather than on nothing. */
834
+ function _hashIsEffectivelyVisible(el) {
835
+ return _isPerceivable(el);
836
+ }
837
+
742
838
  function _hashReadValue(el) {
743
839
  if (!el || el.nodeType !== 1) return null;
744
840
  const tag = (el.tagName || '').toLowerCase();
@@ -1018,7 +1114,7 @@
1018
1114
  and a runtime that declares NAC-3 must NOT silently honor any
1019
1115
  expected_*. */
1020
1116
  const tier = (typeof window !== 'undefined' && window.NAC &&
1021
- window.NAC.conformance_tier) || 'NAC-3-versioned';
1117
+ window.NAC.conformance_tier) || DEFAULT_CONFORMANCE_TIER;
1022
1118
  if (tier === 'NAC-3' && hasAny) {
1023
1119
  throw NacError('feature_not_supported',
1024
1120
  'Runtime tier is NAC-3 (non-versioned); expected_* parameters are not honored.',
@@ -1225,6 +1321,26 @@
1225
1321
  of identical warnings per session. Key by (event_type, field).
1226
1322
  Reset by calling NAC.__resetLegacyWarnDedup() (test-only). */
1227
1323
  const _legacyWarnSeen = Object.create(null);
1324
+ /* 2.7.0 (TF-A03) -- THE REMOVAL PROMISE IS WITHDRAWN, and this
1325
+ message is where it was being made. It said "Will be removed in
1326
+ v2.0" to every adopter's console; v2.0 shipped, so did 2.1
1327
+ through 2.6, and the fields are all still here. A promise that
1328
+ outlives three majors is not a deprecation, it is noise that
1329
+ teaches authors to ignore the warning.
1330
+
1331
+ It is withdrawn rather than kept and honoured because the fields
1332
+ are LOAD-BEARING, which no document noticed: the event matcher
1333
+ that decides whether an event belongs to an element READS
1334
+ from_nac_id / target_nac_id / over_nac_id / nac_id / id /
1335
+ step_id as resolution keys (see _eventMatchesElement below).
1336
+ Removing them would not retire six lines, it would silently
1337
+ break wait_for() and assert_event_fired() on any host that
1338
+ emits only the alias -- which is exactly the shape of host the
1339
+ aliases exist for.
1340
+
1341
+ So: the alias stays, the canonical is still the one to write,
1342
+ and the warning says that without naming a version it cannot
1343
+ keep. Decision D-12, owner delegation of 2026-11-24. */
1228
1344
  function _legacyWarn(eventType, field, canonical) {
1229
1345
  const key = eventType + '::' + field;
1230
1346
  if (_legacyWarnSeen[key]) return;
@@ -1232,7 +1348,9 @@
1232
1348
  if (typeof console !== 'undefined' && console.warn) {
1233
1349
  console.warn('[NAC] legacy_event_field: ' + eventType +
1234
1350
  ' detail.' + field + ' is a legacy alias. Use detail.' +
1235
- canonical + ' instead. Will be removed in v2.0.');
1351
+ canonical + ' instead. The alias is frozen, not scheduled ' +
1352
+ 'for removal: the event matcher resolves it (SPEC 7.4, ' +
1353
+ 'decision D-12).');
1236
1354
  }
1237
1355
  }
1238
1356
 
@@ -1513,6 +1631,60 @@
1513
1631
  return null;
1514
1632
  }
1515
1633
 
1634
+ /* 2.7.0 -- `undrivable_until`, the declaration of a gated surface.
1635
+
1636
+ THE DEFECT IT ANSWERS, measured on this project's own landing page
1637
+ on 2026-11-25 with the probe that 2.7.0 added:
1638
+ `validate_global({probe: true})` reported seven
1639
+ nac_id_declared_not_reachable findings -- chat.lang, chat.tts,
1640
+ chat.mic, chat.voice.always_on, chat.log, chat.input, chat.send.
1641
+ All seven are real, all seven are declared, and all seven live
1642
+ inside a panel that stays behind `aria-hidden="true"` until
1643
+ somebody opens it.
1644
+
1645
+ Before this field the protocol had no way to say that, so the two
1646
+ parties both lost. An AGENT read a manifest advertising seven
1647
+ addressable ids, called click() on one of them and got
1648
+ NacError('hidden') with nothing to do about it -- the surface
1649
+ exists, is declared, and the one thing it needed to know (open the
1650
+ panel first) was the one thing nobody wrote down. And an AUTHOR
1651
+ with a legitimately gated panel had no honest way to reach
1652
+ conformance level 3, which asks for zero findings: the only moves
1653
+ available were to stop declaring the surface (worse for the agent)
1654
+ or to stop painting it until opened (a rewrite of the widget).
1655
+
1656
+ So an element may now declare the id that opens it:
1657
+
1658
+ { id: 'chat.mic', role: 'action',
1659
+ undrivable_until: 'nac_landing.chat.toggle' }
1660
+
1661
+ and three things follow. The probe stops calling it a defect and
1662
+ reports it in its own `gated` bucket, which is NOT a finding.
1663
+ click() still refuses it while it is hidden -- the element really
1664
+ is unreachable, and failing closed is the whole point -- but the
1665
+ rejection now NAMES the gate, so the agent's next move is in the
1666
+ error it just got. And the declaration is checked: a gate that is
1667
+ not declared, not mounted, or itself unreachable is an ERROR, a
1668
+ harder finding than the warn it replaces. A promised way in that
1669
+ does not open is worse than no promise, because an agent will
1670
+ wait for it.
1671
+
1672
+ Fail-closed by construction: no field means no change, for every
1673
+ page already published. */
1674
+ function _resolveGate(nac_id) {
1675
+ for (const slug in _manifests) {
1676
+ const m = _manifests[slug];
1677
+ if (!m) continue;
1678
+ const all = (m.elements || []).concat(m.tabs || []);
1679
+ for (let i = 0; i < all.length; i++) {
1680
+ const e = all[i];
1681
+ if (!e || e.id !== nac_id) continue;
1682
+ return e.undrivable_until ? String(e.undrivable_until) : null;
1683
+ }
1684
+ }
1685
+ return null;
1686
+ }
1687
+
1516
1688
  function _hasCapability(cap) {
1517
1689
  if (!cap) return true;
1518
1690
  if (Array.isArray(cap)) {
@@ -1566,9 +1738,135 @@
1566
1738
  'draggable', 'drop-target',
1567
1739
  /* Tolerated for legacy buttons that just need to be clickable
1568
1740
  without contract. Falls back to action behaviour at runtime. */
1569
- 'button'
1741
+ 'button',
1742
+
1743
+ /* ---- v2.8.0: the surface vocabulary (SPEC.md 1.2) ------------
1744
+ THE DEFECT THIS CLOSES. Measured on this tree on 2026-11-25:
1745
+ the normative table declared 20 roles, the tree USED 67, and
1746
+ 52 of those were declared nowhere -- not here, not in the
1747
+ spec table, not in the click completion map. Every one of
1748
+ them had been written into a page by somebody who needed the
1749
+ word, and the protocol's answer was to treat it as `action`
1750
+ and wait five seconds for an event that role never emits.
1751
+
1752
+ This Set is the runtime's half of the contract and section 1
1753
+ of SPEC.md is the document's half. They are hand-written in
1754
+ two places on purpose -- the runtime must refuse an unknown
1755
+ role with no network and no spec file at hand -- and from
1756
+ 2.8.0 scripts/check-role-registries.mjs refuses the build
1757
+ when the two halves disagree. Before that gate existed the
1758
+ two lists had already drifted once (the spec table carried
1759
+ draggable / drop-target for four minor versions while the
1760
+ lint's copy did not), so this is not a hypothetical. */
1761
+
1762
+ /* Maps. The interior is drawn, not marked up. */
1763
+ 'map', 'map-layer', 'map-marker',
1764
+ /* Charts: chart-series is the operable part, chart-point the
1765
+ readable one. */
1766
+ 'chart', 'chart-series', 'chart-point',
1767
+ 'calendar', 'calendar-event',
1768
+ /* tree-children exists as a role because a collapsed subtree is
1769
+ IN the DOM and not operable, and that is the distinction an
1770
+ agent has to be able to make. */
1771
+ 'tree', 'tree-node', 'tree-children',
1772
+ 'timeline', 'timeline-item',
1773
+ 'carousel', 'carousel-slide',
1774
+ /* Live regions. One-to-one with ARIA on purpose. `feedback` is
1775
+ narrower than `status` and is what NAC.read_feedback() reads. */
1776
+ 'status', 'log', 'toast', 'toast-region', 'banner', 'feedback',
1777
+ /* Overlays. `modal` is the general case of `confirm-dialog`. */
1778
+ 'modal', 'drawer', 'bottom-sheet',
1779
+ /* Controls whose value is not their text: these are what tell an
1780
+ agent to resolve through options() instead of typing. */
1781
+ 'combobox', 'listbox', 'slider', 'richtext',
1782
+ /* The containers of controls that were already declared. */
1783
+ 'tablist', 'tabpanel', 'stepper', 'accordion-section',
1784
+ 'breadcrumb', 'pagination-control',
1785
+ /* Identity, and the state of the interface itself. `skeleton`
1786
+ means NOT LOADED YET and `empty-state` means NOTHING HERE,
1787
+ AND THAT IS NOT AN ERROR -- the difference between waiting,
1788
+ moving on, and reporting a problem. */
1789
+ 'avatar', 'presence-indicator', 'skeleton', 'empty-state',
1790
+ /* Structure. Every one of these is consumed by something: three
1791
+ are queried by this runtime, `list` hosts reorder(), and
1792
+ `canvas` is the door section 15.12 assigned to that surface. */
1793
+ 'list', 'row', 'menu', 'label', 'value', 'paragraph', 'canvas',
1794
+
1795
+ /* ---- v2.9.0: the document vocabulary (SPEC.md 1.2) ----------
1796
+ THE DEFECT THIS CLOSES, and it was this project's own site.
1797
+ Measured 2026-11-27 with the PUBLISHED validator over the
1798
+ whole tree: 45 677 elements across 526 pages carried a role
1799
+ the specification did not declare, and they were not written
1800
+ by hand -- a single producer emits them,
1801
+ scripts/build-spec-html.mjs, which renders the normative text
1802
+ itself as a NAC3 page. So the document that declares the
1803
+ vocabulary was being served marked up in words it did not
1804
+ declare, 354 times per page.
1805
+
1806
+ Why declaring them is the right half of the fix rather than
1807
+ un-painting them: these are document structure, and under
1808
+ section 19 reading a document is a capability, not a side
1809
+ effect of having a screen. An agent with no screen navigates
1810
+ prose by heading; code says the text inside must be read
1811
+ verbatim rather than paraphrased. list and paragraph were
1812
+ already declared, so list-item and heading missing was half a
1813
+ family, which is why the count was in the tens of thousands.
1814
+
1815
+ All five are read-only: they go in _CLICK_NO_EVENT_ROLES
1816
+ below, never in the click family map, because putting a
1817
+ read-only role in that map would make click() promise a
1818
+ completion nobody emits. */
1819
+ 'heading', 'list-item', 'code', 'code-inline', 'note'
1570
1820
  ]);
1571
1821
 
1822
+ /* ---- Declared aliases (SPEC.md 1.5) ---------------------------
1823
+ Seven spellings this tree had grown for roles that already had a
1824
+ name. They are RESOLVED, not rejected: a spelling that ever
1825
+ worked keeps working (section 12 promise 2), and the migration
1826
+ of a tree is a decision its owner makes one page at a time, not
1827
+ something an upgrade imposes.
1828
+
1829
+ Resolution happens in _canonicalRole() below, before anything
1830
+ else in the runtime looks at a role -- so an alias reaches the
1831
+ known-role check, the click completion map and the manifest
1832
+ validator already spelled canonically. The static lint reports
1833
+ them as `dom_role_legacy_spelling` at severity warn, which is
1834
+ how a tree gets migrated deliberately.
1835
+
1836
+ NOT in this table, measured and kept as roles of their own:
1837
+ `feedback` (NAC.read_feedback() filters on it), `label`, `row`,
1838
+ `toast`, `toast-region` and `banner` (this runtime queries each
1839
+ of them by selector). A role the implementation reads is part
1840
+ of the contract whether the document said so or not. */
1841
+ const _ROLE_ALIASES = {
1842
+ 'treenode': 'tree-node',
1843
+ 'timeline-entry': 'timeline-item',
1844
+ 'input': 'field',
1845
+ 'textbox': 'field',
1846
+ 'panel': 'region',
1847
+ 'fab': 'action',
1848
+ 'dropzone': 'drop-target'
1849
+ };
1850
+
1851
+ /* Roles registered at runtime by a host (NAC.register_role, v2.8).
1852
+ Kept apart from _KNOWN_ROLES_V22 so introspection can always
1853
+ say which half of the vocabulary a role came from: the protocol
1854
+ or this page. */
1855
+ const _REGISTERED_ROLES = new Map();
1856
+
1857
+ function _canonicalRole(role) {
1858
+ if (!role) return role;
1859
+ const r = String(role);
1860
+ return Object.prototype.hasOwnProperty.call(_ROLE_ALIASES, r)
1861
+ ? _ROLE_ALIASES[r]
1862
+ : r;
1863
+ }
1864
+
1865
+ function _roleIsKnown(role) {
1866
+ const r = _canonicalRole(role);
1867
+ return _KNOWN_ROLES_V22.has(r) || _REGISTERED_ROLES.has(r);
1868
+ }
1869
+
1572
1870
  function _v22Emit(severity, code, nac_id, message, detail) {
1573
1871
  const fn = severity === 'error'
1574
1872
  ? (typeof console !== 'undefined' && console.error ? console.error.bind(console) : null)
@@ -1592,7 +1890,7 @@
1592
1890
  if (!id) return; /* spec-level error caught elsewhere */
1593
1891
 
1594
1892
  /* Check 1: role enumeration. */
1595
- if (role && !_KNOWN_ROLES_V22.has(role)) {
1893
+ if (role && !_roleIsKnown(role)) {
1596
1894
  findings.push({
1597
1895
  code: 'manifest_role_unknown',
1598
1896
  nac_id: id,
@@ -1601,6 +1899,26 @@
1601
1899
  detail: { plugin: slug, source: source, role: role }
1602
1900
  });
1603
1901
  }
1902
+ /* v2.8.0: a declared alias (SPEC.md 1.5) is legal, and is
1903
+ REPORTED WITHOUT JOINING `findings` -- emitted straight at
1904
+ warn severity instead.
1905
+
1906
+ That distinction is the whole point, and the first draft of
1907
+ this block got it wrong: every entry of `findings` is emitted
1908
+ as an error AND makes register() throw under
1909
+ STRICT_VALIDATION, which has been the default since 2.3. So
1910
+ pushing this one would have meant that a page using a spelling
1911
+ v2.8 declares legal stops registering at all on upgrade --
1912
+ breaking exactly the adopter the alias table exists to
1913
+ protect, in the same release that promised not to. The suite
1914
+ that caught it is runtime/test/role-vocabulary.mjs. */
1915
+ if (role && role !== _canonicalRole(role)) {
1916
+ _v22Emit('warn', 'manifest_role_legacy_spelling', id,
1917
+ 'plugin "' + slug + '" id="' + id + '" uses the legacy role spelling "' +
1918
+ role + '"; the canonical role is "' + _canonicalRole(role) +
1919
+ '" (SPEC.md 1.5). The alias resolves, so nothing is broken today.',
1920
+ { plugin: slug, source: source, role: role, canonical: _canonicalRole(role) });
1921
+ }
1604
1922
 
1605
1923
  /* Check 2: tab-id naming convention -- id like "tab.X" MUST
1606
1924
  have role 'tab'. Catches the role drift class that broke
@@ -2112,10 +2430,60 @@
2112
2430
  _emitAck('nac_editor.delete_selection');
2113
2431
  }
2114
2432
  async function aiCorrectSyntax() {
2115
- status.textContent = 'asking AI...';
2116
2433
  const original = textarea.value;
2434
+
2435
+ /* OFF UNTIL THE HOST SAYS WHERE (TF-A11).
2436
+
2437
+ What this did before 2.7.0: it POSTed the ENTIRE contents of
2438
+ the edited textarea to
2439
+
2440
+ (window.NacChat && window.NacChat._endpoint)
2441
+ || '/crm/api/v1/yujin/nac-demo'
2442
+
2443
+ -- a default nobody on the host side had declared. The matter
2444
+ is narrower than it first looks and worth stating precisely:
2445
+ the path is RELATIVE, so the request went to the host's own
2446
+ origin, not to a third party. This was never a leak to
2447
+ yujin.app from an adopter's page.
2448
+
2449
+ It was still wrong, for two reasons that survive that
2450
+ correction:
2451
+
2452
+ 1. a library does not get to send the user's text anywhere,
2453
+ not even to the host's own server, without the host
2454
+ asking. The host may have no handler on that path, may
2455
+ log request bodies, may be under a data-handling
2456
+ agreement that says what leaves the browser. That is the
2457
+ host's call to make and it was made for them.
2458
+ 2. the only way to change it lived in ANOTHER FILE. An
2459
+ adopter who loads js/nac.js alone -- the documented way
2460
+ to get the runtime -- had no handle to redirect it and no
2461
+ way to switch it off.
2462
+
2463
+ So the endpoint is now declared, and on THIS file's export so
2464
+ loading the runtime alone is enough:
2465
+
2466
+ NAC.editor_ai_endpoint = '/my/own/handler';
2467
+
2468
+ With nothing declared and no chat client loaded, nothing is
2469
+ sent and the control says so. The action stays declared in the
2470
+ manifest and the button stays bound: an agent that invokes it
2471
+ gets an honest "not configured" instead of the control
2472
+ vanishing from the contract between one page and the next.
2473
+ NacChat's endpoint is still honoured when the host loaded the
2474
+ chat client, because that IS the host declaring one. */
2475
+ const endpoint = (global.NAC && global.NAC.editor_ai_endpoint)
2476
+ || (window.NacChat && window.NacChat._endpoint)
2477
+ || null;
2478
+ if (!endpoint) {
2479
+ status.textContent = 'AI correction is not configured: set NAC.editor_ai_endpoint'
2480
+ + ' to the handler that should receive the text. Nothing was sent.';
2481
+ _emitAck('nac_editor.ai_correct_syntax');
2482
+ return;
2483
+ }
2484
+
2485
+ status.textContent = 'asking AI...';
2117
2486
  try {
2118
- const endpoint = (window.NacChat && window.NacChat._endpoint) || '/crm/api/v1/yujin/nac-demo';
2119
2487
  const resp = await fetch(endpoint, {
2120
2488
  method: 'POST',
2121
2489
  headers: { 'Content-Type': 'application/json' },
@@ -2205,18 +2573,37 @@
2205
2573
  let manifest;
2206
2574
  if (typeof arg1 === 'string' && arg2 && typeof arg2 === 'object') {
2207
2575
  manifest = arg2;
2208
- if (!manifest.plugin_slug) manifest.plugin_slug = arg1;
2209
2576
  } else {
2210
2577
  manifest = arg1;
2211
2578
  }
2212
2579
  if (!manifest || typeof manifest !== 'object') {
2213
2580
  throw NacError('invalid', 'manifest object required');
2214
2581
  }
2582
+ /* 2.7.0 (sec 7.2): the signed body is the manifest AS THE HOST
2583
+ BUILT IT. Snapshot it here, before the three defaults below
2584
+ change the bytes -- a host that signs {plugin_slug, elements}
2585
+ and calls register('invoice', m) would otherwise sign one
2586
+ object and have the runtime verify another, and the failure
2587
+ would look like a bad secret. */
2588
+ const _signedBody = (manifest.provenance && manifest.provenance.signature)
2589
+ ? _manifestCanonicalString(manifest)
2590
+ : null;
2591
+ if (typeof arg1 === 'string' && arg2 === manifest && !manifest.plugin_slug) {
2592
+ manifest.plugin_slug = arg1;
2593
+ }
2215
2594
  const slug = String(manifest.plugin_slug || '').trim();
2216
2595
  if (!slug) throw NacError('invalid', 'manifest.plugin_slug required');
2217
2596
  if (!manifest.version) manifest.version = '1.0.0';
2218
2597
  if (!manifest.nac_version) manifest.nac_version = '1.0';
2219
2598
 
2599
+ /* 2.7.0 (sec 7.2, TF-A17): manifest authenticity. Throws when a
2600
+ provenance.signature is present and no registered tenant secret
2601
+ matches it; records what it could tell either way, so a
2602
+ validator can ask NAC.manifest_provenance(slug) instead of
2603
+ assuming. No secret registered = no check and no change for
2604
+ every adopter who never set one. */
2605
+ _recordManifestProvenance(slug, manifest, _signedBody);
2606
+
2220
2607
  /* v2.5 / RFC V24-01 -- synchronous slug uniqueness gate.
2221
2608
  Throws NacError('duplicate_plugin_no_instance_id', ...) when
2222
2609
  the DOM already contains multiple roots for this slug and any
@@ -2419,6 +2806,12 @@
2419
2806
  function unregister(slug) {
2420
2807
  delete _manifests[slug];
2421
2808
  delete _instances[slug];
2809
+ /* 2.7.0 (sec 7.2): the authenticity record is about the manifest
2810
+ that WAS registered. Leaving it behind would let a validator
2811
+ read "verified" for a plugin that is no longer mounted. */
2812
+ if (typeof _manifestProvenance !== 'undefined') {
2813
+ delete _manifestProvenance[slug];
2814
+ }
2422
2815
  }
2423
2816
 
2424
2817
  function manifest(slug) {
@@ -2450,17 +2843,24 @@
2450
2843
  in one atomic step. Single source of truth for OCC. */
2451
2844
  function syncPlugin(arg1, arg2) {
2452
2845
  let m;
2846
+ let twoArg = false;
2453
2847
  if (typeof arg1 === 'string' && arg2 && typeof arg2 === 'object') {
2454
2848
  /* (slug, manifest) form -- match register's calling convention. */
2455
2849
  m = Object.assign({}, arg2);
2456
- if (!m.plugin_slug) m.plugin_slug = arg1;
2850
+ twoArg = true;
2851
+ /* 2.7.0 (sec 7.2): plugin_slug used to be injected HERE, which
2852
+ changed the bytes of a signed manifest before register() could
2853
+ hash them -- a host that signed {elements} and called
2854
+ syncPlugin('invoice', m) got a signature_mismatch that looked
2855
+ like a wrong secret. register() injects it now, after taking
2856
+ its snapshot, and both call forms go through that one place. */
2457
2857
  } else if (arg1 && typeof arg1 === 'object') {
2458
2858
  m = arg1;
2459
2859
  } else {
2460
2860
  throw NacError('invalid',
2461
2861
  'syncPlugin: requires (manifest) or (slug, manifest)');
2462
2862
  }
2463
- const slug = m.plugin_slug;
2863
+ const slug = m.plugin_slug || (twoArg ? arg1 : null);
2464
2864
  if (!slug || typeof slug !== 'string') {
2465
2865
  throw NacError('invalid',
2466
2866
  'syncPlugin: manifest.plugin_slug required (non-empty string)');
@@ -2476,7 +2876,7 @@
2476
2876
  /* Delegate to register() so validation + storage code-path stays
2477
2877
  exactly one place. If register throws (strict validation), the
2478
2878
  prior entry is GONE -- caller's responsibility to handle. */
2479
- register(m);
2879
+ if (twoArg) register(arg1, m); else register(m);
2480
2880
  /* Bump V24-04 OCC version on REPLACE only. First-add is a normal
2481
2881
  register: the boot tree_version already reflects the new plugin
2482
2882
  and subscribers do not need to refresh anything that did not
@@ -2527,7 +2927,14 @@
2527
2927
 
2528
2928
  Provenance on document:
2529
2929
  nac:authority:requested / :granted / :denied / :revoked / :expired
2530
- nac:action:confirmed / :rejected */
2930
+ nac:action:confirmed
2931
+
2932
+ (2.8.0: this comment used to name `nac:action:rejected` as well.
2933
+ No call site produces it -- the comment was the only place that
2934
+ name existed, which is the same defect as an event the spec names
2935
+ and the runtime never emits, one layer in. Found by
2936
+ scripts/check-event-vocabulary.mjs, which now refuses both
2937
+ directions.) */
2531
2938
 
2532
2939
  const _V25_SCOPE_RANK = { low: 1, medium: 2, high: 3 };
2533
2940
  const _v25_authority_grants = new Map();
@@ -2787,10 +3194,12 @@
2787
3194
  }
2788
3195
 
2789
3196
  function _allElements() {
3197
+ _nac_requireDocument('find');
2790
3198
  return _deepQueryAll('[data-nac-id]', document, 0);
2791
3199
  }
2792
3200
 
2793
3201
  function _activePlugin() {
3202
+ _nac_requireDocument('find');
2794
3203
  /* Most recently mounted plugin with state=ready wins. Falls back
2795
3204
  to topmost plugin root in the DOM order. */
2796
3205
  const plugins = Array.prototype.slice.call(
@@ -2901,17 +3310,18 @@
2901
3310
  return null;
2902
3311
  }
2903
3312
 
3313
+ /* The agent-facing `visible`. One predicate with the hash since
3314
+ 2.7.0 -- see the long note on _isPerceivable for why the two used
3315
+ to disagree and which way the disagreement was settled. This also
3316
+ stops throwing in an environment with no defaultView. */
2904
3317
  function _isVisible(el) {
2905
- if (!el || !el.getBoundingClientRect) return false;
2906
- const r = el.getBoundingClientRect();
2907
- if (r.width === 0 && r.height === 0) return false;
2908
- const cs = el.ownerDocument.defaultView.getComputedStyle(el);
2909
- return cs.display !== 'none' && cs.visibility !== 'hidden' && cs.opacity !== '0';
3318
+ return _isPerceivable(el);
2910
3319
  }
2911
3320
 
2912
3321
  /* ---------- Public read API ------------------------------------- */
2913
3322
 
2914
3323
  function describe() {
3324
+ _nac_requireDocument('describe');
2915
3325
  const plugins = Array.prototype.slice.call(
2916
3326
  document.querySelectorAll('[data-nac-plugin]')
2917
3327
  ).map(function (root) {
@@ -2980,6 +3390,152 @@
2980
3390
  });
2981
3391
  }
2982
3392
 
3393
+ /* ---- NAC.register_role(name, spec) (v2.8.0, SPEC.md 1.4) ------
3394
+ THE PROBLEM THIS SOLVES. The nineteen pieces of work that built
3395
+ the v2.8 vocabulary all shared one assumption: that adding a
3396
+ role means editing the protocol. Six layers, two of them
3397
+ published, one of them in nine languages. That is why the 52
3398
+ undeclared roles of 2026-11-25 existed at all -- somebody
3399
+ needed a word, the only door open was writing it into the HTML
3400
+ and hoping nobody looked, and for four years nobody did,
3401
+ because no rule compared the markup against the vocabulary.
3402
+
3403
+ So the vocabulary gets a door. A host declares a role at
3404
+ runtime, with the completion events it answers with, and from
3405
+ that moment:
3406
+ - the manifest validator accepts it instead of reporting
3407
+ manifest_role_unknown,
3408
+ - click() waits for ITS events instead of falling back to the
3409
+ action family and timing out at five seconds,
3410
+ - describe() / roles() report where it came from.
3411
+
3412
+ THE HARD PART, and how it is answered. A registered role exists
3413
+ only while the page is loaded, and the static lint runs with no
3414
+ page -- reading files. A role registered in JavaScript is
3415
+ invisible to it, so the lint would report a page as wrong for
3416
+ using a role that page itself declares. The answer is NOT to
3417
+ make the lint execute the page (a validator that runs the code
3418
+ it is validating has stopped being a validator). It is a second
3419
+ declaration the lint CAN read: a `nac3.roles.json` next to the
3420
+ markup, with the same shape as this argument. Two declarations
3421
+ of one fact is exactly the producer/consumer asymmetry this
3422
+ release spent its time removing, so it is not left to good
3423
+ intentions: `npx nac3 lint` reports role_registration_undeclared
3424
+ when a page calls register_role for a role its
3425
+ nac3.roles.json does not carry, and role_registration_orphan in
3426
+ the other direction.
3427
+
3428
+ WHAT IT REFUSES, and why each refusal is not negotiable:
3429
+ - a canonical role (SPEC.md 1.1 / 1.2). A page cannot
3430
+ redefine `action`: an agent that trusted the protocol's
3431
+ meaning of a canonical role would be reading a different
3432
+ contract on every page. This is the whole value of a closed
3433
+ vocabulary and a registry does not get to open it.
3434
+ - a declared alias (SPEC.md 1.5). Same reason, one level down.
3435
+ - a name that is not /^[a-z][a-z0-9-]*$/. Ids are opaque and
3436
+ roles are not: a role is compared, printed and published.
3437
+ - an event name that is not `nac:*`. A completion event that
3438
+ does not belong to this protocol cannot be waited for by
3439
+ anything that speaks it.
3440
+ Re-registering the SAME role with the SAME spec is idempotent
3441
+ and returns ok -- a page that registers on every render must not
3442
+ fail on the second one. Re-registering with a DIFFERENT spec
3443
+ throws: that is the one case where silence would leave two
3444
+ meanings for one word, which is where this release started. */
3445
+ function register_role(name, spec) {
3446
+ const raw = String(name == null ? '' : name);
3447
+ if (!/^[a-z][a-z0-9-]*$/.test(raw)) {
3448
+ throw NacError('invalid_role',
3449
+ 'register_role: "' + raw + '" is not a legal role name. A role is lowercase'
3450
+ + ' letters, digits and hyphens, starting with a letter (SPEC.md 1.4).');
3451
+ }
3452
+ if (_KNOWN_ROLES_V22.has(raw)) {
3453
+ throw NacError('role_is_canonical',
3454
+ 'register_role: "' + raw + '" is a canonical role of SPEC.md section 1 and cannot be'
3455
+ + ' redefined. An agent relies on a canonical role meaning the same thing on every'
3456
+ + ' page; a page that could change it would be publishing a different protocol.');
3457
+ }
3458
+ if (Object.prototype.hasOwnProperty.call(_ROLE_ALIASES, raw)) {
3459
+ throw NacError('role_is_alias',
3460
+ 'register_role: "' + raw + '" is a declared alias of "' + _ROLE_ALIASES[raw] +
3461
+ '" (SPEC.md 1.5) and cannot be redefined.');
3462
+ }
3463
+ spec = spec || {};
3464
+ const events = Array.isArray(spec.events) ? spec.events.slice(0, 2) : [];
3465
+ for (const ev of events) {
3466
+ if (typeof ev !== 'string' || ev.indexOf('nac:') !== 0) {
3467
+ throw NacError('invalid_role',
3468
+ 'register_role("' + raw + '"): completion event "' + String(ev) + '" is not a NAC3'
3469
+ + ' event name. A completion event must be nac:<family>:<name> so anything that'
3470
+ + ' speaks this protocol can wait for it (SPEC.md 6.4).');
3471
+ }
3472
+ }
3473
+ const entry = {
3474
+ role: raw,
3475
+ events: events,
3476
+ clickable: events.length > 0,
3477
+ describes: (typeof spec.describes === 'string') ? spec.describes : null,
3478
+ plugin: (typeof spec.plugin === 'string') ? spec.plugin : null,
3479
+ source: 'registered'
3480
+ };
3481
+ const prior = _REGISTERED_ROLES.get(raw);
3482
+ if (prior) {
3483
+ /* Idempotent on an identical re-registration: a page that
3484
+ registers its roles on every render must not fail on the
3485
+ second render. Different spec, same name -> throw, because
3486
+ that is two meanings for one word. */
3487
+ if (JSON.stringify(prior) === JSON.stringify(entry)) {
3488
+ return { ok: true, role: raw, already: true };
3489
+ }
3490
+ throw NacError('role_conflict',
3491
+ 'register_role("' + raw + '"): already registered with a different definition.'
3492
+ + ' Prior events=[' + prior.events.join(', ') + '], new events=[' +
3493
+ events.join(', ') + ']. Two definitions of one role is the drift this'
3494
+ + ' registry exists to prevent.');
3495
+ }
3496
+ _REGISTERED_ROLES.set(raw, entry);
3497
+ try {
3498
+ document.dispatchEvent(new CustomEvent('nac:role_registered', {
3499
+ detail: { role: raw, events: events, clickable: entry.clickable,
3500
+ describes: entry.describes, plugin: entry.plugin },
3501
+ bubbles: true
3502
+ }));
3503
+ } catch (_) { /* headless (section 19): no document to dispatch on */ }
3504
+ return { ok: true, role: raw, already: false };
3505
+ }
3506
+
3507
+ /* NAC.roles() -- the vocabulary, with the provenance of every
3508
+ word. Built so a consumer never has to ask which half of the
3509
+ contract a role came from: `canonical` is the protocol,
3510
+ `registered` is this page, `aliases` is what resolves to what.
3511
+ Published as data for the same reason section 1 is: a list a
3512
+ consumer has to reconstruct from prose is a list that rots. */
3513
+ function roles() {
3514
+ const registered = [];
3515
+ _REGISTERED_ROLES.forEach(function (v) { registered.push(v); });
3516
+ const click_events = {};
3517
+ for (const r in _CLICK_EVENT_FAMILY) {
3518
+ if (Object.prototype.hasOwnProperty.call(_CLICK_EVENT_FAMILY, r)) {
3519
+ click_events[r] = _CLICK_EVENT_FAMILY[r].slice();
3520
+ }
3521
+ }
3522
+ return {
3523
+ spec_version: '2.9',
3524
+ canonical: Array.from(_KNOWN_ROLES_V22),
3525
+ aliases: Object.assign({}, _ROLE_ALIASES),
3526
+ registered: registered,
3527
+ click_events: click_events,
3528
+ no_click_event: Array.from(_CLICK_NO_EVENT_ROLES)
3529
+ };
3530
+ }
3531
+
3532
+ /* NAC.canonical_role(role) -- what a spelling means. One line, and
3533
+ it exists because every consumer that compares a role to a
3534
+ constant needs the same answer this runtime gives itself. */
3535
+ function canonical_role(role) {
3536
+ return _canonicalRole(role);
3537
+ }
3538
+
2983
3539
  function snapshot_state() {
2984
3540
  const errs = _allElements()
2985
3541
  .filter(function (el) {
@@ -3143,7 +3699,11 @@
3143
3699
  const _CLICK_EVENT_FAMILY = {
3144
3700
  'action': ['nac:action:succeeded', 'nac:action:failed'],
3145
3701
  'option': ['nac:field:changed'],
3146
- 'tab': ['nac:tab:activated'],
3702
+ /* v2.8.0: the failure half. nac:tab:activation_failed has been
3703
+ emitted since v2.2 and was not in this map, so click() on a
3704
+ tab whose activation was REFUSED waited out its full timeout
3705
+ instead of rejecting the moment the refusal arrived. */
3706
+ 'tab': ['nac:tab:activated', 'nac:tab:activation_failed'],
3147
3707
  'breadcrumb-item': ['nac:breadcrumb:navigated'],
3148
3708
  'accordion-toggle': ['nac:accordion:expanded', 'nac:accordion:collapsed'],
3149
3709
  'step': ['nac:step:advanced'],
@@ -3164,8 +3724,106 @@
3164
3724
  column_nac_id and filter_nac_id as nac_id matches. */
3165
3725
  'sort-control': ['nac:table:sort_changed'],
3166
3726
  'filter-control': ['nac:table:filter_changed'],
3727
+ /* v2.7.0: `button` made EXPLICIT. SPEC.md section 1 says the
3728
+ runtime treats this role as `action`, and it did -- but only by
3729
+ falling through the `||` below, which is indistinguishable from
3730
+ a role nobody thought about. The fallback was right for this one
3731
+ role and wrong for the other eight, and nothing told them
3732
+ apart. Declaring it costs one line and removes the ambiguity
3733
+ that let the other eight hide. */
3734
+ 'button': ['nac:action:succeeded', 'nac:action:failed'],
3735
+
3736
+ /* ---- v2.8.0: the twelve clickable surface roles -------------
3737
+ Each line removes one five-second timeout that blamed the
3738
+ page. The runtime ALREADY emitted every event named here --
3739
+ nac:map:marker_selected has existed since 2.5 -- so the
3740
+ defect was never that the signal was missing: it was that
3741
+ click() did not know the signal belonged to that role, took
3742
+ the `|| _CLICK_EVENT_FAMILY['action']` fallback below, waited
3743
+ for nac:action:succeeded, heard nothing and reported that the
3744
+ WIDGET had not acknowledged. The project paid this twice
3745
+ before (v1.6.4 for `field`, v1.6.6 for `sort-control`, both
3746
+ comments above) and both times fixed one role instead of the
3747
+ class. These twelve are the class.
3748
+
3749
+ Where two events existed for the same thing, the canonical
3750
+ one is here and the other stays emitted (SPEC.md 6.4). */
3751
+ 'map-marker': ['nac:map:marker_selected'],
3752
+ 'map-layer': ['nac:map:layer_toggled'],
3753
+ 'chart-series': ['nac:chart:series_toggled'],
3754
+ 'calendar-event': ['nac:calendar:event_selected'],
3755
+ 'tree-node': ['nac:tree:selected'],
3756
+ 'carousel-slide': ['nac:carousel:slide_changed'],
3757
+ 'toast': ['nac:toast:dismissed'],
3758
+ 'banner': ['nac:banner:dismissed'],
3759
+ 'combobox': ['nac:field:changed'],
3760
+ 'listbox': ['nac:field:changed'],
3761
+ 'slider': ['nac:slider:value_changed'],
3762
+ 'richtext': ['nac:richtext:format_applied'],
3167
3763
  };
3168
3764
 
3765
+ /* The canonical roles that have NO completion event of their own,
3766
+ declared rather than left to the fallback.
3767
+
3768
+ THE DEFECT THIS CLOSES (TF-A14). _CLICK_EVENT_FAMILY knew 11 of
3769
+ the 20 canonical roles of SPEC.md section 1, and click() on
3770
+ anything else took `|| _CLICK_EVENT_FAMILY['action']` -- so it
3771
+ waited for nac:action:succeeded, heard nothing, timed out after
3772
+ five seconds and reported that the WIDGET had not acked. An agent
3773
+ doing exactly what the protocol tells it to do about one of these
3774
+ roles paid five seconds and got a message blaming the page.
3775
+
3776
+ And it is not hypothetical. The comments above record the same
3777
+ shape twice already: v1.6.4 for `field`, v1.6.6 for
3778
+ `sort-control`. Both were found by someone watching a click hang.
3779
+
3780
+ These nine are STRUCTURAL -- a plugin, a section, a region, a
3781
+ navigation landmark, a data-table host, a confirm dialog -- or
3782
+ are driven by their own verb rather than by click: a draggable and
3783
+ a drop target are what drag_drop() moves. None of them has a
3784
+ completion event in the protocol, so there is nothing for click()
3785
+ to wait for.
3786
+
3787
+ WHAT DOES NOT CHANGE, on purpose: click() still clicks them and
3788
+ still listens for the action family, because a host is free to
3789
+ make a region clickable and emit nac:action:succeeded, and that
3790
+ works today. Refusing outright would break those hosts for the
3791
+ sake of a tidier error. What changes is that the TIMEOUT now says
3792
+ what actually happened instead of blaming the widget -- see the
3793
+ rejection in click(). */
3794
+ const _CLICK_NO_EVENT_ROLES = new Set([
3795
+ 'plugin', 'section', 'region', 'navigation', 'data-table',
3796
+ 'confirm-dialog', 'draggable', 'drop-target',
3797
+
3798
+ /* ---- v2.8.0 ------------------------------------------------
3799
+ Thirty-three more, and declaring them is the whole point: a
3800
+ role in this Set gets a timeout message that says "this role
3801
+ has no completion event in the protocol", and a role in
3802
+ NEITHER map gets "no completion event is declared for this
3803
+ role" -- which is the protocol admitting a gap instead of
3804
+ blaming the widget. Until 2.8.0 these thirty-three were in
3805
+ neither map and were indistinguishable from a typo.
3806
+
3807
+ Why each is here rather than in the family map above: four
3808
+ are structural hosts (map, chart, calendar, tree, timeline,
3809
+ carousel, list), six are containers whose CONTROL carries the
3810
+ event (tablist, tabpanel, stepper, accordion-section,
3811
+ breadcrumb, pagination-control, toast-region), and the rest
3812
+ are read-only. Putting a read-only role in the family map
3813
+ would make click() promise a completion nobody emits, which
3814
+ is worse than the omission it would be fixing. */
3815
+ 'map', 'chart', 'chart-point', 'calendar',
3816
+ 'tree', 'tree-children', 'timeline', 'timeline-item',
3817
+ 'carousel', 'status', 'log', 'toast-region', 'feedback',
3818
+ 'modal', 'drawer', 'bottom-sheet',
3819
+ 'tablist', 'tabpanel', 'stepper', 'accordion-section',
3820
+ 'breadcrumb', 'pagination-control',
3821
+ 'avatar', 'presence-indicator', 'skeleton', 'empty-state',
3822
+ 'list', 'row', 'menu', 'label', 'value', 'paragraph', 'canvas',
3823
+ /* v2.9.0: the five document roles. Read-only, every one. */
3824
+ 'heading', 'list-item', 'code', 'code-inline', 'note',
3825
+ ]);
3826
+
3169
3827
  /* v1.6.4: field types whose click() act on a value (toggle).
3170
3828
  For these, the runtime synthesises nac:field:changed after
3171
3829
  el.click() so an automation runner sees a deterministic
@@ -3235,15 +3893,52 @@
3235
3893
  var rect = el.getBoundingClientRect();
3236
3894
  hiddenByLayout = (rect.width === 0 && rect.height === 0);
3237
3895
  }
3238
- if (hiddenByAria || hiddenByLayout) {
3896
+ /* 2.7.0: the ANCESTOR reasons too, through the same function the
3897
+ probe uses.
3898
+
3899
+ Found on 2026-11-25 by the suite written for undrivable_until.
3900
+ The two checks above read the element ITSELF, while
3901
+ validate_global's probe reads `closest('[aria-hidden="true"]')`,
3902
+ `closest('[inert]')` and the computed style -- so the two
3903
+ disagreed about a button inside a hidden PANEL, which is the
3904
+ commonest shape there is. And section 10.1 publishes the
3905
+ agreement as a fact: the unreachable bucket is "exactly what
3906
+ NAC.click() refuses with NacError('hidden')". It was not. The
3907
+ probe called the seven chat ids of this project's own landing
3908
+ page unreachable and click() would have fired into the closed
3909
+ panel, where the host handler never runs and the agent waits out
3910
+ the five-second completion timeout for a click nobody could
3911
+ see -- the silent damage, arriving as a timeout instead of a
3912
+ reason. _probeUnreachable IS the definition now, for the verb
3913
+ and for the validator, so a disagreement between them is not
3914
+ expressible. Decided rather than registered because the
3915
+ normative text already promised this behaviour and the code was
3916
+ the half that was wrong (working agreement rule 10; the owner
3917
+ delegated the call for this session on 2026-11-25). */
3918
+ var hiddenByAncestor = _probeUnreachable(el);
3919
+ if (hiddenByAria || hiddenByLayout || hiddenByAncestor) {
3920
+ /* 2.7.0: if the manifest declared what opens this element, the
3921
+ rejection carries it. The refusal itself does not change --
3922
+ the element is hidden and clicking it would be a lie -- but an
3923
+ agent that gets "open nac_landing.chat.toggle first" has its
3924
+ next move, and one that gets "is not visible" has nothing.
3925
+ That gap was measured on this project's own landing page:
3926
+ seven declared ids behind a closed panel. */
3927
+ var gateId = _resolveGate(nac_id);
3928
+ var msg = 'Element ' + nac_id + ' is not visible'
3929
+ + (gateId ? ': it is declared undrivable until "' + gateId
3930
+ + '" is operated -- do that first, then retry' : '');
3239
3931
  _emitCommandRejected({
3240
3932
  command_method: 'click',
3241
3933
  command_target: nac_id,
3242
3934
  reason: 'hidden',
3243
- message: 'Element ' + nac_id + ' is not visible',
3935
+ message: msg,
3936
+ gate: gateId || undefined,
3244
3937
  source: (opts && opts.source) || undefined,
3245
3938
  });
3246
- throw NacError('hidden', 'Element ' + nac_id + ' is not visible');
3939
+ var hiddenErr = NacError('hidden', msg);
3940
+ if (gateId) hiddenErr.gate = gateId;
3941
+ throw hiddenErr;
3247
3942
  }
3248
3943
  /* v1.9.0 ARIA preflight (sec 7.3.3): inert ancestor + aria-busy
3249
3944
  block click before the host handler runs. Disabled is already
@@ -3272,8 +3967,13 @@
3272
3967
  await _resolveVersionExpectations(opts, el);
3273
3968
  }
3274
3969
  }
3275
- const role = el.getAttribute('data-nac-role') || 'action';
3276
- const family = _CLICK_EVENT_FAMILY[role] || _CLICK_EVENT_FAMILY['action'];
3970
+ /* v2.8.0: resolve a declared alias (SPEC.md 1.5) BEFORE picking
3971
+ the family, so a page that still writes `treenode` gets the
3972
+ tree-node completion event instead of the action fallback. */
3973
+ const role = _canonicalRole(el.getAttribute('data-nac-role') || 'action');
3974
+ const family = _CLICK_EVENT_FAMILY[role]
3975
+ || (_REGISTERED_ROLES.has(role) && _REGISTERED_ROLES.get(role).events)
3976
+ || _CLICK_EVENT_FAMILY['action'];
3277
3977
  /* The first event in each family is the "success" signal; if a
3278
3978
  second entry exists it is the "failure" signal. Some families
3279
3979
  (option, tab, breadcrumb, step, pagination) have no failure
@@ -3284,8 +3984,19 @@
3284
3984
  const successEvents = [family[0]];
3285
3985
  const failureEvents = family.length > 1 ? [family[1]] : [];
3286
3986
  if (role !== 'action') {
3287
- successEvents.push('nac:action:succeeded');
3288
- failureEvents.push('nac:action:failed');
3987
+ /* Deduplicated since 2.7.0. A role with no family of its own
3988
+ falls back to the action family above and then had it pushed
3989
+ again, so the timeout message read "did not emit any of
3990
+ [nac:action:succeeded, nac:action:succeeded,
3991
+ nac:action:failed, nac:action:failed]" -- which makes a reader
3992
+ hunt for two contracts where there is one. Harmless to the
3993
+ listeners, confusing in the one place anybody reads. */
3994
+ if (successEvents.indexOf('nac:action:succeeded') < 0) {
3995
+ successEvents.push('nac:action:succeeded');
3996
+ }
3997
+ if (failureEvents.indexOf('nac:action:failed') < 0) {
3998
+ failureEvents.push('nac:action:failed');
3999
+ }
3289
4000
  }
3290
4001
  /* v1.6.5: cache plugin slug + option value/text BEFORE el.click()
3291
4002
  fires. The host's click handler may DETACH el from the DOM
@@ -3331,10 +4042,28 @@
3331
4042
  if (settled) return;
3332
4043
  settled = true;
3333
4044
  cleanup();
4045
+ /* Say WHY nothing arrived (TF-A14). The old message named the
4046
+ events and the elapsed time, which reads as "the widget did
4047
+ not ack" -- and for a role with no completion event in the
4048
+ protocol that is the wrong diagnosis in the one case where
4049
+ the runtime already knows the answer. Five seconds and a
4050
+ misattributed failure, per control. */
4051
+ const knownFamily = Object.prototype.hasOwnProperty.call(_CLICK_EVENT_FAMILY, role);
4052
+ let why = '';
4053
+ if (_CLICK_NO_EVENT_ROLES.has(role)) {
4054
+ why = ' -- role "' + role + '" has no completion event in NAC3: it is structural, or'
4055
+ + ' it is driven by its own verb (a draggable and a drop-target are what drag_drop()'
4056
+ + ' moves). If this control is meant to be clickable, have its handler emit'
4057
+ + ' nac:action:succeeded (NAC.bindAction does it for you).';
4058
+ } else if (!knownFamily) {
4059
+ why = ' -- role "' + role + '" is not one of the canonical roles of SPEC.md section 1,'
4060
+ + ' so this runtime waited for the action family by default. Declare a canonical'
4061
+ + ' role, or emit nac:action:succeeded from the handler.';
4062
+ }
3334
4063
  reject(NacError('timeout',
3335
4064
  'click(' + nac_id + ', role=' + role + ') did not emit any of [' +
3336
4065
  successEvents.concat(failureEvents).join(', ') + '] within ' +
3337
- timeout_ms + 'ms'));
4066
+ timeout_ms + 'ms' + why));
3338
4067
  }, timeout_ms);
3339
4068
  successEvents.forEach(function (n) { document.addEventListener(n, onSucceeded); });
3340
4069
  failureEvents.forEach(function (n) { document.addEventListener(n, onFailed); });
@@ -3403,7 +4132,13 @@
3403
4132
  d.stepper_id === nac_id || d.carousel_id === nac_id ||
3404
4133
  d.timeline_id === nac_id || d.option_id === nac_id ||
3405
4134
  d.table_id === nac_id ||
3406
- /* v1.6.x legacy aliases (deprecated, removed in v2.0). */
4135
+ /* v1.6.x legacy aliases. NOT deprecated-with-a-date any
4136
+ more (D-12, 2026-11-24): these six are RESOLUTION KEYS
4137
+ -- this is the code that reads them -- so the v2.0
4138
+ removal the comment used to announce would have broken
4139
+ event resolution for any host emitting only an alias.
4140
+ Frozen: they resolve for good, the canonical field is
4141
+ still the one to emit. */
3407
4142
  d.nac_id === nac_id || d.from_nac_id === nac_id ||
3408
4143
  d.target_nac_id === nac_id || d.id === nac_id ||
3409
4144
  d.column_nac_id === nac_id || d.filter_nac_id === nac_id ||
@@ -4713,13 +5448,63 @@
4713
5448
  emission.)
4714
5449
 
4715
5450
  A NAC-3 codebase that wants drift to be a CI blocker should run
4716
- this in addition to the per-plugin validate(slug) loop. */
4717
- function validate_global() {
5451
+ this in addition to the per-plugin validate(slug) loop.
5452
+
5453
+ THE opts ARGUMENT (2.7.0, audit N-35 / TF-A16). SPEC.md section
5454
+ 5.2 has published the signature as
5455
+ validate_global(opts?: {probe?: boolean}) since 2.5, and section
5456
+ 8 keys two conformance levels on it: level 2 wants
5457
+ validate_global({probe: false}) with zero error findings, level 3
5458
+ wants validate_global({probe: true}) with zero findings of ANY
5459
+ severity. This function TOOK NO ARGUMENTS. Passing {probe:true}
5460
+ was accepted and ignored, so the level 3 check was the level 2
5461
+ check with a stricter threshold and the word "probe" meant
5462
+ nothing -- measured while building the reference validator, and
5463
+ written into scripts/contract-api.meta.json as the reason no tool
5464
+ could decide that requirement.
5465
+
5466
+ What probing IS, now that it is defined: the static half of this
5467
+ validator compares two LISTS -- the manifests and the ids present
5468
+ in the DOM. It never asks whether a declared element can actually
5469
+ be reached, so the two failures an agent hits most do not appear
5470
+ in the report:
5471
+
5472
+ ambiguous the same nac_id is on 2+ DOM nodes under ONE
5473
+ manifest. find() takes the first, so click()
5474
+ silently operates on whichever node the document
5475
+ happens to list first. The duplicates bucket does
5476
+ NOT cover this: it compares manifests to each
5477
+ other, not the DOM to itself.
5478
+ unreachable the element is mounted but an agent cannot touch
5479
+ it -- an aria-hidden or inert ancestor, or a box
5480
+ that is not displayed. click() would reject it
5481
+ with NacError('hidden'), so the manifest declares
5482
+ a surface the protocol cannot operate.
5483
+
5484
+ Both buckets exist in the report ALWAYS, and are empty unless
5485
+ probe is true: a consumer reading the shape does not have to
5486
+ branch on the argument, and a caller who never passes opts gets
5487
+ exactly the report 2.5 gave them. Probing reads the DOM and
5488
+ reads computed style; it clicks nothing and mutates nothing. */
5489
+ function validate_global(opts) {
5490
+ _nac_requireDocument('validate_global');
5491
+ const probe = !!(opts && opts.probe);
4718
5492
  const out = {
4719
5493
  ok: true,
5494
+ probed: probe,
4720
5495
  duplicates: [],
4721
5496
  orphans: [],
4722
5497
  unmounted: [],
5498
+ ambiguous: [],
5499
+ unreachable: [],
5500
+ /* 2.7.0: declared-and-gated surfaces. This bucket is NOT a
5501
+ findings bucket -- an element that declares what opens it is
5502
+ keeping the contract, not breaking it -- and like the two
5503
+ probe buckets above it is always present and empty unless the
5504
+ caller asked to probe. It is reported because an agent reading
5505
+ the validation output is exactly who needs to know that four
5506
+ of these ids need a panel opened first. */
5507
+ gated: [],
4723
5508
  convention_violations: [],
4724
5509
  /* v2.5 / RFC V24-01: plugin slug uniqueness findings live in
4725
5510
  their own bucket so CI integrations can gate on them
@@ -4779,12 +5564,15 @@
4779
5564
  - if not in idIndex, it is an orphan.
4780
5565
  - track DOM-side seen ids to compute unmounted = manifest \ DOM. */
4781
5566
  const inDom = Object.create(null);
5567
+ const domNodes = Object.create(null);
4782
5568
  if (typeof document !== 'undefined') {
4783
5569
  const all = document.querySelectorAll('[data-nac-id]');
4784
5570
  Array.prototype.forEach.call(all, function (el) {
4785
5571
  const id = el.getAttribute('data-nac-id');
4786
5572
  if (!id) return;
4787
5573
  inDom[id] = true;
5574
+ if (!domNodes[id]) domNodes[id] = [];
5575
+ domNodes[id].push(el);
4788
5576
  if (!idIndex[id]) {
4789
5577
  /* Orphan in DOM but not in any manifest. Note: tabs
4790
5578
  frequently are declared in DOM-only because the host
@@ -4815,6 +5603,80 @@
4815
5603
  }
4816
5604
  }
4817
5605
 
5606
+ /* 2.7.0: the probe pass (opts.probe). Only declared ids are
5607
+ probed: an id nothing declares is already reported as an
5608
+ orphan, and a brownfield page full of them is the normal case
5609
+ this validator was built to tolerate. */
5610
+ if (probe && typeof document !== 'undefined') {
5611
+ for (const id in idIndex) {
5612
+ const nodes = domNodes[id] || [];
5613
+ if (nodes.length >= 2) {
5614
+ out.ambiguous.push({
5615
+ code: 'nac_id_ambiguous_in_dom',
5616
+ severity: 'error',
5617
+ nac_id: id, count: nodes.length,
5618
+ plugin: idIndex[id][0],
5619
+ hint: 'find() resolves the first match, so which element an '
5620
+ + 'agent operates depends on document order',
5621
+ });
5622
+ }
5623
+ if (nodes.length === 1) {
5624
+ const why = _probeUnreachable(nodes[0]);
5625
+ if (why) {
5626
+ /* 2.7.0: a surface that DECLARES what opens it is not a
5627
+ defect -- it is a gated surface, and the agent now has
5628
+ its next move. The declaration is only honoured when the
5629
+ gate itself holds up; see _resolveGate. */
5630
+ const gate = _resolveGate(id);
5631
+ const gateNodes = gate ? (domNodes[gate] || []) : [];
5632
+ /* The four ways a declared gate fails to be a way in. They
5633
+ are separate values because they are separate fixes: one
5634
+ is a manifest that forgot the gate, one is a view that
5635
+ has not mounted it, one is an id on two nodes -- where
5636
+ find() picks by document order, so "operate the gate"
5637
+ does not name one thing -- and one is a gate behind its
5638
+ own closed container. */
5639
+ const gateBad = !gate ? null
5640
+ : (!idIndex[gate] ? 'gate_not_declared'
5641
+ : (gateNodes.length === 0 ? 'gate_not_mounted'
5642
+ : (gateNodes.length >= 2 ? 'gate_ambiguous'
5643
+ : (_probeUnreachable(gateNodes[0]) ? 'gate_not_reachable'
5644
+ : null))));
5645
+ if (gate && !gateBad) {
5646
+ out.gated.push({
5647
+ code: 'nac_id_undrivable_until_gate',
5648
+ severity: 'info',
5649
+ nac_id: id, reason: why, gate: gate,
5650
+ plugin: idIndex[id][0],
5651
+ hint: 'declared as undrivable until "' + gate + '" is operated; '
5652
+ + 'click() refuses it until then and says so',
5653
+ });
5654
+ } else if (gate) {
5655
+ out.unreachable.push({
5656
+ code: 'nac_id_undrivable_gate_unusable',
5657
+ severity: 'error',
5658
+ nac_id: id, reason: why, gate: gate, gate_problem: gateBad,
5659
+ plugin: idIndex[id][0],
5660
+ hint: 'undrivable_until names "' + gate + '", and that gate is '
5661
+ + gateBad.replace(/_/g, ' ') + ' -- a promised way in that '
5662
+ + 'does not open is worse than none, an agent waits for it',
5663
+ });
5664
+ } else {
5665
+ out.unreachable.push({
5666
+ code: 'nac_id_declared_not_reachable',
5667
+ severity: 'warn',
5668
+ nac_id: id, reason: why,
5669
+ plugin: idIndex[id][0],
5670
+ hint: 'click() would reject this id with NacError(hidden). If the '
5671
+ + 'surface is gated on purpose, declare undrivable_until with '
5672
+ + 'the id that opens it',
5673
+ });
5674
+ }
5675
+ }
5676
+ }
5677
+ }
5678
+ }
5679
+
4818
5680
  /* v1.6.1: tolerated_violations support. Hosts retiring historic
4819
5681
  findings incrementally can register a tolerated set via
4820
5682
  NAC.set_validation_tolerance({tolerated:[...]}); each finding
@@ -4832,7 +5694,8 @@
4832
5694
  const k = String(t.kind || '') + '::' + String(t.nac_id || '');
4833
5695
  tolSet[k] = t.until || true;
4834
5696
  });
4835
- ['duplicates', 'orphans', 'unmounted', 'convention_violations'].forEach(function (kind) {
5697
+ ['duplicates', 'orphans', 'unmounted', 'ambiguous', 'unreachable',
5698
+ 'convention_violations'].forEach(function (kind) {
4836
5699
  const kept = [];
4837
5700
  out[kind].forEach(function (item) {
4838
5701
  const k = kind + '::' + item.nac_id;
@@ -4849,15 +5712,49 @@
4849
5712
  });
4850
5713
  }
4851
5714
 
4852
- out.ok = !out.duplicates.length;
5715
+ /* 2.7.0: ambiguous joins duplicates in the hard-error gate. Both
5716
+ mean the same thing to an agent -- an id that does not resolve
5717
+ to one element -- and the bucket is empty unless the caller
5718
+ asked to probe, so a 2.5 caller sees the same booleans. */
5719
+ out.ok = !out.duplicates.length && !out.ambiguous.length;
4853
5720
  /* v1.6.1: explicit has_errors flag for CI integration. Drift
4854
5721
  findings (duplicates) are hard-errors per spec sec 7.3.2;
4855
5722
  orphans + unmounted + convention_violations stay informative
4856
5723
  unless the host explicitly opts in via tolerance config. */
4857
- out.has_errors = out.duplicates.length > 0;
5724
+ out.has_errors = out.duplicates.length > 0 || out.ambiguous.length > 0;
4858
5725
  return out;
4859
5726
  }
4860
5727
 
5728
+ /* Why an element a manifest declares cannot be operated, or null.
5729
+ The three reasons are the ones click() itself refuses on, so the
5730
+ probe and the verb agree: a probe that reported something click()
5731
+ accepts, or missed something it rejects, would be worse than no
5732
+ probe. Everything is in a try: a host whose getComputedStyle
5733
+ throws gets a report without this bucket, not an exception out of
5734
+ a validator. */
5735
+ function _probeUnreachable(el) {
5736
+ if (!el) return null;
5737
+ try {
5738
+ if (el.closest && el.closest('[aria-hidden="true"]')) return 'aria_hidden';
5739
+ } catch (_) {}
5740
+ try {
5741
+ if (el.closest && el.closest('[inert]')) return 'inert_ancestor';
5742
+ } catch (_) {}
5743
+ try {
5744
+ const view = (el.ownerDocument && el.ownerDocument.defaultView)
5745
+ || (typeof window !== 'undefined' ? window : null);
5746
+ if (view && typeof view.getComputedStyle === 'function') {
5747
+ const st = view.getComputedStyle(el);
5748
+ if (st) {
5749
+ if (st.display === 'none') return 'not_displayed';
5750
+ if (st.visibility === 'hidden') return 'not_displayed';
5751
+ if (String(st.opacity) === '0') return 'not_displayed';
5752
+ }
5753
+ }
5754
+ } catch (_) {}
5755
+ return null;
5756
+ }
5757
+
4861
5758
  /* v1.6.1: tolerance config storage + setter. The shape:
4862
5759
  {
4863
5760
  tolerated: [
@@ -4888,14 +5785,51 @@
4888
5785
  are wrapped automatically when no resolver is set. */
4889
5786
  const _optionResolvers = Object.create(null);
4890
5787
 
5788
+ /* The resolver key, which has to be INJECTIVE (TF-A05).
5789
+
5790
+ It used to be:
5791
+
5792
+ String(plugin || '') + '::' + String(field_id || '')
5793
+
5794
+ and that collided in two independent ways:
5795
+
5796
+ 1. `String(x || '')` maps undefined, null, '', 0 and false all
5797
+ onto the empty string, so a resolver registered with no
5798
+ plugin and one registered with plugin '' were the same entry
5799
+ -- the second silently replaced the first.
5800
+ 2. '::' as a separator with nothing escaping it: ('a::b', 'c')
5801
+ and ('a', 'b::c') both produce 'a::b::c'. SPEC.md does not
5802
+ restrict the characters of a field_id, so a '::' inside one
5803
+ is legal, and two different fields could share a resolver.
5804
+
5805
+ The length prefix makes the split unambiguous: knowing how long
5806
+ the plugin part is, there is exactly one way to read the key back.
5807
+ The separator stays for readability in a debugger, but nothing
5808
+ depends on it being unique any more. */
4891
5809
  function _resolverKey(plugin, field_id) {
4892
- return String(plugin || '') + '::' + String(field_id || '');
5810
+ const p = plugin == null ? '' : String(plugin);
5811
+ const f = field_id == null ? '' : String(field_id);
5812
+ return p.length + ':' + p + '::' + f;
4893
5813
  }
4894
5814
 
4895
5815
  function set_options_resolver(plugin, field_id, fn) {
4896
5816
  if (typeof fn !== 'function') {
4897
5817
  throw NacError('invalid', 'resolver fn required');
4898
5818
  }
5819
+ /* And refuse the empty case outright rather than keying on ''.
5820
+ A resolver with no plugin or no field is a programming error,
5821
+ and before this it was an error that looked like success until
5822
+ something else overwrote the entry. The sibling guard above
5823
+ already throws for a missing fn; this is the same shape. */
5824
+ if (plugin == null || String(plugin) === '') {
5825
+ throw NacError('invalid',
5826
+ 'set_options_resolver: plugin is required -- a resolver with no plugin'
5827
+ + ' used to be stored under the empty key, where the next one replaced it');
5828
+ }
5829
+ if (field_id == null || String(field_id) === '') {
5830
+ throw NacError('invalid',
5831
+ 'set_options_resolver: field_id is required -- see the note on plugin');
5832
+ }
4899
5833
  _optionResolvers[_resolverKey(plugin, field_id)] = fn;
4900
5834
  }
4901
5835
 
@@ -5678,6 +6612,10 @@
5678
6612
  function step_to(stepper_id, n) {
5679
6613
  const steps = _stepperSteps(stepper_id);
5680
6614
  if (!steps.length) throw NacError('stepper_not_found', stepper_id);
6615
+ /* n slots for n steps, 0..n-1: this SELECTS one of the steps that
6616
+ exist. Same limit as reorder(), which also moves within n.
6617
+ drag_drop() bounds to n instead, because inserting into a list
6618
+ of n has n + 1 slots (TF-A07). */
5681
6619
  n = Math.max(0, Math.min(steps.length - 1, Number(n)));
5682
6620
  const prior = step_state(stepper_id).current;
5683
6621
  steps.forEach(function (s, i) {
@@ -6222,6 +7160,15 @@
6222
7160
  var siblings = Array.prototype.slice.call(list.querySelectorAll(
6223
7161
  '[data-nac-role="draggable"]'));
6224
7162
  var from_index = siblings.indexOf(item);
7163
+ /* Bounded to siblings.length - 1, NOT siblings.length, and the
7164
+ difference from drag_drop() is deliberate (TF-A07): this MOVES
7165
+ an item that is already one of the n, so there are n landing
7166
+ slots, 0..n-1. drag_drop() INSERTS an item the list does not
7167
+ hold yet, so it has n + 1. step_to() selects one of n existing
7168
+ steps: n slots, like here.
7169
+ Three bounds, two limits, one reason -- written at all three
7170
+ sites because it was written at none, and a reader comparing
7171
+ them could not tell a deliberate asymmetry from a slip. */
6225
7172
  var bounded = Math.max(0, Math.min(to_index, siblings.length - 1));
6226
7173
  if (from_index === -1) {
6227
7174
  return Promise.reject(new NacError('invalid',
@@ -6235,13 +7182,36 @@
6235
7182
  list.insertBefore(item, ref);
6236
7183
  }
6237
7184
  }
7185
+ /* Say whether the index was ACOTADO (TF-A06).
7186
+
7187
+ The old pair was: emit to_index = bounded, resolve { ok: true }.
7188
+ So a consumer asking for index 99 in a list of three got
7189
+ ok: true and no index at all from the promise, and the event
7190
+ reported 2 with nothing marking it as clamped. "I moved it where
7191
+ you asked" and "I moved it as far as it would go" were
7192
+ indistinguishable -- for an agent deciding whether its plan
7193
+ worked, those are different answers.
7194
+
7195
+ requested_index and bounded are ADDITIVE: to_index still means
7196
+ what it meant, so nothing reading it breaks. */
7197
+ var wasBounded = bounded !== to_index;
6238
7198
  _emit('nac:list:reordered', {
6239
- list_id: list_id,
6240
- item_id: item_id,
6241
- from_index: from_index,
6242
- to_index: bounded,
7199
+ list_id: list_id,
7200
+ item_id: item_id,
7201
+ from_index: from_index,
7202
+ to_index: bounded,
7203
+ requested_index: to_index,
7204
+ bounded: wasBounded,
7205
+ });
7206
+ return Promise.resolve({
7207
+ ok: true,
7208
+ list_id: list_id,
7209
+ item_id: item_id,
7210
+ from_index: from_index,
7211
+ to_index: bounded,
7212
+ requested_index: to_index,
7213
+ bounded: wasBounded,
6243
7214
  });
6244
- return Promise.resolve({ ok: true });
6245
7215
  }
6246
7216
 
6247
7217
  /* ---------- v1.6.2: drag_drop (implements spec sec 13.4) -------- */
@@ -6341,6 +7311,8 @@
6341
7311
 
6342
7312
  source.setAttribute('data-nac-state', 'dragging');
6343
7313
  /* v1.7.0: emit canonical source_id + legacy from_nac_id alias.
7314
+ The alias is frozen, not pending removal (D-12): the matcher
7315
+ resolves events by it.
6344
7316
  Plugin scope from the source's data-nac-plugin ancestor so
6345
7317
  sec 6.2.1 universal base (plugin + plugin_instance_id) is
6346
7318
  satisfied. v1.7 round 3 conformance FAILed without these. */
@@ -6353,11 +7325,34 @@
6353
7325
  };
6354
7326
  _emit('nac:drag:started', Object.assign({}, dragPluginCtx, {
6355
7327
  source_id: source_nac_id,
6356
- from_nac_id: source_nac_id, /* legacy, removed v2.0 */
7328
+ from_nac_id: source_nac_id, /* legacy alias, frozen (D-12) */
6357
7329
  }));
6358
7330
 
6359
- /* Tiny delay so the focus pulse is observable before the DOM
6360
- move settles. Mirrors the demo's existing UX. */
7331
+ /* The settle delay, now the HOST's choice (TF-A02).
7332
+
7333
+ Why it exists: a focus pulse on the source is only visible to a
7334
+ human reviewer if the DOM move waits for it. The 80 ms was this
7335
+ repository's demo UX, hard-coded into the library -- so every
7336
+ adopter paid it, including the ones with no reviewer watching
7337
+ and the ones driving a thousand moves in a test.
7338
+
7339
+ The DEFAULT STAYS 80. Dropping it to zero would change the
7340
+ timing of every existing adopter's drop for the sake of
7341
+ tidiness, and a host that liked the pulse would lose it without
7342
+ asking. What changes is that it can now be set:
7343
+
7344
+ NAC.drag_drop(a, b, { settle_ms: 0 }) per call
7345
+ NAC.drag_settle_ms = 0 per host
7346
+
7347
+ opts wins over the global, and the global defaults to the
7348
+ historical 80. Zero is honoured -- `|| 80` would have silently
7349
+ turned the useful value back into the default, which is the
7350
+ usual way an option like this ends up not working. */
7351
+ var settleMs = (opts && typeof opts.settle_ms === 'number')
7352
+ ? Math.max(0, opts.settle_ms)
7353
+ : ((global.NAC && typeof global.NAC.drag_settle_ms === 'number')
7354
+ ? Math.max(0, global.NAC.drag_settle_ms)
7355
+ : 80);
6361
7356
  return new Promise(function (resolve, reject) {
6362
7357
  setTimeout(function () {
6363
7358
  try {
@@ -6365,17 +7360,66 @@
6365
7360
  _emit('nac:drag:over', Object.assign({}, dragPluginCtx, {
6366
7361
  source_id: source_nac_id, /* v1.7.0 canonical */
6367
7362
  target_id: target_nac_id, /* v1.7.0 canonical */
6368
- from_nac_id: source_nac_id, /* legacy, drop v2.0 */
6369
- over_nac_id: target_nac_id, /* legacy, drop v2.0 */
7363
+ from_nac_id: source_nac_id, /* legacy, frozen D-12 */
7364
+ over_nac_id: target_nac_id, /* legacy, frozen D-12 */
6370
7365
  }));
6371
- /* Remove any "drop here" placeholder the demo stages. */
6372
- var empty = target.querySelector('.ne-drag-empty');
6373
- if (empty) empty.parentNode.removeChild(empty);
7366
+ /* Remove a "drop here" placeholder, IF THE HOST DECLARED ONE.
7367
+
7368
+ TF-A01. Until 2.7.0 this line was:
7369
+
7370
+ var empty = target.querySelector('.ne-drag-empty');
7371
+ if (empty) empty.parentNode.removeChild(empty);
7372
+
7373
+ -- the runtime deleting a node out of the host's document
7374
+ because of a CSS class name that belongs to THIS
7375
+ repository's demo (css/example.css, js/example.js). The
7376
+ class is real here; what was never real is the agreement.
7377
+ Nothing obliges an adopter to avoid `ne-drag-empty`, and
7378
+ an adopter who happens to use it for anything else lost
7379
+ the element on the first drop, silently, with no way to
7380
+ switch it off.
7381
+
7382
+ A library may not reach into a document it did not write
7383
+ on a convention it invented. So the default is now to
7384
+ remove NOTHING, and a host that wants placeholder removal
7385
+ asks for it, in the idiom the rest of the protocol uses --
7386
+ an attribute on the element that owns the contract:
7387
+
7388
+ <ul data-nac-role="drop-target"
7389
+ data-nac-drop-placeholder=".ne-drag-empty">
7390
+
7391
+ NAC.drop_placeholder_selector is the tree-wide default for
7392
+ a host that wants it everywhere; it is null, and the
7393
+ per-target attribute wins over it. The selector is only
7394
+ ever queried INSIDE the target, so a host cannot be made
7395
+ to delete something elsewhere in its page by accident. */
7396
+ var placeholderSel = target.getAttribute('data-nac-drop-placeholder')
7397
+ || (global.NAC && global.NAC.drop_placeholder_selector) || null;
7398
+ if (placeholderSel) {
7399
+ var stale = target.querySelectorAll(placeholderSel);
7400
+ for (var pi = 0; pi < stale.length; pi++) {
7401
+ if (stale[pi].parentNode) stale[pi].parentNode.removeChild(stale[pi]);
7402
+ }
7403
+ }
6374
7404
  /* Optional to_index for ordered drop-targets; otherwise
6375
7405
  append at end. */
6376
7406
  if (typeof opts.to_index === 'number') {
6377
7407
  var siblings = Array.prototype.slice.call(
6378
7408
  target.querySelectorAll('[data-nac-role="draggable"]'));
7409
+ /* Bounded to siblings.length, NOT siblings.length - 1, and
7410
+ the difference from reorder() is deliberate (TF-A07).
7411
+
7412
+ This is an INSERT into a list the item is not in yet, so
7413
+ a list of n items has n + 1 landing slots: before each
7414
+ of the n, plus after the last. reorder() MOVES an item
7415
+ that is already among the n, so it has n slots, and
7416
+ bounds to n - 1. step_to() selects one of n existing
7417
+ steps: also n - 1.
7418
+
7419
+ Three bounds, two limits, one reason -- written down
7420
+ here because it was not, and a reader comparing the
7421
+ three had no way to tell a deliberate asymmetry from a
7422
+ copy-paste slip. */
6379
7423
  var bounded = Math.max(0, Math.min(opts.to_index, siblings.length));
6380
7424
  var ref = siblings[bounded] || null;
6381
7425
  if (ref) target.insertBefore(source, ref);
@@ -6388,8 +7432,8 @@
6388
7432
  _emit('nac:drag:dropped', Object.assign({}, dragPluginCtx, {
6389
7433
  source_id: source_nac_id, /* v1.7.0 canonical */
6390
7434
  target_id: target_nac_id, /* v1.7.0 canonical */
6391
- from_nac_id: source_nac_id, /* legacy, drop v2.0 */
6392
- target_nac_id: target_nac_id, /* legacy, drop v2.0 */
7435
+ from_nac_id: source_nac_id, /* legacy, frozen D-12 */
7436
+ target_nac_id: target_nac_id, /* legacy, frozen D-12 */
6393
7437
  value: opts.value !== undefined ? opts.value : null,
6394
7438
  }));
6395
7439
  resolve({ ok: true, source: source_nac_id, target: target_nac_id });
@@ -6398,7 +7442,7 @@
6398
7442
  target.setAttribute('data-nac-state', 'idle');
6399
7443
  _emit('nac:drag:cancelled', Object.assign({}, dragPluginCtx, {
6400
7444
  source_id: source_nac_id, /* v1.7.0 canonical */
6401
- from_nac_id: source_nac_id, /* legacy, drop v2.0 */
7445
+ from_nac_id: source_nac_id, /* legacy, frozen D-12 */
6402
7446
  reason: 'aborted',
6403
7447
  error: err && err.message ? err.message : String(err),
6404
7448
  }));
@@ -6416,7 +7460,7 @@
6416
7460
  reject(err instanceof Error ? err :
6417
7461
  new NacError('invalid', String(err)));
6418
7462
  }
6419
- }, 80);
7463
+ }, settleMs);
6420
7464
  });
6421
7465
  }
6422
7466
 
@@ -6870,6 +7914,413 @@
6870
7914
  return hex;
6871
7915
  }
6872
7916
 
7917
+ /* ---------- 2.7.0: manifest authenticity (sec 7.2) ------------
7918
+
7919
+ WHAT THIS CLOSES. Section 7.2 has published, since 1.9, a worked
7920
+ example of an HMAC-signed manifest: set the tenant secret, pass a
7921
+ provenance block to register(), and "the runtime computes the
7922
+ expected HMAC over a stable serialisation of the manifest
7923
+ (excluding the signature itself) and rejects manifests whose
7924
+ signature does not match". None of that existed. sign_provenance /
7925
+ verify_provenance (above) sign an EVENT's detail.source and have
7926
+ never looked at a manifest, and register() stored whatever object
7927
+ it was handed. So conformance level 3 -- whose first requirement
7928
+ is "carries HMAC-signed manifests" -- could not be asserted by any
7929
+ tool, which is the measured finding audit N-36 / PND-045 records
7930
+ and what scripts/contract-api.meta.json says in the note on that
7931
+ requirement: "the runtime exposes no manifest verification at all
7932
+ ... which is why no tool can assert level 3 today".
7933
+
7934
+ WHY A HAND-WRITTEN SHA-256 AND NOT SubtleCrypto. Because
7935
+ register() is SYNCHRONOUS and throws -- that is its whole
7936
+ contract, and STRICT_VALIDATION made it a hard gate in 2.3.
7937
+ crypto.subtle.sign returns a Promise, so a register() built on it
7938
+ could only verify AFTER returning: the manifest would already be
7939
+ live, the host would already have gone on to click things, and the
7940
+ rejection would arrive as a console message in a later tick. That
7941
+ is silent damage with extra steps. A synchronous digest is ~70
7942
+ lines, has fixed test vectors anybody can check (FIPS 180-4 for
7943
+ the digest, RFC 4231 for the HMAC -- both are in
7944
+ runtime/test/manifest-hmac.mjs), needs no DOM, no network and no
7945
+ Node built-in, and lets the signature be refused at the only
7946
+ moment where refusing costs nothing.
7947
+
7948
+ WHAT IT DOES NOT DO, said plainly: it does not make a manifest
7949
+ trustworthy. The secret lives in the page, so an agent with
7950
+ user-level access reads it (sec 7.3 says exactly this). What it
7951
+ buys is the multi-tenant case 7.2 names -- tenant A cannot hand
7952
+ tenant B's host a manifest it did not sign -- and an answer to
7953
+ "can anything here say it verified this?" that is not "no". */
7954
+
7955
+ const _SHA256_K = [
7956
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
7957
+ 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
7958
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
7959
+ 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
7960
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
7961
+ 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
7962
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
7963
+ 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
7964
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
7965
+ 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
7966
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
7967
+ 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
7968
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
7969
+ 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
7970
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
7971
+ 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
7972
+ ];
7973
+
7974
+ function _rotr32(x, n) { return ((x >>> n) | (x << (32 - n))) >>> 0; }
7975
+
7976
+ /* UTF-8 bytes without TextEncoder, so the digest works in any host
7977
+ that can run the rest of this file (old WebViews included). */
7978
+ function _utf8Bytes(str) {
7979
+ str = String(str);
7980
+ if (typeof TextEncoder !== 'undefined') {
7981
+ return new TextEncoder().encode(str);
7982
+ }
7983
+ const out = [];
7984
+ for (let i = 0; i < str.length; i++) {
7985
+ let c = str.charCodeAt(i);
7986
+ if (c < 0x80) { out.push(c); continue; }
7987
+ if (c < 0x800) {
7988
+ out.push(0xc0 | (c >> 6), 0x80 | (c & 0x3f));
7989
+ continue;
7990
+ }
7991
+ if (c >= 0xd800 && c <= 0xdbff && i + 1 < str.length) {
7992
+ const lo = str.charCodeAt(i + 1);
7993
+ if (lo >= 0xdc00 && lo <= 0xdfff) {
7994
+ c = 0x10000 + ((c - 0xd800) << 10) + (lo - 0xdc00);
7995
+ i++;
7996
+ out.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 0x3f),
7997
+ 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f));
7998
+ continue;
7999
+ }
8000
+ }
8001
+ out.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 0x3f),
8002
+ 0x80 | (c & 0x3f));
8003
+ }
8004
+ return new Uint8Array(out);
8005
+ }
8006
+
8007
+ /* SHA-256 over bytes -> Uint8Array(32). FIPS 180-4. */
8008
+ function _sha256Bytes(bytes) {
8009
+ const H = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
8010
+ 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];
8011
+ const len = bytes.length;
8012
+ const padded = new Uint8Array((Math.floor((len + 8) / 64) + 1) * 64);
8013
+ padded.set(bytes);
8014
+ padded[len] = 0x80;
8015
+ const n = padded.length;
8016
+ const hiBits = Math.floor(len / 536870912); /* (len * 8) >> 32 */
8017
+ const loBits = (len * 8) >>> 0;
8018
+ padded[n - 8] = (hiBits >>> 24) & 0xff;
8019
+ padded[n - 7] = (hiBits >>> 16) & 0xff;
8020
+ padded[n - 6] = (hiBits >>> 8) & 0xff;
8021
+ padded[n - 5] = hiBits & 0xff;
8022
+ padded[n - 4] = (loBits >>> 24) & 0xff;
8023
+ padded[n - 3] = (loBits >>> 16) & 0xff;
8024
+ padded[n - 2] = (loBits >>> 8) & 0xff;
8025
+ padded[n - 1] = loBits & 0xff;
8026
+ const w = new Array(64);
8027
+ for (let off = 0; off < n; off += 64) {
8028
+ for (let i = 0; i < 16; i++) {
8029
+ const j = off + i * 4;
8030
+ w[i] = ((padded[j] << 24) | (padded[j + 1] << 16)
8031
+ | (padded[j + 2] << 8) | padded[j + 3]) >>> 0;
8032
+ }
8033
+ for (let i = 16; i < 64; i++) {
8034
+ const x = w[i - 15], y = w[i - 2];
8035
+ const s0 = (_rotr32(x, 7) ^ _rotr32(x, 18) ^ (x >>> 3)) >>> 0;
8036
+ const s1 = (_rotr32(y, 17) ^ _rotr32(y, 19) ^ (y >>> 10)) >>> 0;
8037
+ w[i] = (((w[i - 16] + s0) >>> 0) + ((w[i - 7] + s1) >>> 0)) >>> 0;
8038
+ }
8039
+ let a = H[0], b = H[1], c = H[2], d = H[3];
8040
+ let e = H[4], f = H[5], g = H[6], h = H[7];
8041
+ for (let i = 0; i < 64; i++) {
8042
+ const S1 = (_rotr32(e, 6) ^ _rotr32(e, 11) ^ _rotr32(e, 25)) >>> 0;
8043
+ const ch = ((e & f) ^ (~e & g)) >>> 0;
8044
+ const t1 = (((h + S1) >>> 0) + ((ch + _SHA256_K[i]) >>> 0)
8045
+ + w[i]) >>> 0;
8046
+ const S0 = (_rotr32(a, 2) ^ _rotr32(a, 13) ^ _rotr32(a, 22)) >>> 0;
8047
+ const maj = ((a & b) ^ (a & c) ^ (b & c)) >>> 0;
8048
+ const t2 = (S0 + maj) >>> 0;
8049
+ h = g; g = f; f = e; e = (d + t1) >>> 0;
8050
+ d = c; c = b; b = a; a = (t1 + t2) >>> 0;
8051
+ }
8052
+ H[0] = (H[0] + a) >>> 0; H[1] = (H[1] + b) >>> 0;
8053
+ H[2] = (H[2] + c) >>> 0; H[3] = (H[3] + d) >>> 0;
8054
+ H[4] = (H[4] + e) >>> 0; H[5] = (H[5] + f) >>> 0;
8055
+ H[6] = (H[6] + g) >>> 0; H[7] = (H[7] + h) >>> 0;
8056
+ }
8057
+ const out = new Uint8Array(32);
8058
+ for (let i = 0; i < 8; i++) {
8059
+ out[i * 4] = (H[i] >>> 24) & 0xff;
8060
+ out[i * 4 + 1] = (H[i] >>> 16) & 0xff;
8061
+ out[i * 4 + 2] = (H[i] >>> 8) & 0xff;
8062
+ out[i * 4 + 3] = H[i] & 0xff;
8063
+ }
8064
+ return out;
8065
+ }
8066
+
8067
+ function _bytesToHex(arr) {
8068
+ let hex = '';
8069
+ for (let i = 0; i < arr.length; i++) {
8070
+ const b = arr[i].toString(16);
8071
+ hex += b.length === 1 ? '0' + b : b;
8072
+ }
8073
+ return hex;
8074
+ }
8075
+
8076
+ /* HMAC-SHA256, synchronous. RFC 2104 / tested against RFC 4231. */
8077
+ function _hmacSha256Hex(secret, message) {
8078
+ const BLOCK = 64;
8079
+ let key = _utf8Bytes(secret);
8080
+ if (key.length > BLOCK) key = _sha256Bytes(key);
8081
+ const k0 = new Uint8Array(BLOCK);
8082
+ k0.set(key);
8083
+ const msg = _utf8Bytes(message);
8084
+ const inner = new Uint8Array(BLOCK + msg.length);
8085
+ const outer = new Uint8Array(BLOCK + 32);
8086
+ for (let i = 0; i < BLOCK; i++) {
8087
+ inner[i] = k0[i] ^ 0x36;
8088
+ outer[i] = k0[i] ^ 0x5c;
8089
+ }
8090
+ inner.set(msg, BLOCK);
8091
+ outer.set(_sha256Bytes(inner), BLOCK);
8092
+ return _bytesToHex(_sha256Bytes(outer));
8093
+ }
8094
+
8095
+ /* Stable serialisation: keys sorted at every depth, undefined
8096
+ dropped, so two hosts that build the same manifest in a different
8097
+ key order sign the same bytes. */
8098
+ function _stableStringify(v) {
8099
+ if (v === undefined) return 'null';
8100
+ if (v === null || typeof v !== 'object') return JSON.stringify(v);
8101
+ if (Array.isArray(v)) {
8102
+ const items = [];
8103
+ for (let i = 0; i < v.length; i++) items.push(_stableStringify(v[i]));
8104
+ return '[' + items.join(',') + ']';
8105
+ }
8106
+ const keys = Object.keys(v).filter(function (k) {
8107
+ return v[k] !== undefined && typeof v[k] !== 'function';
8108
+ }).sort();
8109
+ const parts = keys.map(function (k) {
8110
+ return JSON.stringify(k) + ':' + _stableStringify(v[k]);
8111
+ });
8112
+ return '{' + parts.join(',') + '}';
8113
+ }
8114
+
8115
+ /* The signed body: the whole manifest, with provenance.signature
8116
+ removed and everything else of the provenance block KEPT -- the
8117
+ signature covers signed_at and signed_by, so a replay cannot
8118
+ relabel who signed it or when. */
8119
+ function _manifestCanonicalString(m) {
8120
+ const clone = {};
8121
+ Object.keys(m).forEach(function (k) {
8122
+ if (k === 'provenance') return;
8123
+ clone[k] = m[k];
8124
+ });
8125
+ if (m.provenance && typeof m.provenance === 'object') {
8126
+ const p = {};
8127
+ Object.keys(m.provenance).forEach(function (k) {
8128
+ if (k === 'signature') return;
8129
+ p[k] = m.provenance[k];
8130
+ });
8131
+ clone.provenance = p;
8132
+ }
8133
+ return _stableStringify(clone);
8134
+ }
8135
+
8136
+ /* Tenant secrets for MANIFEST verification. Separate store from the
8137
+ extensions module's event-provenance secrets, and deliberately so:
8138
+ register() lives in this file and cannot reach into that closure.
8139
+ NAC.set_provenance_secret (extensions) FORWARDS here, so the
8140
+ example published in section 7.2 works exactly as written. */
8141
+ let _manifestSecrets = [];
8142
+
8143
+ function set_manifest_secret(s) {
8144
+ if (typeof s === 'string') _manifestSecrets = [s];
8145
+ else if (Array.isArray(s)) _manifestSecrets = s.slice();
8146
+ else if (s == null) _manifestSecrets = [];
8147
+ else {
8148
+ throw NacError('invalid',
8149
+ 'NAC.set_manifest_secret expects a string, an array of strings, or null');
8150
+ }
8151
+ return _manifestSecrets.length;
8152
+ }
8153
+
8154
+ /* NAC.sign_manifest(manifest, secret?) -> hex signature.
8155
+ Sign the object you are about to hand to register(): the digest
8156
+ covers it as you built it, BEFORE register() fills in its
8157
+ defaults (version, nac_version, plugin_slug from the two-argument
8158
+ form), which is why register() takes its snapshot first. */
8159
+ function sign_manifest(manifest, secret) {
8160
+ if (!manifest || typeof manifest !== 'object') {
8161
+ throw NacError('invalid', 'NAC.sign_manifest: manifest object required');
8162
+ }
8163
+ const key = (secret != null) ? secret : _manifestSecrets[0];
8164
+ if (typeof key !== 'string' || !key) {
8165
+ throw NacError('invalid',
8166
+ 'NAC.sign_manifest: no secret. Pass one, or call NAC.set_manifest_secret first');
8167
+ }
8168
+ return _hmacSha256Hex(key, _manifestCanonicalString(manifest));
8169
+ }
8170
+
8171
+ /* NAC.verify_manifest(manifest, secret?) -> boolean.
8172
+ Constant-time compare against every registered secret, so a
8173
+ tenant rotating a secret can hold both for the window. */
8174
+ function verify_manifest(manifest, secret) {
8175
+ if (!manifest || typeof manifest !== 'object') return false;
8176
+ const prov = manifest.provenance;
8177
+ if (!prov || typeof prov !== 'object' || !prov.signature) return false;
8178
+ const keys = (secret != null) ? [secret] : _manifestSecrets;
8179
+ if (!keys.length) return false;
8180
+ const body = _manifestCanonicalString(manifest);
8181
+ const provided = String(prov.signature);
8182
+ let any = false;
8183
+ for (let i = 0; i < keys.length; i++) {
8184
+ if (typeof keys[i] !== 'string' || !keys[i]) continue;
8185
+ const expected = _hmacSha256Hex(keys[i], body);
8186
+ if (provided.length !== expected.length) continue;
8187
+ let diff = 0;
8188
+ for (let j = 0; j < provided.length; j++) {
8189
+ diff |= provided.charCodeAt(j) ^ expected.charCodeAt(j);
8190
+ }
8191
+ if (diff === 0) any = true;
8192
+ }
8193
+ return any;
8194
+ }
8195
+
8196
+ /* What register() recorded about each manifest's provenance, so a
8197
+ validator on the page can ask instead of guessing. Shape:
8198
+ { signed, verified, reason, signed_by, signed_at }
8199
+ verified is true / false / null, and null is not a synonym for
8200
+ false: it means NOBODY COULD TELL (no secret registered). A tool
8201
+ that reports level 3 off this MUST treat null as unverified. */
8202
+ const _manifestProvenance = Object.create(null);
8203
+
8204
+ function manifest_provenance(slug) {
8205
+ if (slug === undefined) {
8206
+ const out = {};
8207
+ Object.keys(_manifestProvenance).forEach(function (k) {
8208
+ out[k] = Object.assign({}, _manifestProvenance[k]);
8209
+ });
8210
+ return out;
8211
+ }
8212
+ const rec = _manifestProvenance[String(slug)];
8213
+ return rec ? Object.assign({}, rec) : null;
8214
+ }
8215
+
8216
+ /* Called from register() with the canonical string captured BEFORE
8217
+ any default was applied. Throws when a signature is present and a
8218
+ secret says it is wrong; stays silent when there is no signature
8219
+ (section 7.2: a manifest MAY carry a provenance block) or no
8220
+ secret (nothing to check against, and an adopter who never set
8221
+ one must keep working exactly as before). */
8222
+ function _recordManifestProvenance(slug, manifest, canonical) {
8223
+ const prov = manifest && manifest.provenance;
8224
+ if (!prov || typeof prov !== 'object' || !prov.signature) {
8225
+ _manifestProvenance[slug] = {
8226
+ signed: false, verified: null, reason: 'no_provenance_block',
8227
+ signed_by: (prov && prov.signed_by) || null,
8228
+ signed_at: (prov && prov.signed_at) || null,
8229
+ };
8230
+ return;
8231
+ }
8232
+ if (!_manifestSecrets.length) {
8233
+ _manifestProvenance[slug] = {
8234
+ signed: true, verified: null, reason: 'no_secret_registered',
8235
+ signed_by: prov.signed_by || null,
8236
+ signed_at: prov.signed_at || null,
8237
+ };
8238
+ return;
8239
+ }
8240
+ const provided = String(prov.signature);
8241
+ let ok = false;
8242
+ for (let i = 0; i < _manifestSecrets.length; i++) {
8243
+ const key = _manifestSecrets[i];
8244
+ if (typeof key !== 'string' || !key) continue;
8245
+ const expected = _hmacSha256Hex(key, canonical);
8246
+ if (provided.length !== expected.length) continue;
8247
+ let diff = 0;
8248
+ for (let j = 0; j < provided.length; j++) {
8249
+ diff |= provided.charCodeAt(j) ^ expected.charCodeAt(j);
8250
+ }
8251
+ if (diff === 0) ok = true;
8252
+ }
8253
+ if (!ok) {
8254
+ delete _manifestProvenance[slug];
8255
+ throw NacError('invalid',
8256
+ 'manifest "' + slug + '" carries a provenance.signature that does not '
8257
+ + 'match the HMAC of its body under any registered tenant secret '
8258
+ + '(SPEC.md sec 7.2). Either the manifest was altered after signing, '
8259
+ + 'or it was signed for another tenant.');
8260
+ }
8261
+ _manifestProvenance[slug] = {
8262
+ signed: true, verified: true, reason: 'verified',
8263
+ signed_by: prov.signed_by || null,
8264
+ signed_at: prov.signed_at || null,
8265
+ };
8266
+ }
8267
+
8268
+ /* ---------- 2.7.0: NAC.set_source (sec 15.7) ------------------
8269
+
8270
+ Section 15.7 has published, since 2.5, that source on
8271
+ nac:plugin:invoked / :read / :event "defaults to 'agent'; hosts
8272
+ that wrap the runtime in a user-facing UI MAY override via the
8273
+ existing NAC.set_source(...) mechanism (sec 7)". The mechanism
8274
+ was not existing: there were zero occurrences of set_source in
8275
+ js/, so every dispatch from a host where a HUMAN pressed the
8276
+ button was sealed source:'agent', trusted:false, and an auditor
8277
+ reading the log could not tell the two apart (D-09).
8278
+
8279
+ It is an ATTESTATION BY THE HOST, not a measurement, and the
8280
+ threat model (7.3) already says an agent with user-level access
8281
+ can do anything the user can -- including calling this. What it
8282
+ buys is the honest case: a host with a confirmation UI in front
8283
+ of the dispatch can say so, and every change of the claim emits
8284
+ nac:source_changed so the override is itself in the log. */
8285
+
8286
+ let _dispatchSource = { source: 'agent', trusted: false };
8287
+
8288
+ function set_source(src) {
8289
+ let next;
8290
+ if (src == null) {
8291
+ next = { source: 'agent', trusted: false };
8292
+ } else if (typeof src === 'string') {
8293
+ if (!src.trim()) {
8294
+ throw NacError('invalid', 'NAC.set_source: source string must not be empty');
8295
+ }
8296
+ next = { source: src, trusted: false };
8297
+ } else if (typeof src === 'object') {
8298
+ const label = src.source !== undefined ? src.source : src.type;
8299
+ if (typeof label !== 'string' || !label.trim()) {
8300
+ throw NacError('invalid',
8301
+ 'NAC.set_source: {source} must be a non-empty string');
8302
+ }
8303
+ next = { source: label, trusted: !!src.trusted };
8304
+ } else {
8305
+ throw NacError('invalid',
8306
+ 'NAC.set_source expects a string, {source, trusted}, or null to reset');
8307
+ }
8308
+ const prev = _dispatchSource;
8309
+ _dispatchSource = next;
8310
+ try {
8311
+ document.dispatchEvent(new CustomEvent('nac:source_changed', {
8312
+ detail: {
8313
+ source: next.source, trusted: next.trusted,
8314
+ previous_source: prev.source, previous_trusted: prev.trusted,
8315
+ },
8316
+ bubbles: true, composed: true,
8317
+ }));
8318
+ } catch (_) { /* no document: the setter still took effect */ }
8319
+ return Object.assign({}, next);
8320
+ }
8321
+
8322
+ function get_source() { return Object.assign({}, _dispatchSource); }
8323
+
6873
8324
  /* ---------- v1.9.0: recommended_remediation (sec 6.2.30) ----- */
6874
8325
 
6875
8326
  const _REMEDIATION_BY_REASON = {
@@ -6949,6 +8400,34 @@
6949
8400
  'emitter-listen': true,
6950
8401
  };
6951
8402
 
8403
+ /* 2.7.0 (SPEC sec 19.1) -- which of those nine backends reach their
8404
+ surface WITHOUT a document. This is the whole predicate of the
8405
+ headless profile, and it is a property of the implementation, not
8406
+ an opinion: sdk-call walks a registered API handle or the global
8407
+ object, and emitter-listen subscribes to a library's own emitter.
8408
+ Neither ever calls document.querySelector. The other six do, which
8409
+ is why they are absent from this table.
8410
+
8411
+ 'inherits' means the binding is DOM-free exactly when every state
8412
+ path it observes is: synthetic-poll only calls read() on the state
8413
+ paths it declares. */
8414
+ const _V25_DOM_FREE_BACKENDS = {
8415
+ 'sdk-call': true,
8416
+ 'emitter-listen': true,
8417
+ 'synthetic-poll': 'inherits',
8418
+ };
8419
+
8420
+ /* Why each DOM-requiring backend needs one -- named, so the refusal a
8421
+ declared-headless manifest gets says what to change (sec 19.1). */
8422
+ const _V25_DOM_REASON = {
8423
+ 'postmessage': 'posts to the contentWindow of an iframe matched by a CSS selector',
8424
+ 'postmessage-listen': 'filters window.message by the iframe a CSS selector matches',
8425
+ 'script-bridge': 'posts to the contentWindow of an iframe matched by a CSS selector',
8426
+ 'dom-mirror': 'reads a DOM element matched by a CSS selector',
8427
+ 'same-origin-window': 'reads into the contentWindow of an iframe matched by a CSS selector',
8428
+ 'synthetic-mutation': 'observes DOM mutations with a MutationObserver',
8429
+ };
8430
+
6952
8431
  /* The closed list of NacError codes the plugin contract raises
6953
8432
  (SPEC.md sec 15.9), plus the namespace a plugin uses for a code
6954
8433
  of its own (v2.6, RFC V26-01 hook E-6). Before this, `call` lifted
@@ -6967,6 +8446,16 @@
6967
8446
  'state_unreadable': true,
6968
8447
  'timeout': true,
6969
8448
  'invalid': true,
8449
+ /* 2.7.0 (sec 19.3 / 19.4). no_document: a DOM primitive was called
8450
+ where there is no document, so there is nothing to resolve --
8451
+ raised instead of the raw ReferenceError the reference runtime
8452
+ used to let through. provenance_unobservable: a plugin that
8453
+ declares headless: true was called with no document AND no event
8454
+ sink, so its nac:plugin:* row would be dropped; refused before
8455
+ the effect, because a surface nobody can audit is the silent
8456
+ damage this protocol exists to remove. */
8457
+ 'no_document': true,
8458
+ 'provenance_unobservable': true,
6970
8459
  };
6971
8460
  const _V25_PLUGIN_CODE_PREFIX = 'plugin.';
6972
8461
 
@@ -7175,6 +8664,8 @@
7175
8664
  }
7176
8665
 
7177
8666
  function _v25_backend_dom_mirror(binding /*, args*/) {
8667
+ const miss = _v25_noDocument('dom-mirror');
8668
+ if (miss) return Promise.reject(miss);
7178
8669
  const sel = binding.selector;
7179
8670
  if (!sel) return Promise.reject(new Error('dom-mirror requires `selector` string'));
7180
8671
  const el = document.querySelector(sel);
@@ -7199,6 +8690,8 @@
7199
8690
  /* postmessage (verb): post a structured message to the iframe.contentWindow
7200
8691
  of the target. `values` literal + `values_from_args` forward keys. */
7201
8692
  function _v25_backend_postmessage(binding, args) {
8693
+ const miss = _v25_noDocument('postmessage');
8694
+ if (miss) return Promise.reject(miss);
7202
8695
  const sel = binding.target;
7203
8696
  if (!sel) return Promise.reject(new Error('postmessage requires `target` selector'));
7204
8697
  const iframe = document.querySelector(sel);
@@ -7235,6 +8728,8 @@
7235
8728
  flag the test sets explicitly; in real browsers the property access
7236
8729
  throws a DOMException SecurityError which we map the same way. */
7237
8730
  function _v25_backend_same_origin_window(binding /*, args*/) {
8731
+ const miss = _v25_noDocument('same-origin-window');
8732
+ if (miss) return Promise.reject(miss);
7238
8733
  const sel = binding.target;
7239
8734
  if (!sel) return Promise.reject(new Error('same-origin-window requires `target`'));
7240
8735
  const iframe = document.querySelector(sel);
@@ -7279,6 +8774,8 @@
7279
8774
  CallPythonScript pattern; generalises to any app that exposes a
7280
8775
  RPC channel over postMessage. */
7281
8776
  function _v25_backend_script_bridge(binding, args) {
8777
+ const miss = _v25_noDocument('script-bridge');
8778
+ if (miss) return Promise.reject(miss);
7282
8779
  const sel = binding.target;
7283
8780
  if (!sel) return Promise.reject(new Error('script-bridge requires `target`'));
7284
8781
  const iframe = document.querySelector(sel);
@@ -7396,6 +8893,8 @@
7396
8893
  fall back to synthetic-poll for those cases (declared, not
7397
8894
  implicit). */
7398
8895
  function _v25_subscribe_synthetic_mutation(plugin, event_path, binding, cb) {
8896
+ const miss = _v25_noDocument('synthetic-mutation');
8897
+ if (miss) throw miss;
7399
8898
  if (typeof MutationObserver === 'undefined') {
7400
8899
  throw new Error('synthetic-mutation requires MutationObserver in scope');
7401
8900
  }
@@ -7654,6 +9153,8 @@
7654
9153
  on the host window, filter by source iframe + MessageId, run the
7655
9154
  extractor, fire the user callback. Returns a teardown closure. */
7656
9155
  function _v25_subscribe_postmessage_listen(plugin, event_path, binding, cb) {
9156
+ const miss = _v25_noDocument('postmessage-listen');
9157
+ if (miss) throw miss;
7657
9158
  const sel = binding.source;
7658
9159
  const wantMsgId = binding.message;
7659
9160
  if (!wantMsgId) throw new Error('postmessage-listen requires `message`');
@@ -7799,6 +9300,13 @@
7799
9300
  const events = manifest.events || {};
7800
9301
  _v25_validateText(manifest.label, 'manifest "' + slug + '"', 'label');
7801
9302
  _v25_validateText(manifest.hint, 'manifest "' + slug + '"', 'hint');
9303
+ /* 2.7.0 (sec 19.1) -- headless is a boolean or it is absent. A
9304
+ string "true" is a typo that would silently leave the plugin
9305
+ outside the profile, so it is refused rather than coerced. */
9306
+ if (manifest.headless !== undefined && typeof manifest.headless !== 'boolean') {
9307
+ const e = new Error('manifest "' + slug + '": headless must be a boolean when declared');
9308
+ e.code = 'invalid'; throw e;
9309
+ }
7802
9310
  /* Verbs: single binding each, backend in vocabulary. */
7803
9311
  for (const vp in verbs) {
7804
9312
  const b = verbs[vp];
@@ -7858,6 +9366,28 @@
7858
9366
  e.code = 'invalid'; throw e;
7859
9367
  }
7860
9368
  }
9369
+ /* 2.7.0 (sec 19.1) -- a manifest that DECLARES the headless
9370
+ profile has to be in it. Checked here, at register time, so the
9371
+ adopter learns on the bench instead of discovering it on a
9372
+ device with no screen: every binding must reach its surface
9373
+ without a document, and the refusal names the ones that do not. */
9374
+ if (manifest.headless === true) {
9375
+ const need = _v25_domRequired({
9376
+ verbs: verbs, state: states, events: events,
9377
+ });
9378
+ if (need.length) {
9379
+ const first = need[0];
9380
+ const e = new Error('manifest "' + slug + '" declares headless: true but ' +
9381
+ need.length + ' binding' + (need.length === 1 ? '' : 's') + ' need' +
9382
+ (need.length === 1 ? 's' : '') + ' a document. First: ' + first.kind + ' "' +
9383
+ first.path + '" -- ' + first.why + '. Declare a DOM-free backend (sdk-call, ' +
9384
+ 'emitter-listen, or synthetic-poll over DOM-free state) or drop the ' +
9385
+ 'declaration (SPEC sec 19.1).');
9386
+ e.code = 'invalid';
9387
+ e.dom_required = need;
9388
+ throw e;
9389
+ }
9390
+ }
7861
9391
  }
7862
9392
 
7863
9393
  function registerPlugin(slug, manifest) {
@@ -7867,6 +9397,10 @@
7867
9397
  slug: slug,
7868
9398
  label: manifest.label != null ? manifest.label : null,
7869
9399
  hint: manifest.hint != null ? manifest.hint : null,
9400
+ /* 2.7.0 (sec 19.1) -- the headless profile is DECLARED, never
9401
+ inferred. Absent means false, which is every manifest ever
9402
+ written before today. */
9403
+ headless: manifest.headless === true,
7870
9404
  verbs: manifest.verbs || {},
7871
9405
  state: manifest.state || {},
7872
9406
  events: manifest.events || {},
@@ -7901,6 +9435,10 @@
7901
9435
  slug: entry.slug,
7902
9436
  label: entry.label != null ? entry.label : null,
7903
9437
  hint: entry.hint != null ? entry.hint : null,
9438
+ /* 2.7.0 (sec 19.1): an agent that discovers a plugin learns
9439
+ from the descriptor whether it needs a page -- the same
9440
+ question NAC.profile answers in full. */
9441
+ headless: !!entry.headless,
7904
9442
  verbs: [],
7905
9443
  state: [],
7906
9444
  events: [],
@@ -7980,6 +9518,192 @@
7980
9518
  return _v25_describeEntry(_v25_plugins[slug]);
7981
9519
  }
7982
9520
 
9521
+ /* ================================================================
9522
+ 19. Headless profile -- the manifest as the surface (v2.7)
9523
+ ================================================================
9524
+
9525
+ Owner decision D-26 (2026-11-25). Sections 1-14 address nodes and
9526
+ section 15 addresses a surface a node cannot reach. Neither says
9527
+ what happens when there is no document AT ALL -- a screenless
9528
+ assistant, an IVR, a voice device, a worker. The answer is that the
9529
+ extension contract already IS a capability interface: a plugin
9530
+ whose every binding is DOM-free is operable with no document, and
9531
+ plugins() + describePlugin() are the resolution surface, because
9532
+ they read the manifest and never the page.
9533
+
9534
+ What was missing was not routing. It was three things:
9535
+
9536
+ 1. Nothing DECLARED it, so neither an agent nor the adopter could
9537
+ tell a manifest that needs a page from one that does not.
9538
+ profile() answers it from the manifest, mechanically.
9539
+ 2. Provenance was silently LOST. Until 2.7.0 the emit helper
9540
+ below did document.dispatchEvent inside a try/catch, so with
9541
+ no document every nac:plugin:* row vanished and the call
9542
+ still reported success -- the exact silent damage section 7
9543
+ exists to prevent. setEventSink gives the same events the
9544
+ same shapes over a bus that is not the DOM.
9545
+ 3. A DOM primitive crashed with a ReferenceError instead of
9546
+ refusing by name. _nac_requireDocument (sec 19.3) fixed that.
9547
+
9548
+ Nothing here is a new primitive and nothing here is implicit: a
9549
+ manifest written against 2.5 or 2.6 keeps working untouched, and
9550
+ the only way into the profile is to declare headless: true. */
9551
+
9552
+ /* The non-DOM provenance bus. Additive: when a document exists the
9553
+ events still go to it, so installing a sink in a browser gives an
9554
+ audit log without changing a single consumer. */
9555
+ let _v25_event_sink = null;
9556
+ const _v25_prov_stats = { to_document: 0, to_sink: 0, dropped: 0, sink_errors: 0 };
9557
+
9558
+ function setEventSink(fn) {
9559
+ if (fn !== null && fn !== undefined && typeof fn !== 'function') {
9560
+ throw _v25_buildNacError('invalid',
9561
+ 'NAC.setEventSink: expects a function or null');
9562
+ }
9563
+ _v25_event_sink = (typeof fn === 'function') ? fn : null;
9564
+ return _v25_event_sink;
9565
+ }
9566
+
9567
+ function eventSink() { return _v25_event_sink; }
9568
+
9569
+ /* Is a provenance row observable by anybody at all right now? Two
9570
+ buses, and the answer is the OR of them. */
9571
+ function _v25_provObservable() {
9572
+ const hasDoc = (typeof document !== 'undefined' && !!document && !!document.dispatchEvent);
9573
+ return hasDoc || !!_v25_event_sink;
9574
+ }
9575
+
9576
+ function provenanceStatus() {
9577
+ return {
9578
+ document: (typeof document !== 'undefined' && !!document && !!document.dispatchEvent),
9579
+ sink: !!_v25_event_sink,
9580
+ observable: _v25_provObservable(),
9581
+ to_document: _v25_prov_stats.to_document,
9582
+ to_sink: _v25_prov_stats.to_sink,
9583
+ /* A row nobody received. Counted instead of swallowed: outside
9584
+ the headless profile the runtime does not refuse the call, so
9585
+ the loss has to be READABLE or it is still silent. */
9586
+ dropped: _v25_prov_stats.dropped,
9587
+ /* A sink that threw. The row is gone and the call is not undone;
9588
+ what the runtime owes the caller is the count, not a retry. */
9589
+ sink_errors: _v25_prov_stats.sink_errors,
9590
+ };
9591
+ }
9592
+
9593
+ function _v25_noDocument(backend) {
9594
+ if (typeof document !== 'undefined' && document) return null;
9595
+ return _v25_buildNacError('no_document',
9596
+ 'backend "' + backend + '" needs a document: it ' +
9597
+ (_V25_DOM_REASON[backend] || 'reads the DOM') +
9598
+ '. With no document there is nothing to reach -- declare a DOM-free ' +
9599
+ 'backend (sdk-call, emitter-listen) or run this plugin where a document exists ' +
9600
+ '(SPEC sec 19.1).',
9601
+ { backend: backend });
9602
+ }
9603
+
9604
+ /* Classify ONE binding. Returns null when it is DOM-free, or the row
9605
+ that goes into profile().dom_required when it is not. */
9606
+ function _v25_bindingDomNeed(kind, path, binding, entry, seen) {
9607
+ const backend = (binding && binding.backend) || null;
9608
+ const free = backend ? _V25_DOM_FREE_BACKENDS[backend] : undefined;
9609
+ if (free === true) return null;
9610
+ if (free === 'inherits') {
9611
+ /* synthetic-poll is DOM-free exactly when every state path it
9612
+ observes is. Recursion is depth-guarded: a manifest may name
9613
+ the same state from two events. */
9614
+ const observe = Array.isArray(binding.observe) ? binding.observe : [];
9615
+ for (let i = 0; i < observe.length; i++) {
9616
+ const sp = observe[i];
9617
+ const key = 'state:' + sp;
9618
+ if (seen[key]) continue;
9619
+ seen[key] = true;
9620
+ const chain = (entry.state && entry.state[sp]) || null;
9621
+ if (!chain || !chain.length) {
9622
+ return { kind: kind, path: path, backend: backend, observes: sp,
9623
+ why: 'observes the state path "' + sp + '", which this manifest does not declare' };
9624
+ }
9625
+ for (let j = 0; j < chain.length; j++) {
9626
+ const need = _v25_bindingDomNeed('state', sp, chain[j], entry, seen);
9627
+ if (need) {
9628
+ return { kind: kind, path: path, backend: backend, observes: sp,
9629
+ why: 'observes the state path "' + sp + '", which needs a document: ' + need.why };
9630
+ }
9631
+ }
9632
+ }
9633
+ return null;
9634
+ }
9635
+ return {
9636
+ kind: kind, path: path, backend: backend,
9637
+ why: backend
9638
+ ? 'the ' + backend + ' backend ' + (_V25_DOM_REASON[backend] || 'reads the DOM')
9639
+ : 'the binding declares no backend',
9640
+ };
9641
+ }
9642
+
9643
+ /* Every binding of a plugin that would need a document. The state
9644
+ chain is checked WHOLE and not just its first link: a chain whose
9645
+ fallback is a dom-mirror works in a browser and degrades to
9646
+ nothing without one, which is a declaration error in a profile
9647
+ whose entire claim is that no page is needed. */
9648
+ function _v25_domRequired(entry) {
9649
+ const out = [];
9650
+ const seen = {};
9651
+ const verbPaths = Object.keys(entry.verbs || {}).sort();
9652
+ for (let i = 0; i < verbPaths.length; i++) {
9653
+ const need = _v25_bindingDomNeed('verb', verbPaths[i], entry.verbs[verbPaths[i]], entry, seen);
9654
+ if (need) out.push(need);
9655
+ }
9656
+ const statePaths = Object.keys(entry.state || {}).sort();
9657
+ for (let i = 0; i < statePaths.length; i++) {
9658
+ const chain = entry.state[statePaths[i]] || [];
9659
+ for (let j = 0; j < chain.length; j++) {
9660
+ const need = _v25_bindingDomNeed('state', statePaths[i], chain[j], entry, seen);
9661
+ if (need) { need.binding_index = j; out.push(need); }
9662
+ }
9663
+ }
9664
+ const eventPaths = Object.keys(entry.events || {}).sort();
9665
+ for (let i = 0; i < eventPaths.length; i++) {
9666
+ const need = _v25_bindingDomNeed('event', eventPaths[i], entry.events[eventPaths[i]], entry, seen);
9667
+ if (need) out.push(need);
9668
+ }
9669
+ return out;
9670
+ }
9671
+
9672
+ /* The public predicate. Answers for ANY registered plugin, declared
9673
+ or not: an agent can discover that a manifest written without the
9674
+ profile in mind happens to be operable with no page. */
9675
+ function profile(slug) {
9676
+ if (typeof slug !== 'string' || !slug) {
9677
+ throw _v25_buildNacError('invalid', 'NAC.profile: slug must be a non-empty string');
9678
+ }
9679
+ const entry = _v25_plugins[slug];
9680
+ if (!entry) {
9681
+ throw _v25_buildNacError('plugin_not_registered',
9682
+ 'NAC.profile: plugin "' + slug + '" not registered');
9683
+ }
9684
+ const dom_required = _v25_domRequired(entry);
9685
+ return {
9686
+ slug: slug,
9687
+ declared_headless: !!entry.headless,
9688
+ headless: dom_required.length === 0,
9689
+ dom_required: _v25_copy(dom_required) || [],
9690
+ };
9691
+ }
9692
+
9693
+ /* The gate the profile buys: inside it, an unobservable call is
9694
+ refused BEFORE the effect. Outside it nothing changes -- which is
9695
+ why the profile is opt-in and not inferred. */
9696
+ function _v25_provGate(op, plugin, entry) {
9697
+ if (!entry || !entry.headless) return null;
9698
+ if (_v25_provObservable()) return null;
9699
+ return _v25_buildNacError('provenance_unobservable',
9700
+ 'NAC.' + op + ': plugin "' + plugin + '" declares headless: true and there is ' +
9701
+ 'neither a document nor an event sink, so its nac:plugin:* row would be dropped. ' +
9702
+ 'Install one with NAC.setEventSink(fn) before driving a headless surface ' +
9703
+ '(SPEC sec 19.4).',
9704
+ { plugin: plugin });
9705
+ }
9706
+
7983
9707
  /* Provenance emit helper -- the kind is one of 'invoked', 'read',
7984
9708
  'event'. Detail shape per SPEC.md sec 15.7. */
7985
9709
  function _v25_emitProvenance(kind, plugin, path, backend, request_id, ok, error, duration_ms, extra) {
@@ -7987,8 +9711,11 @@
7987
9711
  plugin: plugin,
7988
9712
  backend: backend || null,
7989
9713
  request_id: request_id,
7990
- source: 'agent',
7991
- trusted: false,
9714
+ /* 2.7.0 (TF-A19): sec 15.7 publishes 'agent' as the DEFAULT and
9715
+ an override through NAC.set_source. _dispatchSource holds
9716
+ exactly that default until a host says otherwise. */
9717
+ source: _dispatchSource.source,
9718
+ trusted: _dispatchSource.trusted,
7992
9719
  duration_ms: duration_ms,
7993
9720
  ok: !!ok,
7994
9721
  error: error || null,
@@ -7999,9 +9726,29 @@
7999
9726
  if (extra) {
8000
9727
  for (const k in extra) detail[k] = extra[k];
8001
9728
  }
9729
+ /* 2.7.0 (sec 19.4): TWO buses, and a row that reached neither is
9730
+ COUNTED. Before this the dispatch was a lone try/catch, so with
9731
+ no document the row disappeared and nothing anywhere said so. */
9732
+ const type = 'nac:plugin:' + kind;
9733
+ let delivered = false;
8002
9734
  try {
8003
- document.dispatchEvent(new CustomEvent('nac:plugin:' + kind, { detail: detail, bubbles: true }));
8004
- } catch (_) { /* if document lacks dispatch, swallow */ }
9735
+ document.dispatchEvent(new CustomEvent(type, { detail: detail, bubbles: true }));
9736
+ delivered = true;
9737
+ _v25_prov_stats.to_document++;
9738
+ } catch (_) { /* no document, or a document without dispatchEvent */ }
9739
+ if (_v25_event_sink) {
9740
+ try {
9741
+ _v25_event_sink({ type: type, detail: detail });
9742
+ delivered = true;
9743
+ _v25_prov_stats.to_sink++;
9744
+ } catch (_) {
9745
+ /* A sink that throws is a host defect. The effect already
9746
+ happened, so the runtime does not undo it and does not
9747
+ retry -- it counts the loss where a caller can read it. */
9748
+ _v25_prov_stats.sink_errors++;
9749
+ }
9750
+ }
9751
+ if (!delivered) _v25_prov_stats.dropped++;
8005
9752
  }
8006
9753
 
8007
9754
  function _v25_buildNacError(code, message, extra) {
@@ -8023,6 +9770,8 @@
8023
9770
  _v25_emitProvenance('invoked', plugin, verb_path, null, request_id, false, err.message, Date.now() - t0);
8024
9771
  return Promise.reject(err);
8025
9772
  }
9773
+ const gated = _v25_provGate('call', plugin, _v25_plugins[plugin]);
9774
+ if (gated) return Promise.reject(gated);
8026
9775
  const binding = _v25_plugins[plugin].verbs[verb_path];
8027
9776
  if (!binding) {
8028
9777
  const err = _v25_buildNacError('verb_not_declared',
@@ -8075,6 +9824,8 @@
8075
9824
  _v25_emitProvenance('read', plugin, state_path, null, request_id, false, err.message, Date.now() - t0);
8076
9825
  return Promise.reject(err);
8077
9826
  }
9827
+ const gated = _v25_provGate('read', plugin, _v25_plugins[plugin]);
9828
+ if (gated) return Promise.reject(gated);
8078
9829
  const chain = _v25_plugins[plugin].state[state_path];
8079
9830
  if (!chain) {
8080
9831
  const err = _v25_buildNacError('state_not_declared',
@@ -8144,6 +9895,8 @@
8144
9895
  throw _v25_buildNacError('plugin_not_registered',
8145
9896
  'NAC.subscribe: plugin "' + plugin + '" not registered');
8146
9897
  }
9898
+ const gated = _v25_provGate('subscribe', plugin, _v25_plugins[plugin]);
9899
+ if (gated) throw gated;
8147
9900
  const binding = _v25_plugins[plugin].events[event_path];
8148
9901
  if (!binding) {
8149
9902
  throw _v25_buildNacError('event_not_declared',
@@ -8229,6 +9982,7 @@
8229
9982
  }
8230
9983
 
8231
9984
  function narrate(plugin, nac_id) {
9985
+ _nac_requireDocument('narrate');
8232
9986
  if (typeof nac_id !== 'string' || !nac_id) return null;
8233
9987
  /* Scope by plugin if provided -- look only inside [data-nac-plugin=plugin]
8234
9988
  subtree. If plugin is omitted, fall back to global search. */
@@ -8241,7 +9995,27 @@
8241
9995
  /* Use attribute selector with CSS-safe escape via JSON.stringify
8242
9996
  to avoid injection when nac_id contains weird chars. */
8243
9997
  const safeId = '"' + String(nac_id).replace(/["\\]/g, '\\$&') + '"';
8244
- const el = root.querySelector('[data-nac-id=' + safeId + ']');
9998
+ /* The ROOT ITSELF counts (fixed 2.7.0, found by the first test
9999
+ this verb ever had).
10000
+
10001
+ querySelector searches DESCENDANTS, so when `plugin` was given
10002
+ and the asked-for id belonged to the plugin root -- the usual
10003
+ case, since a root normally carries both data-nac-plugin and
10004
+ data-nac-id -- narrate returned null. A plugin could not narrate
10005
+ itself.
10006
+
10007
+ It showed up through context(), whose breadcrumb walks up to and
10008
+ including the root and labels each entry with narrate(): the
10009
+ FIRST entry of every breadcrumb came back with label: null. An
10010
+ assistive consumer reading that breadcrumb aloud started with
10011
+ nothing. */
10012
+ let el = null;
10013
+ if (root !== document && root.getAttribute
10014
+ && root.getAttribute('data-nac-id') === String(nac_id)) {
10015
+ el = root;
10016
+ } else {
10017
+ el = root.querySelector('[data-nac-id=' + safeId + ']');
10018
+ }
8245
10019
  if (!el) return null;
8246
10020
  /* 1. aria-label */
8247
10021
  const aria = el.getAttribute('aria-label');
@@ -8280,6 +10054,7 @@
8280
10054
  }
8281
10055
 
8282
10056
  function context(plugin) {
10057
+ _nac_requireDocument('context');
8283
10058
  const out = { breadcrumb: [] };
8284
10059
  const root = _v25b_pluginRoot(plugin);
8285
10060
  if (!root) return out;
@@ -8338,6 +10113,28 @@
8338
10113
  Both delegate to NAC.read() so they inherit V25-01's full
8339
10114
  fallback-chain semantics for free. */
8340
10115
 
10116
+ /* A value rendered for a human, that cannot throw. JSON.stringify
10117
+ fails on a cycle and on a DOM node it returns '{}', neither of
10118
+ which helps a reader; a DOM node is named by what it is. */
10119
+ function _v25_renderValue(v) {
10120
+ if (v === undefined) return 'undefined';
10121
+ if (v === null) return 'null';
10122
+ if (typeof v === 'string') return JSON.stringify(v);
10123
+ if (typeof v === 'number' || typeof v === 'boolean') return String(v);
10124
+ if (v && v.nodeType === 1 && typeof v.getAttribute === 'function') {
10125
+ const id = v.getAttribute('data-nac-id');
10126
+ return '<' + String(v.tagName || 'element').toLowerCase()
10127
+ + (id ? ' data-nac-id="' + id + '"' : '') + '>'
10128
+ + ' -- a DOM element: the binding has no `extract`, so it resolved the node itself';
10129
+ }
10130
+ try {
10131
+ const out = JSON.stringify(v);
10132
+ return out === undefined ? String(v) : out;
10133
+ } catch (e) {
10134
+ return '[unserialisable ' + (typeof v) + ': ' + (e && e.message ? e.message : 'cycle') + ']';
10135
+ }
10136
+ }
10137
+
8341
10138
  function expect(plugin, statePath, value, opts) {
8342
10139
  opts = opts || {};
8343
10140
  const timeout = (typeof opts.timeout_ms === 'number') ? opts.timeout_ms : 5000;
@@ -8354,9 +10151,23 @@
8354
10151
  catch (_) { matches = false; }
8355
10152
  if (matches) { resolve(cur); return; }
8356
10153
  if (Date.now() >= deadline) {
10154
+ /* The last value is rendered DEFENSIVELY (fixed 2.7.0,
10155
+ found by the first test this verb ever had).
10156
+
10157
+ It used to be a bare JSON.stringify(cur), and `cur` is
10158
+ whatever the host's state binding returned -- a
10159
+ dom-mirror binding with no extractor returns the ELEMENT
10160
+ itself, and app state can hold a reference cycle. On
10161
+ either of those, expect() threw a TypeError out of its
10162
+ own timeout path instead of rejecting with the timeout
10163
+ it promises, so the caller got "Converting circular
10164
+ structure to JSON" from inside a verb that was supposed
10165
+ to tell them their state never matched.
10166
+ An error path that can itself throw is worse than a
10167
+ vague message. */
8357
10168
  reject(_v25_buildNacError('timeout',
8358
10169
  'NAC.expect: state "' + statePath + '" did not match within ' +
8359
- timeout + 'ms (last value: ' + JSON.stringify(cur) + ')'));
10170
+ timeout + 'ms (last value: ' + _v25_renderValue(cur) + ')'));
8360
10171
  return;
8361
10172
  }
8362
10173
  setTimeout(tick, pollMs);
@@ -8399,6 +10210,7 @@
8399
10210
  }
8400
10211
 
8401
10212
  function tree(plugin, rootId) {
10213
+ _nac_requireDocument('tree');
8402
10214
  const pluginRoot = _v25b_pluginRoot(plugin);
8403
10215
  if (!pluginRoot) return [];
8404
10216
  let start = pluginRoot;
@@ -8430,8 +10242,8 @@
8430
10242
 
8431
10243
  global.NAC = {
8432
10244
  __nac_v1_installed: true,
8433
- version: '2.6.0',
8434
- spec_version: '2.6',
10245
+ version: '2.9.0',
10246
+ spec_version: '2.9',
8435
10247
  /* v2.2.0 (V22-01) -- strict validation toggle. When true,
8436
10248
  NAC.register throws on findings (manifest_role_unknown,
8437
10249
  tab_id_manifest_role_drift, manifest_dom_role_mismatch).
@@ -8445,7 +10257,18 @@
8445
10257
  on the first slug uniqueness violation; the boot-time pass
8446
10258
  paints a red banner + dispatches nac:fatal. Set false BEFORE
8447
10259
  any register() call to opt out for a single migration window.
8448
- The flag is removed in v2.6 (enforcement becomes unconditional). */
10260
+
10261
+ 2.7.0 (TF-A13) -- "The flag is removed in v2.6 (enforcement
10262
+ becomes unconditional)" is what this comment said while running
10263
+ INSIDE 2.6 with the flag present and consulted in four places.
10264
+ The removal is WITHDRAWN (D-13, owner delegation of
10265
+ 2026-11-24), for two measured reasons: a host that set it false
10266
+ to get through a migration would start throwing on upgrade with
10267
+ no code change of its own -- the plainest form of breaking an
10268
+ adopter -- and the escape hatch is load-bearing in this
10269
+ repository too (runtime/test/stage11-plugin-id-dedup.mjs drives
10270
+ the opt-out path). The hatch is PERMANENT. What stays true is
10271
+ the default: enforcement is on unless a host says otherwise. */
8449
10272
  HARD_DEDUP: true,
8450
10273
  /* registry */
8451
10274
  register: register,
@@ -8474,10 +10297,64 @@
8474
10297
  verb (click/fill/select/invoke/tab/tab_by_label) honours the
8475
10298
  gate, so STRICT_VERSIONING default flips to true: callers
8476
10299
  MUST pass at least one expected_* or set STRICT_VERSIONING
8477
- =false explicitly. Removed in v2.6 (becomes unconditional). */
10300
+ =false explicitly.
10301
+
10302
+ 2.7.0 (TF-A13) -- "Removed in v2.6 (becomes unconditional)" was
10303
+ written here and is withdrawn (D-13, owner delegation of
10304
+ 2026-11-24), same reasoning as HARD_DEDUP above and one more
10305
+ that is specific to this one: made unconditional, every caller
10306
+ of every mutating verb MUST carry an expected_* snapshot, so an
10307
+ adopter driving click() without optimistic concurrency stops
10308
+ working on upgrade. The flag is PERMANENT and the default stays
10309
+ true. runtime/test/stage12-snapshot-versioning.mjs drives both
10310
+ sides of it. */
8478
10311
  STRICT_VERSIONING: true,
8479
10312
  eager_hashing: false,
8480
- conformance_tier: 'NAC-3-versioned',
10313
+ /* v2.4 (RFC V24-04 sec 5.11) -- the runtime's self-described tier.
10314
+
10315
+ A TIER IS NOT A LEVEL, and that distinction is the whole point
10316
+ of this comment. There are two taxonomies in this project and
10317
+ their names look alike:
10318
+
10319
+ - a conformance TIER is what the RUNTIME supports, and the
10320
+ vocabulary is RFC V24-04 sec 6: 'NAC-3' (no versioning),
10321
+ 'NAC-3-versioned' (honours expected_*), 'NAC-3-strict'. An
10322
+ agent reads it at boot to decide what it may send.
10323
+ - a conformance LEVEL is what a PAGE achieves, and the
10324
+ vocabulary is SPEC.md sec 8. `nac validate <url> --drive`
10325
+ reports one.
10326
+
10327
+ The published catalogue has said so in machine-readable form
10328
+ since 2.5.0 (audit N-29: until then api/ published this field as
10329
+ `type: "string"` and not its values, so a machine could see the
10330
+ field with no way to learn that 'NAC-3-versioned' is not a level
10331
+ name). The runtime export itself said nothing, which left the
10332
+ clarification only where a human was least likely to be
10333
+ reading. Now it is next to the value.
10334
+
10335
+ DEFAULT_CONFORMANCE_TIER is read, not retyped: the tier reject
10336
+ in the versioning gate used to carry its own copy of this
10337
+ string literal, which is audit N-17's shape in miniature. */
10338
+ conformance_tier: DEFAULT_CONFORMANCE_TIER,
10339
+ /* v2.7.0 (TF-A01). The selector drag_drop() removes from INSIDE a
10340
+ drop target before dropping. null = remove nothing, which is
10341
+ the default because a library may not delete a node out of a
10342
+ document it did not write. A target can override it with
10343
+ data-nac-drop-placeholder, which wins over this. */
10344
+ drop_placeholder_selector: null,
10345
+ /* v2.7.0 (TF-A02). The settle delay of drag_drop(), in ms. 80 is
10346
+ what this repository's demo UX needed and what every adopter
10347
+ paid; it stays the default so no existing drop changes timing,
10348
+ and opts.settle_ms overrides it per call. */
10349
+ drag_settle_ms: 80,
10350
+ /* v2.7.0 (TF-A11). Where the editor's "fix my grammar" control
10351
+ POSTs the text being edited. null = the feature is off and
10352
+ nothing is sent; the control reports that instead of guessing a
10353
+ path. It lives on THIS export on purpose: the only way to
10354
+ change it used to be a field of nac-chat-client.js, so an
10355
+ adopter loading the runtime alone could neither redirect it nor
10356
+ switch it off. */
10357
+ editor_ai_endpoint: null,
8481
10358
  markHydrationComplete: markHydrationComplete,
8482
10359
  versionHistory: versionHistory,
8483
10360
  /* v2.3 preview (V23-02): introspection helper that returns the
@@ -8516,6 +10393,10 @@
8516
10393
  list: list,
8517
10394
  find: find,
8518
10395
  read_feedback: read_feedback,
10396
+ /* v2.8.0 -- the role vocabulary, and the door into it. */
10397
+ roles: roles,
10398
+ canonical_role: canonical_role,
10399
+ register_role: register_role,
8519
10400
  snapshot_state: snapshot_state,
8520
10401
  /* write */
8521
10402
  click: click,
@@ -8657,6 +10538,17 @@
8657
10538
  /* v1.9.0 -- provenance authenticity (sec 6.2.1) */
8658
10539
  sign_provenance: sign_provenance,
8659
10540
  verify_provenance: verify_provenance,
10541
+ /* 2.7.0 -- manifest authenticity (sec 7.2). set_manifest_secret
10542
+ is the core entry point; NAC.set_provenance_secret in the
10543
+ extensions module forwards here so the example published in
10544
+ 7.2 works as written. */
10545
+ set_manifest_secret: set_manifest_secret,
10546
+ sign_manifest: sign_manifest,
10547
+ verify_manifest: verify_manifest,
10548
+ manifest_provenance: manifest_provenance,
10549
+ /* 2.7.0 -- dispatch provenance override (sec 15.7) */
10550
+ set_source: set_source,
10551
+ get_source: get_source,
8660
10552
  /* v1.9.0 -- recommended remediation (sec 6.2.30) */
8661
10553
  recommended_remediation: recommended_remediation,
8662
10554
  /* v1.2 -- error codes */
@@ -8689,6 +10581,16 @@
8689
10581
  window (a React ref, a library instance held in a closure). */
8690
10582
  plugins: plugins,
8691
10583
  describePlugin: describePlugin,
10584
+ /* v2.7 -- the headless profile (SPEC.md sec 19 / decision D-26).
10585
+ profile() says whether a registered plugin needs a document at
10586
+ all; setEventSink() carries the nac:plugin:* family over a bus
10587
+ that is not the DOM, so a screenless host keeps its provenance;
10588
+ provenanceStatus() makes the delivery -- and any loss --
10589
+ readable instead of swallowed. */
10590
+ profile: profile,
10591
+ setEventSink: setEventSink,
10592
+ eventSink: eventSink,
10593
+ provenanceStatus: provenanceStatus,
8692
10594
  registerApiHandle: registerApiHandle,
8693
10595
  unregisterApiHandle: unregisterApiHandle,
8694
10596
  apiHandles: apiHandles,