@nac3/runtime 2.5.0-alpha.5 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/SPEC.md CHANGED
@@ -1,1442 +1,1761 @@
1
- # NAC3 -- Native Agent Contract
2
-
3
- **Version:** 2.5.0-alpha.4 (alpha.3 + tab(opts) + STRICT_VERSIONING default flipped to true -- V24-04 contract fully covered across every mutating verb)
4
- **Status:** v2.5.0-alpha.4 alpha -- V24-04 SHIPPED end-to-end. Promotion alpha->latest gated on the three-layer test bar (sec 3.1 PROJECT.md)
5
- **License:** Apache-2.0
6
- **Editor:** Yujin (yujin.app)
7
-
8
- ---
9
-
10
- ## 0. Purpose
11
-
12
- NAC3 is a contract between web UIs and the agents that drive them.
13
- Agents include voice runners, LLM intermediaries, RPA bots,
14
- accessibility tools, and end-to-end test runners. The contract
15
- specifies:
16
-
17
- 1. **How elements are named** -- so an agent can ask "click the
18
- save button" and resolve it to a single DOM node.
19
- 2. **How verbs apply** -- so an agent can call `NAC.click(id)`,
20
- `NAC.fill(id, value)`, `NAC.tab(plugin, key)`, etc., without
21
- per-app glue.
22
- 3. **How completion is signalled** -- so an agent knows when a
23
- step finished, with a deterministic event family per role.
24
- 4. **How provenance is preserved** -- so a downstream system can
25
- tell a real user click from a synthesised one.
26
-
27
- NAC3 adds a thin layer on top of whatever framework you already
28
- render with. It does not replace ARIA, React, Vue, or your design
29
- system.
30
-
31
- ---
32
-
33
- ## 1. Roles
34
-
35
- Every agent-relevant DOM element carries `data-nac-role`. The
36
- canonical roles are:
37
-
38
- | Role | Meaning | Example |
39
- |------|---------|---------|
40
- | `plugin` | A self-contained UI module (a page, a panel, a widget collection). | `<article data-nac-plugin="invoice">` |
41
- | `section` | A landmark inside a plugin (header, body, footer, sidebar). | `<section data-nac-role="section">` |
42
- | `region` | A nameable area inside a section (a card cluster, a result list). | `<div data-nac-role="region">` |
43
- | `action` | A clickable widget that triggers a verb (button, link-as-button). | `<button data-nac-role="action" data-nac-action="save">` |
44
- | `field` | An input the user types or toggles (text, number, checkbox, radio, date, file). | `<input data-nac-role="field">` |
45
- | `option` | A selectable option inside a field (combobox / select / radio group child). | `<li data-nac-role="option">` |
46
- | `tab` | A switchable panel selector. **Required when `data-nac-id` matches `^tab\.`** | `<button data-nac-role="tab" data-nac-id="tab.lines">` |
47
- | `breadcrumb-item` | A breadcrumb hop. | `<a data-nac-role="breadcrumb-item">` |
48
- | `accordion-toggle` | An expand/collapse control. | `<button data-nac-role="accordion-toggle">` |
49
- | `step` | A wizard step indicator. | `<li data-nac-role="step">` |
50
- | `pagination-item` | A page-jump control in a paginated list. | `<button data-nac-role="pagination-item">` |
51
- | `confirm-button` | A confirm/cancel button inside a confirm dialog. | `<button data-nac-role="confirm-button">` |
52
- | `sort-control` | A column sort header. | `<th data-nac-role="sort-control">` |
53
- | `filter-control` | A column filter trigger. | `<button data-nac-role="filter-control">` |
54
- | `data-table` | A data-table host (v2.1). | `<table data-nac-role="data-table">` |
55
- | `navigation` | A landmark navigation region. **Not a tab.** | `<nav data-nac-role="navigation">` |
56
- | `confirm-dialog` | The modal of a confirmation request. | `<div data-nac-role="confirm-dialog">` |
57
-
58
- Roles outside this list are reserved for future use. A NAC-strict
59
- runtime SHOULD reject unknown roles at register-time (v2.2). A
60
- NAC-permissive runtime MAY treat unknown roles as `action` for
61
- back-compat (v1.9 and v2.0 default).
62
-
63
- ---
64
-
65
- ## 2. Names
66
-
67
- Every agent-resolvable element carries `data-nac-id`. The id is:
68
-
69
- - **A dotted path** (e.g. `deals.list.row.42.actions.delete`).
70
- Dots separate semantic levels; the runtime does not interpret
71
- them, but humans and LLMs do.
72
- - **Globally unique within a `data-nac-plugin` scope.** Two
73
- different plugins MAY share an id; the runtime resolves by
74
- `(plugin, id)` pair.
75
- - **Stable across re-renders.** Frameworks that produce a new id
76
- per render (random hashes, instance counters) break the contract.
77
- - **Stable across UI redesigns.** A button moves from the toolbar
78
- to a dropdown; its id MUST stay the same.
79
-
80
- Reserved id prefixes (v2.1):
81
-
82
- | Prefix | Reserved for |
83
- |--------|--------------|
84
- | `tab.` | Tab buttons. Role MUST be `tab`. |
85
- | `modal.` | Modal-scoped elements. Role is the leaf widget's role. |
86
- | `field.` | Form field shorthand. Role MUST be `field` or `option`. |
87
- | `confirm.` | Confirm dialogs. |
88
-
89
- ---
90
-
91
- ## 3. Verbs
92
-
93
- A `data-nac-role="action"` element MAY carry `data-nac-action="<verb>"`
94
- naming what it does. The verb is a free-form snake-case identifier
95
- agreed between the host and the agent. Common verbs:
96
-
97
- `save`, `cancel`, `submit`, `delete`, `edit`, `view`, `create`,
98
- `approve`, `reject`, `send`, `download`, `upload`, `refresh`,
99
- `expand`, `collapse`, `open`, `close`, `add_row`, `remove_row`.
100
-
101
- `NAC.click_by_verb(plugin, verb)` resolves a verb to the unique
102
- action under that plugin and clicks it. Multiple actions sharing
103
- the same verb under one plugin is a manifest error (lint:
104
- `duplicate_verb`).
105
-
106
- ---
107
-
108
- ## 4. Manifest
109
-
110
- Every plugin MAY register a manifest via:
111
-
112
- ```js
113
- NAC.register({
114
- plugin_slug: 'invoice',
115
- version: '1.0.0',
116
- nac_version: '2.1',
117
- elements: [
118
- { id: 'invoice.save', role: 'action',
119
- actions: [{ verb: 'save', label_i18n: { es: 'Guardar', en: 'Save', ... } }],
120
- label_i18n: { es: 'Guardar factura', en: 'Save invoice', ... } },
121
- ...
122
- ],
123
- tabs: [
124
- { nac_id: 'tab.lines', label_i18n: { es: 'Lineas', en: 'Lines' } },
125
- ...
126
- ],
127
- fields: [
128
- { id: 'field.client_name', type: 'text', required: true,
129
- label_i18n: { es: 'Cliente', en: 'Customer' } },
130
- ...
131
- ],
132
- data_tables: [...]
133
- });
134
- ```
135
-
136
- The manifest is the agent-facing source of truth. An LLM
137
- intermediary that decides "the user said 'guardar'" looks up the
138
- plugin manifest, finds the verb `save`, and emits
139
- `NAC.click_by_verb('invoice', 'save')`.
140
-
141
- ### 4.1 Required fields
142
-
143
- - `plugin_slug` -- matches `data-nac-plugin` on the host element.
144
- - `nac_version` -- the NAC3 version this manifest claims to comply
145
- with. Runtime rejects manifests claiming a version higher than
146
- itself.
147
-
148
- ### 4.2 Optional fields
149
-
150
- - `elements[]` -- the catalogue of named widgets. Each entry MUST
151
- have `id` and `role`.
152
- - `tabs[]` -- a separate top-level array for tabs. Equivalent to
153
- `elements[]` entries with `role:'tab'`. Both shapes valid.
154
- - `fields[]`, `actions[]`, `kpis[]`, `data_tables[]` -- typed
155
- sub-collections; same semantics as `elements[]` filtered by
156
- role. Demos pick the shape that reads cleanest to humans.
157
-
158
- ### 4.3 i18n
159
-
160
- Every `label_i18n` MUST cover all 10 NAC3 locales:
161
-
162
- ```
163
- es, en, pt, fr, ja, zh, hi, ar, de, it
164
- ```
165
-
166
- `i18n_strict: 'permissive'` on `NAC.autoRegister.watch()` allows
167
- partial coverage during brownfield migration; production manifests
168
- should ship 10 locales.
169
-
170
- ---
171
-
172
- ## 5. Public API
173
-
174
- ### 5.1 Imperative
175
-
176
- ```ts
177
- NAC.click(nac_id: string, opts?: ClickOpts): Promise<{ok: true}>
178
- NAC.click_by_verb(plugin: string|null, verb: string, opts?): Promise<...>
179
- NAC.fill(nac_id: string, value: string|number|boolean): Promise<...>
180
- NAC.select(nac_id: string, value: string): Promise<...>
181
- NAC.tab(plugin: string, tab_key: string): Promise<...>
182
- NAC.tab_by_label(plugin: string|null, label: string): Promise<...>
183
- NAC.go_to_section(nac_id: string): Promise<...>
184
- NAC.drag_drop(source_id, target_id, opts?: {to_index?: number}): Promise<...>
185
- NAC.set_mode(mode: 'modal'|'maximized'|'new_tab'|'new_window'): void
186
- NAC.screenshot(): Promise<string> // data URL
187
- NAC.bindAction(el, handler, {plugin, action_id}): () => void // v2.2
188
- ```
189
-
190
- ### 5.1.1 Conformance helper (v2.2)
191
-
192
- `NAC.bindAction(el, handler, ctx)` is the spec-conformant way to
193
- wire a click handler. It emits `nac:action:succeeded` (or
194
- `:failed`) automatically after the handler runs (sync, throw, or
195
- Promise). Returns an unbinder. Use this instead of raw
196
- `addEventListener('click', ...)` whenever the host supports it;
197
- brownfield code can still emit the event manually as before.
198
-
199
- ### 5.1.3 Field editor (v2.3)
200
-
201
- `NAC.edit_field(nac_id)` opens a modal that lets a user (or an
202
- agent on their behalf) edit any text field with Word-style tools:
203
-
204
- ```ts
205
- NAC.edit_field(nac_id: string): Promise<{ok:true}>
206
- ```
207
-
208
- The modal registers under `plugin_slug='nac_editor'` with these
209
- NAC-3 callable verbs:
210
-
211
- | Verb | Effect |
212
- |------|--------|
213
- | `select_word` | select the word at the caret |
214
- | `select_sentence` | select the sentence at the caret |
215
- | `select_all` | ctrl-A within the editor |
216
- | `replace` | replace selection with given text |
217
- | `delete_selection` | remove current selection |
218
- | `ai_correct_syntax` | POST current value to the LLM intermediary with system prompt "fix grammar + spelling, return only fixed text"; replace value with response |
219
- | `save` | write back to source field, dispatch input + change events, close |
220
- | `cancel` | discard, close |
221
-
222
- Esc closes (cancel). Ctrl/Cmd+Enter saves. Click on overlay
223
- backdrop cancels.
224
-
225
- Spec sec 13 will formalise the contract in v2.3; the v2.2 runtime
226
- ships a working reference impl so adopters can wire it today.
227
- Available on any field via:
228
-
229
- ```js
230
- NAC.edit_field('invoice.client_name');
231
- // or by intermediary:
232
- NAC.click_by_verb('myplugin', 'edit_field', { nac_id: 'invoice.client_name' });
233
- ```
234
-
235
- ### 5.1.4 Action payload + invoke (v2.3)
236
-
237
- NAC v2.2 actions are click-and-go: an agent triggers `NAC.click(id)`
238
- or `NAC.click_by_verb(plugin, verb)` and the host runs whatever it
239
- does. This works for verb-and-state actions (`save`, `cancel`,
240
- `submit`, `delete`) but collapses when an action needs **data**
241
- from the agent -- `utter(text)`, `search(query)`,
242
- `send_message(body)`, `upload(file)`, `schedule(date)`,
243
- `translate(text, target_lang)`. The host has no way to receive
244
- the agent's payload via a synthetic click.
245
-
246
- v2.3 closes this gap. The contract is additive: click-style
247
- verbs continue to work unchanged.
248
-
249
- ```ts
250
- NAC.invoke(action_id: string, payload: object, opts?: { timeout?: number })
251
- : Promise<{ok: true, request_id: string, ack: object|null}>
252
-
253
- NAC.utter(action_id: string,
254
- opts: { text: string, lang?: string, voice?: string, metadata?: object })
255
- : Promise<{ok: true, request_id: string, ack: object|null}>
256
- ```
257
-
258
- `NAC.invoke` dispatches a `nac:action:requested` `CustomEvent`
259
- on the host element (bubbles to document) with:
260
-
261
- ```ts
262
- detail: {
263
- action_id: string, // canonical nac_id of the host element
264
- verb: string, // payload.verb || el's data-nac-action
265
- payload: object, // arbitrary, action-specific
266
- plugin: string|null,
267
- request_id: string, // correlation token assigned by the runtime
268
- ts: number, // Date.now()
269
- }
270
- ```
271
-
272
- The host listens for `nac:action:requested`, processes the
273
- payload, and emits `nac:action:succeeded` (or `nac:action:failed`)
274
- with the same `request_id` in the detail. The runtime correlates
275
- by `request_id` and resolves the agent's Promise.
276
-
277
- Default timeout is **30 seconds** (vs 5 s for click). Override
278
- with `opts.timeout`. On timeout, the Promise rejects with
279
- `NacError('timeout', ...)`. As with click, a timeout means real
280
- failure: callers MUST treat it as such unless they have side-
281
- effect proof via another channel.
282
-
283
- `NAC.utter(id, opts)` is the ergonomic shortcut for the most
284
- common payload-bearing verb. It is equivalent to:
285
-
286
- ```js
287
- NAC.invoke(id, { verb: 'utter', text: opts.text, lang: opts.lang });
288
- ```
289
-
290
- #### Manifest declaration
291
-
292
- A payload-bearing action declares its payload schema in the
293
- manifest entry for traceability and tooling:
294
-
295
- ```js
296
- NAC.register({
297
- plugin_slug: 'atlas_pro_ad',
298
- version: '2.1.0',
299
- nac_version: '2.3',
300
- elements: [
301
- { id: 'atlas_pro_ad.mic', role: 'action',
302
- actions: [
303
- { verb: 'listen' },
304
- { verb: 'utter',
305
- payload_schema: {
306
- text: { type: 'string', required: true, max: 4000 },
307
- lang: { type: 'string',
308
- enum: ['en','es','pt','fr','it','de','ja','zh','hi','ar'] }
309
- },
310
- label_i18n: { es:'Decir', en:'Utter', /* ... 10 locales */ } }
311
- ],
312
- label_i18n: { /* ... */ } }
313
- ]
314
- });
315
- ```
316
-
317
- `payload_schema` is informational in v2.3 stable. Agents MAY
318
- validate before sending; runtimes MAY enforce it when
319
- `STRICT_VALIDATION` is `true`. Schemas are intentionally simple
320
- (JSON-Schema-shaped subset) so a runtime can validate without
321
- shipping a full JSON-Schema validator. v2.4 will formalise the
322
- schema grammar and turn enforcement into a default.
323
-
324
- #### Disabled-state semantics (v2.3 hotfix from alpha.2)
325
-
326
- `NAC.invoke` does NOT reject when the target element has
327
- `disabled` or `aria-disabled='true'` set. The `disabled` HTML
328
- attribute is a UX click guard; `invoke` is a logical
329
- payload-bearing request, not a synthetic click. Hosts that need
330
- to refuse an invoke based on UI state MUST do it in their
331
- `nac:action:requested` listener and emit `nac:action:failed`
332
- with a meaningful error code.
333
-
334
- `NAC.click`, by contrast, STILL rejects on disabled elements
335
- (click semantics preserved). Test coverage:
336
- `packages/nac/test/v23-invoke.mjs` T7/T8/T9.
337
-
338
- #### Conformance: hosts that support invoke MUST
339
-
340
- 1. Declare `actions[].payload_schema` in the manifest entry.
341
- 2. Listen for `nac:action:requested` (or use a generic listener
342
- that filters by `detail.action_id` + `detail.verb`).
343
- 3. Emit `nac:action:succeeded` -- with `detail.request_id`
344
- echoed back -- after processing, or `nac:action:failed`
345
- (with `detail.error` code) on failure.
346
- 4. NEVER emit a `:succeeded` event with a `request_id` they did
347
- not receive (prevents cross-talk between concurrent invocations).
348
-
349
- Hosts that do NOT support invoke continue to operate normally
350
- under `NAC.click()` and `NAC.click_by_verb()`. Agents that call
351
- `NAC.invoke()` against a host without an `actions[].payload_schema`
352
- entry will still receive a `request_id` but the runtime cannot
353
- guarantee delivery; the timeout fires after 30 s.
354
-
355
- #### Why this matters
356
-
357
- The full agentic surface stops being "list of buttons" and
358
- becomes "list of buttons + structured inputs". A voice ad becomes
359
- NAC.invoke-able. A search bar becomes NAC.invoke-able. A
360
- file upload becomes NAC.invoke-able. Same protocol, same
361
- provenance, same ack semantics.
362
-
363
- The first reference adopter is **Atlas Pro** -- its
364
- `atlas_pro_ad.mic` element declares both `listen` (click-only,
365
- existing) and `utter` (payload-bearing) verbs. The same
366
- `/parse` + `/tts` conversational loop drives in either case;
367
- agents that have STT call `listen`, agents that have their own
368
- language model call `utter`.
369
-
370
- #### Forward modalities (anticipated, no spec change required)
371
-
372
- `invoke` is intentionally modality-agnostic so future input
373
- families plug in without breaking the contract:
374
-
375
- | Modality | Verb (sketch) | Payload (sketch) |
376
- |----------|-----------------------|--------------------------------------------------|
377
- | Text | `utter` | `{text, lang?}` |
378
- | Search | `search` | `{query, scope?, limit?}` |
379
- | File | `upload` | `{filename, mime, data_url \| stream_id}` |
380
- | Image | `analyze_image` | `{image_url \| data_url, prompt?}` |
381
- | Video | `analyze_stream` | `{stream_url, frame_window_ms?, return?}` |
382
- | Schedule | `schedule` | `{datetime, duration_min, attendees?}` |
383
- | Code | `apply_diff` | `{file_path, unified_diff}` |
384
- | Voice | `transcribe` | `{audio_url \| data_url, lang?}` |
385
-
386
- Each modality follows the same `nac:action:requested` ->
387
- `nac:action:succeeded` / `:failed` event protocol, the same
388
- `request_id` correlation, the same timeout semantics. The
389
- runtime stays small; the verb vocabulary grows by convention
390
- between hosts and agents. Ergonomic shortcuts (`NAC.utter`,
391
- `NAC.search`, `NAC.watch`, etc.) can be added later without
392
- re-spec because each is a thin wrapper over `invoke`.
393
-
394
- ### 5.1.5 Shadow DOM resolution -- open roots (v2.3)
395
-
396
- The runtime resolves `data-nac-id` references through open
397
- shadow roots recursively. A page can mount Web Components
398
- using `attachShadow({mode:'open'})`, place
399
- `data-nac-*` attributes on elements inside the shadow tree,
400
- and any NAC3 caller (`NAC.click`, `NAC.fill`, `NAC.invoke`,
401
- etc.) resolves the target transparently.
402
-
403
- #### Resolution algorithm
404
-
405
- For a selector `S` (typically `[data-nac-id="..."]`) against a
406
- root `R` (typically `document`):
407
-
408
- 1. `R.querySelector(S)` -> if non-null, return immediately.
409
- 2. For every descendant `el` of `R`:
410
- - If `el.shadowRoot` is non-null (i.e. open shadow root):
411
- recurse with `R := el.shadowRoot`, depth +1.
412
- - Else if `el.nac3` is an object exposing a `query` method,
413
- delegate (see sec 5.1.6).
414
- 3. The recursion is **depth-capped at 10 levels**. Targets
415
- deeper than 10 are unreachable; the caller receives
416
- `code='not_found'`. The cap exists to prevent pathological
417
- walks; in practice no production codebase nests more than
418
- 3-4 shadow levels.
419
- 4. The walk is breadth-of-DOM-order: siblings before nested
420
- shadows. First match wins.
421
-
422
- #### Event propagation
423
-
424
- Events emitted by hosts inside shadow roots MUST set
425
- `composed: true` for document-level listeners to receive them.
426
- The NAC3 runtime emits all its own events with `composed:true`
427
- already; host code that emits manual `nac:*` events is
428
- responsible for the same. Without `composed:true` the event
429
- stops at the shadow boundary and the runtime's correlation
430
- machinery never sees it.
431
-
432
- #### Author responsibility
433
-
434
- The component author needs to:
435
-
436
- 1. Place `data-nac-id`, `data-nac-role`, `data-nac-action` on
437
- operable elements inside the shadow root.
438
- 2. Set `composed:true` on any custom event the host emits to
439
- signal a NAC3 contract (`nac:action:succeeded`,
440
- `nac:field:changed`, etc.).
441
- 3. Avoid `<slot>` for elements that need to be
442
- shadow-isolated -- slotted nodes live in light DOM and are
443
- resolved there instead.
444
-
445
- No manifest hint or runtime opt-in is required for open shadow
446
- roots; the resolution is automatic.
447
-
448
- #### Reference implementation
449
-
450
- The reference runtime exposes two internal helpers,
451
- `_deepQuery(selector, root)` and
452
- `_deepQueryAll(selector, root)`, that perform the walk. Public
453
- helpers `NAC.click`, `NAC.fill`, `NAC.invoke`,
454
- `NAC.describe`, etc. all go through the deep variants.
455
-
456
- #### Demos and tests
457
-
458
- - `example-v23-shadow-open.php` -- 1-, 2-, and 3-level nested
459
- open shadow demos.
460
- - `packages/nac/test/v23-shadow.mjs` T1-T3, T10 -- unit
461
- coverage including depth cap.
462
-
463
- ### 5.1.6 Shadow DOM resolution -- closed roots, voluntary exposure (v2.3)
464
-
465
- Closed shadow roots (`attachShadow({mode:'closed'})`) are
466
- opaque from outside the component author's code -- a browser
467
- security boundary, not a NAC3 decision. NAC3 cannot reach
468
- inside unless the component author voluntarily exposes a
469
- queriable surface via the contract below.
470
-
471
- #### The `el.nac3` interface contract
472
-
473
- A custom element MAY expose an interface object on its host
474
- via a getter named `nac3`:
475
-
476
- ```ts
477
- interface NAC3HostInterface {
478
- query(selector: string): Element | null; // MANDATORY
479
- queryAll(selector: string): Element[]; // RECOMMENDED
480
- describe?(): Array<{ // OPTIONAL
481
- id: string;
482
- role: string;
483
- action?: string;
484
- label?: string;
485
- }>;
486
- }
487
- ```
488
-
489
- Components opt in by implementing the getter. Components that
490
- do NOT opt in remain inaccessible to NAC3 callers (their
491
- internals stay private, as the browser intends).
492
-
493
- #### Resolution semantics
494
-
495
- During `_deepQuery(selector)`, for every visited element `el`
496
- with `el.shadowRoot === null`:
497
-
498
- 1. If `typeof el.nac3 === 'object'` and `el.nac3.query` is a
499
- function, the runtime calls `el.nac3.query(selector)`:
500
- - Return value is an Element -> resolved.
501
- - Return value is `null` -> not a match in this shadow.
502
- - Return value is anything else -> emit
503
- `nac:shadow_protocol_violation` (once per host) and skip.
504
- - Throws -> emit `nac:shadow_blocked` (reason
505
- `'exposure_threw'`, once per host) and skip.
506
- 2. Else if `el.hasAttribute('data-nac-shadow') === true` and
507
- the attribute value is `'closed'` AND there is no `nac3`
508
- interface present, the runtime emits `nac:shadow_blocked`
509
- (reason `'not_exposed'`, once per host). Author opt-in to
510
- the "I am a deliberately closed component" debug signal.
511
- 3. Else: the element is treated as a normal light-DOM
512
- element with no shadow root.
513
-
514
- #### Error event detail shapes
515
-
516
- `nac:shadow_blocked` detail:
517
-
518
- ```ts
519
- {
520
- host: Element, // the closed-shadow host
521
- reason: 'exposure_threw' | 'not_exposed',
522
- ts: number // Date.now()
523
- }
524
- ```
525
-
526
- `nac:shadow_protocol_violation` detail:
527
-
528
- ```ts
529
- {
530
- host: Element,
531
- message: string, // diagnostic message
532
- value_snapshot: string, // truncated value preview
533
- ts: number
534
- }
535
- ```
536
-
537
- Both events bubble (`bubbles: true`) and cross shadow
538
- boundaries (`composed: true`). Dedup is per-host via a
539
- WeakSet kept by the runtime; the same host emits each event
540
- **at most once per page load**.
541
-
542
- #### Why voluntary
543
-
544
- The browser enforces closed-shadow opacity. Even if NAC3
545
- defined a non-voluntary mechanism, the browser would prevent
546
- it. Voluntary exposure puts the component author in full
547
- control of what their public surface looks like for agents.
548
-
549
- The cost is per-component opt-in; the benefit is that
550
- NAC3-compliant agents work against design systems with closed
551
- shadow components (Salesforce Lightning, some GitHub Primer
552
- components, security-sensitive widgets) without per-component
553
- adapter code.
554
-
555
- #### Demos and tests
556
-
557
- - `example-v23-shadow-closed.php` -- positive
558
- (`<todo-card-closed-exposed>`) and negative
559
- (`<todo-card-closed-blind>`) side-by-side with verdict
560
- panels + live event log.
561
- - `packages/nac/test/v23-shadow.mjs` T4-T9 -- unit coverage
562
- for every error event family plus dedup semantics.
563
- - `guides/SHADOW_DOM_CLOSED.md` -- authoring guide.
564
-
565
- ### 5.1.7 Auth-aware capabilities (v2.3)
566
-
567
- NAC3 v2.3 lets the manifest declare per-action capability
568
- requirements that gate `NAC.click` and `NAC.invoke` before
569
- dispatch. The agent receives a fast rejection
570
- (`code='capability_required'`) instead of a round-trip that
571
- fails server-side.
572
-
573
- #### Manifest declaration
574
-
575
- A capability requirement attaches at the element level or at
576
- the verb level. Verb-level wins if both are present.
577
-
578
- ```js
579
- NAC.register({
580
- plugin_slug: 'fin',
581
- version: '1.0.0',
582
- nac_version: '2.3',
583
- elements: [
584
- // Element-level (covers all verbs on this id).
585
- { id: 'fin.invoice.delete', role: 'action',
586
- requires_capability: 'finance.delete_invoice',
587
- actions: [{ verb: 'delete' }] },
588
-
589
- // Verb-level (more granular).
590
- { id: 'fin.invoice.edit', role: 'action',
591
- actions: [
592
- { verb: 'edit',
593
- requires_capability: 'finance.edit_invoice' },
594
- { verb: 'view',
595
- /* no capability -> always allowed */ }
596
- ] },
597
-
598
- // Array value: OR semantics.
599
- // ("at least one of these capabilities matches")
600
- { id: 'fin.invoice.approve', role: 'action',
601
- requires_capability: ['finance.approve',
602
- 'finance.admin'],
603
- actions: [{ verb: 'approve' }] }
604
- ]
605
- });
606
- ```
607
-
608
- For AND semantics ("user needs ALL of these caps"), declare
609
- each via separate gated actions or compose at the host level
610
- in the `nac:action:requested` listener.
611
-
612
- #### Public API
613
-
614
- ```ts
615
- NAC.setCapabilities(caps: string | string[] | null): void
616
- NAC.grantCapability(cap: string): void
617
- NAC.revokeCapability(cap: string): void
618
- NAC.userCapabilities(): string[]
619
- ```
620
-
621
- `setCapabilities` replaces the entire set (use for login /
622
- session refresh). `grantCapability` / `revokeCapability` are
623
- incremental. `userCapabilities` returns a snapshot array.
624
- `setCapabilities(null)` clears the set.
625
-
626
- Hosts call these whenever the user's role changes. The set
627
- lives in the runtime; no manifest reload is required.
628
-
629
- #### Gate semantics
630
-
631
- Before dispatch, `NAC.click(id)` and `NAC.invoke(id, payload)`
632
- look up the matching manifest entry (element + verb), read
633
- `requires_capability`, and call `_hasCapability`:
634
-
635
- - No requirement declared -> allow.
636
- - Requirement declared, current set satisfies it -> allow.
637
- - Requirement declared, current set does NOT satisfy -> reject
638
- with `NacError('capability_required', ...)` AND emit
639
- `nac:command:rejected` with `detail.reason='capability_required'`.
640
-
641
- The gate runs AFTER `not_found` / `disabled` / `hidden` checks
642
- on `click` so the most specific failure surfaces. On `invoke`,
643
- the gate runs before the request event fires (the host never
644
- sees an unauthorised attempt).
645
-
646
- #### Why this matters
647
-
648
- Without the gate, an agent calling `NAC.click('finance.delete')`
649
- either succeeds (no auth gate at all -> security hole) or
650
- fails server-side with a 403 several seconds later. With the
651
- gate, the agent learns synchronously that it lacks the
652
- capability and can react appropriately (request a different
653
- flow, ask for elevation, surface the constraint to the user).
654
-
655
- This complements -- it does not replace -- server-side
656
- authorisation. Hosts MUST still enforce permissions on the
657
- server. The client gate is a UX optimisation and an
658
- intent-level signal, not a security boundary.
659
-
660
- #### Demos and tests
661
-
662
- - `packages/nac/test/v23-capabilities.mjs` -- 17 assertions
663
- covering set/get, grant/revoke, click gate, invoke gate,
664
- verb-level vs element-level resolution, OR semantics,
665
- null-clear, invalid-input rejection, regression for
666
- unguarded actions.
667
-
668
- ### 5.1.2 Strict validation flag (v2.2; default-flipped in v2.3)
669
-
670
- `NAC.STRICT_VALIDATION` (boolean). When `true`, `NAC.register()`
671
- throws an `Error` with `code='strict_validation'` and a
672
- `findings` array on any of:
673
-
674
- - `manifest_role_unknown` -- entry's role outside the canonical set.
675
- - `tab_id_manifest_role_drift` -- id matches `^tab\.` but role
676
- is not `'tab'`.
677
- - `manifest_dom_role_mismatch` -- mounted DOM element's
678
- `data-nac-role` differs from manifest entry's role.
679
-
680
- **Default value:**
681
-
682
- - **v2.2.x:** `false` (warning-only). Adopters needed a migration
683
- window.
684
- - **v2.3.x:** **`true`** (throwing). The migration window closed
685
- with the v2.2 line. Adopters with drift-laden manifests opt
686
- out by setting `NAC.STRICT_VALIDATION = false` BEFORE any
687
- `register()` call.
688
- - **v3.0:** flag removed (strict is the only mode).
689
-
690
- See `guides/MIGRATION_v2.2_to_v2.3.md` for the playbook to clean
691
- up drift findings.
692
-
693
- All async methods reject with `NacError` whose `code` is one of:
694
-
695
- - `not_found` -- the named element/role/verb is not in the DOM.
696
- - `invalid` -- argument shape is wrong.
697
- - `disabled` -- element has `disabled` or `aria-disabled='true'`
698
- (`NAC.click` only; `NAC.invoke` no longer checks per v2.3
699
- hotfix, see sec 5.1.4).
700
- - `hidden` -- element is offscreen / `aria-hidden='true'` /
701
- zero-dimension.
702
- - `capability_required` -- manifest declared
703
- `requires_capability` and the current
704
- `NAC.userCapabilities()` set does not satisfy it (v2.3, see
705
- sec 5.1.7).
706
- - `timeout` -- side effect dispatched but the conformance ack
707
- event did not arrive within 5 seconds (30 seconds for
708
- `invoke`). **A timeout means real failure**: the handler may
709
- have hung, the ack was never wired, a network race occurred.
710
- Callers MUST treat timeout as failure unless they have proof
711
- of side effect via another channel.
712
-
713
- ### 5.2 Introspection
714
-
715
- ```ts
716
- NAC.describe(): { active: string|null, plugins: PluginSnap[] }
717
- NAC.describe_v2(): { v2_scope_entries: [...], sitemap: ..., data_tables: [...] }
718
- NAC.manifest(plugin_slug: string): Manifest|null
719
- NAC.validate_global(opts?: {probe?: boolean}): Findings[]
720
- ```
721
-
722
- ### 5.3 Data tables (v2.1)
723
-
724
- ```ts
725
- NAC.registerDataTable(spec: DataTableSpec): void
726
- NAC.dt_add_row(table_id, values): {ok, row_id}
727
- NAC.dt_remove_row(table_id, row_id): {ok}
728
- NAC.dt_edit_cell(table_id, row_id, column, value): {ok} | {ok:false, error}
729
- NAC.dt_set_cell(table_id, row, col, value): {ok} | {ok:false, error}
730
- NAC.dt_select(table_id, target): {ok}
731
- NAC.dt_commit(table_id): {ok, final_state} | {ok:false, errors:[...]}
732
- NAC.dt_discard(table_id): {ok}
733
- NAC.dt_state(table_id): TableState
734
- NAC.dt_read_aggregate(table_id, agg_key, column): number|null
735
- NAC.registerDataTableComputed(table_id, column, fn): void
736
- ```
737
-
738
- A data table has a `subkind`:
739
-
740
- - `collection` -- ordered rows with optional transactional commit.
741
- Used for invoice lines, cart items, log entries.
742
- - `matrix` -- row x column grid where every cell carries a value.
743
- Used for permission matrices, schedule grids.
744
- - `matrix-singletree` -- matrix where each row collapses into a
745
- tree (rare).
746
-
747
- ---
748
-
749
- ## 6. Events
750
-
751
- Every action emits a deterministic completion event. The runtime's
752
- `NAC.click()` polls for this event and resolves when it fires.
753
-
754
- | Role | Success event | Failure event |
755
- |------|---------------|---------------|
756
- | `action` | `nac:action:succeeded` | `nac:action:failed` |
757
- | `field` | `nac:field:changed` | -- |
758
- | `option` | `nac:field:changed` | -- |
759
- | `tab` | `nac:tab:activated` | -- |
760
- | `breadcrumb-item` | `nac:breadcrumb:navigated` | -- |
761
- | `accordion-toggle` | `nac:accordion:expanded` / `:collapsed` | -- |
762
- | `step` | `nac:step:advanced` | -- |
763
- | `pagination-item` | `nac:table:page_changed` | -- |
764
- | `confirm-button` | `nac:confirm:resolved` / `:cancelled` | -- |
765
- | `sort-control` | `nac:table:sort_changed` | -- |
766
- | `filter-control` | `nac:table:filter_changed` | -- |
767
-
768
- ### 6.1 Event detail shape
769
-
770
- Every event detail carries the canonical id field plus `plugin`:
771
-
772
- ```js
773
- nac:action:succeeded {
774
- detail: { plugin: 'invoice', action_id: 'invoice.save', ... }
775
- }
776
- nac:tab:activated {
777
- detail: { plugin: 'invoice_edit_modal', tab_id: 'tab.lines', ... }
778
- }
779
- nac:field:changed {
780
- detail: { plugin: 'invoice', field_id: 'field.client_name',
781
- value: 'Acme Corp', ... }
782
- }
783
- ```
784
-
785
- ### 6.2 Emitting from a host handler
786
-
787
- A click handler MUST emit the corresponding success event after
788
- its synchronous side effect:
789
-
790
- ```js
791
- button.addEventListener('click', function (ev) {
792
- // ... do the work ...
793
- document.dispatchEvent(new CustomEvent('nac:action:succeeded', {
794
- detail: { plugin: 'invoice', action_id: 'invoice.save' }
795
- }));
796
- });
797
- ```
798
-
799
- If the work is asynchronous, emit after resolution. If the work
800
- fails, emit `nac:action:failed` with `{detail: {plugin, action_id,
801
- error: <message>}}`.
802
-
803
- The v2.2 runtime will provide `NAC.bindAction(el, handler, ctx)`
804
- that wraps `addEventListener` and emits automatically.
805
-
806
- ### 6.3 Why not use the click event itself?
807
-
808
- A DOM `click` event fires before the handler runs. NAC3's contract
809
- needs to know when the **side effect completed**, not when the
810
- click started. Hence the separate event family.
811
-
812
- ---
813
-
814
- ## 7. Provenance
815
-
816
- ### 7.1 isTrusted
817
-
818
- `event.isTrusted` is `true` for user-initiated clicks (real mouse,
819
- real keypress, screen reader activation) and `false` for
820
- synthesised clicks (`element.click()`, dispatchEvent of a built
821
- MouseEvent, automation).
822
-
823
- NAC3 MUST surface this via `event.detail.is_trusted` in the
824
- success event. Hosts that take security-sensitive actions
825
- (payment, deletion) MAY require `is_trusted === true` and reject
826
- synthetic clicks. The reference demo `example-v20-full.php`
827
- includes a button pair (`v20_panel.istrusted_real` and
828
- `v20_panel.istrusted_fake`) that demonstrates the distinction.
829
-
830
- ### 7.2 HMAC-signed manifests
831
-
832
- A manifest MAY carry a `provenance` block:
833
-
834
- ```js
835
- NAC.set_provenance_secret('your-tenant-secret');
836
- NAC.register({
837
- plugin_slug: 'invoice',
838
- ...,
839
- provenance: {
840
- signed_at: '2026-05-09T10:00:00Z',
841
- signed_by: 'tenant-X',
842
- signature: '<HMAC-SHA256 of manifest body>'
843
- }
844
- });
845
- ```
846
-
847
- The runtime computes the expected HMAC over a stable
848
- serialisation of the manifest (excluding the signature itself)
849
- and rejects manifests whose signature does not match. Used by
850
- multi-tenant deployments to prevent a tenant from spoofing
851
- another tenant's manifest.
852
-
853
- ### 7.3 Threat model
854
-
855
- See `SECURITY.md` for the full threat model. Short version:
856
-
857
- - NAC3 does not authenticate the **user**. That is your auth
858
- layer's job.
859
- - NAC3 authenticates the **manifest** (HMAC).
860
- - NAC3 distinguishes real clicks from synthesised clicks
861
- (isTrusted) so a host can refuse the latter for sensitive verbs.
862
- - NAC3 does not protect against a malicious agent running with
863
- user-level access. Such an agent can do anything the user can.
864
-
865
- ---
866
-
867
- ## 8. Conformance levels
868
-
869
- A page is **NAC-1 conformant** if:
870
-
871
- - Every clickable widget that an agent should be able to operate
872
- carries `data-nac-id` and `data-nac-role`.
873
- - Every `data-nac-role="action"` element fires
874
- `nac:action:succeeded` after its side effect.
875
- - The page registers at least one plugin manifest via
876
- `NAC.register()`.
877
- - `NAC.click(id)` works for every advertised id.
878
-
879
- A page is **NAC-2 conformant** if it also:
880
-
881
- - Registers `tabs[]`, `fields[]`, `actions[]` arrays explicitly
882
- in its manifest (not inferred from DOM).
883
- - Provides `label_i18n` covering all 10 NAC3 locales for every
884
- user-facing label.
885
- - Implements the v2.0 brownfield primitives: scope tree,
886
- ephemeral capture, autoRegister.watch.
887
- - Passes `NAC.validate_global({probe: false})` with zero
888
- `error`-severity findings.
889
-
890
- A page is **NAC-3 conformant** if it also:
891
-
892
- - Carries HMAC-signed manifests.
893
- - Distinguishes `isTrusted` for security-sensitive verbs.
894
- - Passes `NAC.validate_global({probe: true})` with zero
895
- findings.
896
-
897
- The NPM package's CLI (`npx @nac3/runtime validate <url>`) reports
898
- the highest level a page reaches.
899
-
900
- ---
901
-
902
- ## 9. Versioning
903
-
904
- NAC3 follows semver:
905
-
906
- - **Major** bump: breaking change to public API or wire formats.
907
- Adopters edit code.
908
- - **Minor** bump: new features, backward-compatible. Old code
909
- keeps working.
910
- - **Patch** bump: bug fixes, doc-only changes.
911
-
912
- Deprecation policy: a feature marked `@deprecated` in version
913
- `X.Y.0` is removed no earlier than `(X+1).0.0`. The release notes
914
- document every removal explicitly.
915
-
916
- The NPM package version mirrors the spec version: `@nac3/runtime@2.1.3`
917
- implements NAC3 v2.1 with three patch revisions.
918
-
919
- ---
920
-
921
- ## 10. Validators
922
-
923
- ### 10.1 Runtime: `NAC.validate_global()`
924
-
925
- Walks the live DOM + the registered manifests + the i18n catalog
926
- and returns an array of findings:
927
-
928
- ```ts
929
- {
930
- severity: 'error' | 'warn' | 'info',
931
- code: string, // e.g. 'tab_role_drift'
932
- nac_id: string | null,
933
- message: string,
934
- detail: Record<string, any>
935
- }
936
- ```
937
-
938
- Findings codes are stable across patch releases; new codes only
939
- in minor bumps.
940
-
941
- ### 10.2 CLI: `npx @nac3/runtime validate <target>`
942
-
943
- Wraps `validate_global` plus a static lint of HTML/manifest
944
- coherence. Exit codes:
945
-
946
- - `0` -- no findings of severity >= configured threshold.
947
- - `1` -- findings.
948
- - `2` -- the target itself failed to load.
949
-
950
- Useful in CI: `npx @nac3/runtime validate ./dist/index.html
951
- --severity=error`.
952
-
953
- ---
954
-
955
- ## 11. The system around NAC3
956
-
957
- NAC3 is a contract layer. To turn a NAC-conformant page into a
958
- voice-driven app, you also need:
959
-
960
- 1. **A speech-to-text source** (browser SpeechRecognition,
961
- Whisper API, etc).
962
- 2. **An LLM intermediary** that takes user text + the page's
963
- `NAC.describe()` snapshot + an i18n hint and emits structured
964
- actions: `[{kind: 'click', nac_id: 'X'}, {kind: 'fill', nac_id:
965
- 'Y', value: 'Z'}]`. See `guides/LLM_WIRING.md`.
966
- 3. **A chat client** that holds the conversation and dispatches
967
- the actions. The reference is `js/nac-chat-client.js`.
968
- 4. **A text-to-speech sink** for spoken replies (browser
969
- SpeechSynthesis, ElevenLabs, etc).
970
-
971
- NAC3 standardises only step 2's input/output shape (the
972
- `NAC.describe()` snapshot + the action shape). Steps 1, 3, 4 are
973
- outside the spec; you compose what you like.
974
-
975
- ---
976
-
977
- ## 12. Stability guarantees
978
-
979
- What this spec promises:
980
-
981
- 1. The set of canonical roles in section 1 will not shrink.
982
- New roles MAY be added in minor versions.
983
- 2. The event family in section 6 will not be renamed.
984
- New events MAY be added in minor versions.
985
- 3. The verbs of `NAC.click`, `NAC.fill`, etc. will not change
986
- shape in minor versions. New optional `opts` fields MAY appear.
987
- 4. The `validate_global` finding codes will not be reused for
988
- different conditions across minor versions.
989
-
990
- What this spec does NOT promise:
991
-
992
- 1. Precise wording of error messages (those are i18n catalog
993
- strings; localisations may shift).
994
- 2. The DOM strategy for finding elements (`querySelector` today;
995
- may move to a faster index later).
996
- 3. The internal manifest cache layout. Treat manifests as
997
- write-only from the host side, read-only from the agent side.
998
-
999
- ---
1000
-
1001
- ## 13. Open questions (tracked separately)
1002
-
1003
- - Should `data-nac-role="navigation"` ever resolve to a tab?
1004
- Currently no (v2.1). The v22 roadmap argues for stricter
1005
- rejection.
1006
- - Should `NAC.click()` accept relative ids (e.g. `'./save'` to
1007
- mean "save under the active plugin")? Not in v2.1; possibly v2.3.
1008
- - Should manifests support inheritance / extension across plugins
1009
- (one base manifest extended by a tenant)? Tracked as v3.0
1010
- candidate.
1011
-
1012
- ---
1013
-
1014
- ## 13.5 Governance
1015
-
1016
- NAC3 is currently stewarded by Yujin. The spec is published
1017
- under Apache 2.0; the reference runtime under MIT. Yujin
1018
- commits to moving NAC3 to a neutral foundation (W3C community
1019
- group, Linux Foundation, or equivalent industry body) if and
1020
- when adoption justifies neutral governance. Until then, spec
1021
- changes follow the RFC process documented in
1022
- `CONTRIBUTING.md`, with public comment period of at least 14
1023
- days for any change that affects the public API or wire
1024
- formats.
1025
-
1026
- Adopters: the Apache 2.0 + MIT license combination guarantees
1027
- that the spec and runtime survive any change in Yujin's
1028
- corporate status. You can fork either, run either, and ship
1029
- either, today and after we are gone. This document records
1030
- the commitment so the path to that survival is explicit, not
1031
- implicit.
1032
-
1033
- ---
1034
-
1035
- ## 14. Reference implementation
1036
-
1037
- The canonical implementation is the reference runtime distributed
1038
- as the NPM package `@nac3/runtime`. The runtime is feature-complete
1039
- for v2.1 and ships:
1040
-
1041
- - `js/nac.js` -- v1.9 base + the public API in section 5.
1042
- - `js/nac-v2-extensions.js` -- the v2.0 brownfield primitives
1043
- (scope tree, capture ephemeral, autoRegister, HMAC, isTrusted).
1044
- - `js/nac-chat-client.js` -- a reference chat client that wires
1045
- voice + LLM + dispatcher.
1046
-
1047
- Other implementations are welcome (Python for native automation
1048
- runners, Rust for embedded agents, etc). The spec, not the JS
1049
- code, is the authority.
1050
-
1051
- ---
1052
-
1053
- ## 15. Plugin extension contract -- canvas + API surfaces (v2.5)
1054
-
1055
- Sections 1-14 assume the agent-relevant surface is **DOM**. Every
1056
- addressable element has a `data-nac-id` attribute, every verb fires
1057
- through `el.click()`, every state read comes from
1058
- `el.getAttribute(...)`. This works for apps whose chrome AND
1059
- content live in DOM nodes.
1060
-
1061
- It does not work for apps where part of the surface is **canvas**
1062
- (LibreOffice / Collabora Online, Figma, Excalidraw, Miro, every
1063
- custom WebGL editor). The chrome may still be DOM (toolbars,
1064
- dialogs), but commands often need to flow through the app's own
1065
- public API (postMessage, plugin SDK, script bridge), and state may
1066
- not be readable from the DOM at all.
1067
-
1068
- v2.5 adds a small set of primitives that let a NAC3 plugin declare
1069
- its own routing contract to such surfaces. The runtime stays
1070
- agnostic of any specific app -- it learns how to talk to one only
1071
- by reading the plugin's manifest.
1072
-
1073
- ### 15.1 Why a new primitive set
1074
-
1075
- DOM-only `NAC.click(id)` cannot:
1076
-
1077
- - Send a `Send_UNO_Command` postMessage to a sandboxed Collabora
1078
- iframe.
1079
- - Call `figma.currentPage.selection = [...]` inside the Figma
1080
- plugin sandbox.
1081
- - Invoke `excalidrawAPI.setElements(...)` on a React ref.
1082
- - Read whether Bold is active on the current Collabora selection
1083
- (the toolbar reflects it; the canvas hides it).
1084
-
1085
- The fix is **not** to extend `NAC.click` with backend-detection
1086
- heuristics. The fix is to add an explicit, agnostic verb that
1087
- takes a plugin slug and a verb path, and lets the plugin's
1088
- manifest declare how that verb is routed.
1089
-
1090
- ### 15.2 The three primitives
1091
-
1092
- ```ts
1093
- NAC.registerPlugin(slug: string, manifest: PluginManifest): void
1094
- NAC.call(plugin: string, verb_path: string, args?: object): Promise<any>
1095
- NAC.read(plugin: string, state_path: string): Promise<any>
1096
- NAC.subscribe(plugin: string, event_path: string,
1097
- cb: (data: any) => void): SubscriptionHandle
1098
- NAC.unsubscribe(handle: SubscriptionHandle): void
1099
- ```
1100
-
1101
- - `registerPlugin(slug, manifest)` registers a v2.5 plugin. A given
1102
- `slug` MAY appear in both the DOM manifest registry (section 5)
1103
- and the v2.5 extension registry; the two coexist. v2.5 calls
1104
- resolve only through the v2.5 registry.
1105
- - `call` invokes a declared verb. Routing is chosen by the
1106
- manifest, not by the agent. Resolves with whatever the backend
1107
- returned (often `undefined` / `{ok: true}`); rejects with
1108
- `NacError` if the verb is unknown, the backend fails, or the
1109
- response shape is invalid.
1110
- - `read` returns a declared state value. The runtime walks the
1111
- state's fallback chain in declared order and returns the first
1112
- source that resolves; rejects only when every source in the
1113
- chain failed.
1114
- - `subscribe` attaches a listener to a declared event. Returns a
1115
- handle that the caller passes to `unsubscribe` to clean up.
1116
- Events MAY be backed by a real upstream event source or
1117
- synthesised via polling / MutationObserver -- the manifest
1118
- declares which.
1119
-
1120
- All four functions are async (Promise-returning) except
1121
- `unsubscribe`, which is synchronous and idempotent.
1122
-
1123
- ### 15.3 Plugin manifest shape
1124
-
1125
- ```ts
1126
- interface PluginManifest {
1127
- slug: string;
1128
- verbs: { [verb_path: string]: VerbBinding };
1129
- state: { [state_path: string]: StateBinding[] };
1130
- events: { [event_path: string]: EventBinding };
1131
- }
1132
-
1133
- interface VerbBinding {
1134
- backend: BackendKind;
1135
- /* backend-specific fields (see 15.4) */
1136
- [k: string]: any;
1137
- }
1138
-
1139
- interface StateBinding {
1140
- backend: BackendKind;
1141
- /* backend-specific fields (see 15.4) */
1142
- extract?: string; /* extractor DSL string (see 15.5) */
1143
- [k: string]: any;
1144
- }
1145
-
1146
- interface EventBinding {
1147
- backend: BackendKind;
1148
- /* backend-specific fields */
1149
- [k: string]: any;
1150
- }
1151
-
1152
- type BackendKind =
1153
- | 'postmessage'
1154
- | 'postmessage-listen'
1155
- | 'sdk-call'
1156
- | 'script-bridge'
1157
- | 'dom-mirror'
1158
- | 'same-origin-window'
1159
- | 'synthetic-mutation'
1160
- | 'synthetic-poll';
1161
- ```
1162
-
1163
- Manifests are pure JSON (no JS callbacks). Forge, Sumi, and any
1164
- future tooling generates them as data; the runtime interprets the
1165
- backend names from a fixed vocabulary.
1166
-
1167
- Verbs and events have **exactly one** binding. State has an
1168
- **ordered array** of bindings: the runtime walks the chain in
1169
- order, returning the first source that successfully resolved.
1170
-
1171
- ### 15.4 Backend vocabulary
1172
-
1173
- | Kind | Used for | Required fields |
1174
- |------|----------|-----------------|
1175
- | `postmessage` | Verb: post a message to an iframe via `postMessage`. | `target` (CSS selector of the iframe to send to), `message` (MessageId string), `values` (object literal interpolated with args), `values_from_args` (optional array of arg keys to forward verbatim) |
1176
- | `postmessage-listen` | Event: listen for a specific incoming `MessageId` on `window.message`. | `source` (CSS selector of the iframe to filter origin by; if omitted, accept any source), `message` (MessageId to match), `extract` (extractor DSL into the message data) |
1177
- | `sdk-call` | Verb: call a globally-exposed JS function (e.g. Figma plugin, Excalidraw API). | `path` (dotted path into `window`, e.g. `figma.currentPage.selection`), `mode` (`assign` to set the path to the args value, `invoke` to call it as a function with the args object) |
1178
- | `script-bridge` | Verb or state: invoke an app's scripting bridge (Collabora's `CallPythonScript`, LibreOffice UNO bridge, Google Apps Script). | `bridge` (a backend-specific identifier like `collabora.python`), `script` (script identifier), `function` (function name to run), `args` (object literal interpolated with the call args), `response_match` (for state: the response MessageId to wait on), `timeout_ms` (optional, default 5000) |
1179
- | `dom-mirror` | State: read from a DOM element whose attribute / class / text mirrors a canvas-internal state (e.g. a toolbar button highlighted when its formatting is active on the current selection). | `selector` (CSS selector to query), `extract` (extractor DSL, see 15.5) |
1180
- | `same-origin-window` | State: read from `iframe.contentWindow.<path>` when the iframe is same-origin. The runtime detects cross-origin and falls through. | `target` (CSS selector of the iframe), `path` (dotted path into `contentWindow`) |
1181
- | `synthetic-mutation` | Event: synthesise an event by observing DOM mutations on one or more state sources and re-emitting when the observed value changes. | `observe` (array of state paths to watch; the runtime calls `read` on each and diffs across mutations), `throttle_ms` (optional, default 100) |
1182
- | `synthetic-poll` | Event: synthesise an event by polling state sources. | `observe` (array of state paths), `interval_ms` (default 250) |
1183
-
1184
- Each backend MUST be implemented by the runtime as a self-contained
1185
- dispatcher (`dispatch(binding, args, context) -> Promise<value>`).
1186
- Adding a new backend type to the spec requires bumping the spec
1187
- version; runtimes ignoring unknown backends MUST reject manifests
1188
- that declare them (no silent skip).
1189
-
1190
- ### 15.5 Extractor mini-DSL
1191
-
1192
- State backends and the `postmessage-listen` event backend often
1193
- need to pluck a field out of a larger object. The runtime ships
1194
- a tiny declarative DSL so manifests stay JSON-only:
1195
-
1196
- | Syntax | Meaning | Example input -> output |
1197
- |--------|---------|-------------------------|
1198
- | `field.path.to.value` | Dotted path traversal. | `{a:{b:1}}` with `a.b` -> `1` |
1199
- | `attribute:NAME` | DOM only: read `el.getAttribute(NAME)`. | `<i data-x="hi">` with `attribute:data-x` -> `'hi'` |
1200
- | `text` | DOM only: read `el.textContent`. | `<span>hi</span>` with `text` -> `'hi'` |
1201
- | `classList.contains:CLASS` | DOM only: `el.classList.contains(CLASS)` -> boolean. | `<button class="active">` with `classList.contains:active` -> `true` |
1202
- | `value` | DOM only: read `el.value`. | `<input value="x">` with `value` -> `'x'` |
1203
- | `present` | DOM only: returns `true` if the selector resolved an element, `false` otherwise. | selector matched -> `true` |
1204
-
1205
- Composition is not supported in v2.5; an extractor is exactly one
1206
- of the rows above. A manifest needing complex transformation
1207
- declares a `script-bridge` instead.
1208
-
1209
- ### 15.6 Fallback chain semantics for `state`
1210
-
1211
- `state[path]` is an array of bindings. `NAC.read(plugin, path)` walks
1212
- the array in order. For each binding:
1213
-
1214
- 1. The runtime invokes the backend's dispatcher.
1215
- 2. If the dispatcher resolves with a value (including `false`, `0`,
1216
- empty string, but NOT `undefined`), `read` returns that value.
1217
- 3. If the dispatcher rejects, or resolves with `undefined`, the
1218
- runtime advances to the next binding in the array.
1219
- 4. If no binding produced a value, `read` rejects with
1220
- `NacError('state_unreadable', ...)` whose `err.attempts: [...]`
1221
- carries one entry per attempted backend with `{backend, reason}`.
1222
-
1223
- Rationale: the chain encodes the manifest author's preference
1224
- order. The fastest, cheapest, freshest source is declared first;
1225
- fallbacks degrade gracefully. The runtime never silently picks an
1226
- inferior source first.
1227
-
1228
- ### 15.7 Provenance for synthetic actions
1229
-
1230
- Every `NAC.call` dispatch emits a `nac:plugin:invoked` event on
1231
- `document` after the backend returns. The detail payload:
1232
-
1233
- ```js
1234
- {
1235
- plugin: 'collabora.writer',
1236
- verb_path: 'uno.Bold',
1237
- backend: 'postmessage',
1238
- request_id: 'pi_<random hex>',
1239
- source: 'agent', // see sec 7
1240
- trusted: false,
1241
- duration_ms: 12,
1242
- ok: true,
1243
- error: null,
1244
- }
1245
- ```
1246
-
1247
- Same shape for `nac:plugin:read` (after a `read`) and
1248
- `nac:plugin:event` (synthesised event re-emit). `source` defaults
1249
- to `'agent'`; hosts that wrap the runtime in a user-facing UI MAY
1250
- override via the existing `NAC.set_source(...)` mechanism (sec 7).
1251
-
1252
- ### 15.8 Worked example -- Collabora Writer
1253
-
1254
- ```json
1255
- {
1256
- "slug": "collabora.writer",
1257
- "verbs": {
1258
- "uno.Bold": {
1259
- "backend": "postmessage",
1260
- "target": "iframe[data-collabora-frame]",
1261
- "message": "Send_UNO_Command",
1262
- "values": { "Command": ".uno:Bold" }
1263
- },
1264
- "doc.save": {
1265
- "backend": "postmessage",
1266
- "target": "iframe[data-collabora-frame]",
1267
- "message": "Action_Save",
1268
- "values_from_args": ["DontTerminateEdit", "Notify"]
1269
- }
1270
- },
1271
- "state": {
1272
- "selection.isBold": [
1273
- { "backend": "dom-mirror",
1274
- "selector": "[data-nac-id='toolbar.bold']",
1275
- "extract": "classList.contains:selected" },
1276
- { "backend": "script-bridge",
1277
- "bridge": "collabora.python",
1278
- "script": "yujin_state.py",
1279
- "function": "GetSelectionState",
1280
- "response_match": "CallPythonScript-Result",
1281
- "extract": "Values.is_bold" }
1282
- ],
1283
- "doc.modified": [
1284
- { "backend": "same-origin-window",
1285
- "target": "iframe[data-collabora-frame]",
1286
- "path": "app.file.modified" }
1287
- ]
1288
- },
1289
- "events": {
1290
- "doc.modified": {
1291
- "backend": "postmessage-listen",
1292
- "source": "iframe[data-collabora-frame]",
1293
- "message": "Doc_ModifiedStatus",
1294
- "extract": "Values.Modified"
1295
- },
1296
- "selection.changed": {
1297
- "backend": "synthetic-mutation",
1298
- "observe": ["selection.isBold", "selection.isItalic"],
1299
- "throttle_ms": 100
1300
- }
1301
- }
1302
- }
1303
- ```
1304
-
1305
- The agent calls `NAC.call('collabora.writer', 'uno.Bold')`; the
1306
- runtime routes through the `postmessage` backend, posts
1307
- `Send_UNO_Command` to the iframe. To confirm the effect occurred
1308
- (see sec 17), the agent calls
1309
- `await NAC.read('collabora.writer', 'selection.isBold')`; the
1310
- runtime tries the toolbar mirror first (fast, free), falls back to
1311
- the Python script bridge if the mirror is unavailable. The agent
1312
- never knows or cares which source answered.
1313
-
1314
- ### 15.9 Errors
1315
-
1316
- `NAC.call` / `read` / `subscribe` reject with `NacError` whose `code`
1317
- is one of:
1318
-
1319
- - `plugin_not_registered` -- the slug has no v2.5 manifest.
1320
- - `verb_not_declared` -- the verb path is not in the manifest.
1321
- - `state_not_declared` -- the state path is not in the manifest.
1322
- - `event_not_declared` -- the event path is not in the manifest.
1323
- - `backend_unknown` -- the manifest declares a backend the runtime
1324
- does not implement. Manifest MUST be rejected at register time;
1325
- this error only surfaces if a runtime accepts a future manifest
1326
- format it then cannot dispatch.
1327
- - `backend_target_missing` -- the backend's target (iframe, JS
1328
- path, DOM selector) is not findable.
1329
- - `cross_origin_blocked` -- `same-origin-window` was attempted
1330
- against a cross-origin iframe.
1331
- - `state_unreadable` -- every binding in a state chain failed; see
1332
- 15.6.
1333
- - `timeout` -- a backend did not respond within its declared
1334
- `timeout_ms` (default 5000 for verbs, 1000 for state reads).
1335
- - `invalid` -- argument shape is wrong (bad slug, malformed
1336
- manifest at register time, etc).
1337
-
1338
- ---
1339
-
1340
- ## 16. Tree navigation (v2.5 -- SHIPPED in 2.5.0-alpha.5 / RFC V25-02)
1341
-
1342
- Hierarchical command navigation primitives for assistive flows and
1343
- voice runners that need to describe what they can do from the
1344
- current focus.
1345
-
1346
- **API surface:**
1347
-
1348
- - `NAC.context(plugin) -> { breadcrumb: [{nac_id, label}, ...] }`
1349
- Walks up from `document.activeElement` through ancestor elements
1350
- carrying `data-nac-id`, stopping at the plugin root. Returns an
1351
- empty breadcrumb if nothing is focused inside the plugin. Each
1352
- crumb's `label` comes from `narrate` (sec 17).
1353
-
1354
- - `NAC.tree(plugin, rootId?) -> [{nac_id, label, opens?, leaf?}, ...]`
1355
- Enumerates the IMMEDIATE addressable children of `rootId` (or the
1356
- plugin root if omitted). "Immediate" means no other `data-nac-id`
1357
- element lies between the start and the child. For each entry:
1358
- - `label` resolved via `narrate`
1359
- - `opens` mirrors the `data-nac-opens` attribute when present
1360
- - `leaf` is `true` when `data-nac-leaf` is present
1361
-
1362
- **Authoring attributes:**
1363
-
1364
- - `data-nac-opens="<target-nac-id>"`: declares this node opens /
1365
- drills into the element identified by the target id. Lets agents
1366
- follow the navigation chain without guessing names.
1367
- - `data-nac-leaf`: explicit terminal marker; downstream agents know
1368
- no further drill is possible.
1369
-
1370
- **Errors:** `tree` returns `[]` for an unknown rootId (silent
1371
- empty, not an error). `context` always returns
1372
- `{ breadcrumb: [] }` for unknown plugins.
1373
-
1374
- ---
1375
-
1376
- ## 17. Asistive labels (v2.5 -- SHIPPED in 2.5.0-alpha.5 / RFC V25-03)
1377
-
1378
- Canonical human-readable label resolution. One function for screen
1379
- readers, TTS, voice flows, audit logs, mobile assistive surfaces.
1380
-
1381
- **API surface:**
1382
-
1383
- - `NAC.narrate(plugin, nac_id) -> string | null`
1384
- Returns `null` if the plugin or nac_id cannot be found. Otherwise
1385
- the label following this strict priority order:
1386
-
1387
- 1. **`aria-label`** -- a11y-first; respected unless whitespace-only.
1388
- 2. **visible text** -- `textContent` of the element excluding any
1389
- nested `data-nac-id` subtrees (those have their own narrate
1390
- resolution; they get excluded so spoken output stays scoped).
1391
- 3. **`data-nac-label`** -- explicit author override; useful when
1392
- visible text contains icon glyphs or i18n keys.
1393
- 4. **`nac_id` fallback** -- worst case; signals "no label authored".
1394
-
1395
- Whitespace-only values at any tier collapse to the next tier.
1396
-
1397
- **Validation:** `validate_global()` may emit warnings in the
1398
- `plugin_instance_violations` bucket for ordinal-shaped nac_ids
1399
- (`btn-1`, `btn-2`, ...) lacking any of the upper-tier labels.
1400
-
1401
- ---
1402
-
1403
- ## 18. Effect detection (v2.5 -- SHIPPED in 2.5.0-alpha.5 / RFC V25-04)
1404
-
1405
- Closes the "silent damage" gap: an agent confirms the EFFECT of
1406
- an action, not just that the command was emitted. Both primitives
1407
- compose with `NAC.read()` so any V25-01 backend works (postmessage,
1408
- sdk-call, dom-mirror, ...).
1409
-
1410
- **API surface:**
1411
-
1412
- - `NAC.expect(plugin, statePath, value, opts?) -> Promise<value>`
1413
- Polls `NAC.read(plugin, statePath)` until the comparator returns
1414
- truthy or the deadline fires. Resolves with the resolved value;
1415
- rejects with `NacError('timeout', ...)` on deadline.
1416
-
1417
- Read failures during polling are retried until the deadline
1418
- (treated as "not yet observable", not as a hard error).
1419
-
1420
- Options:
1421
- - `timeout_ms` (default `5000`)
1422
- - `poll_ms` (default `100`)
1423
- - `comparator` (default `(cur, want) => cur === want`)
1424
- Receives `(current, expected)`, returns boolean.
1425
-
1426
- - `NAC.diff(plugin, statePath, actionFn) -> Promise<{before, after, changed}>`
1427
- Reads state, awaits `actionFn()`, reads state again. Returns
1428
- both snapshots and a `changed` boolean computed via JSON-stringify
1429
- compare (so `undefined`-vs-value still flags as changed).
1430
- Read failures collapse to `undefined`.
1431
-
1432
- **Composition notes:** `diff` only captures the START and END
1433
- snapshot; it does NOT observe intermediate states inside the
1434
- action. Use `expect` if your concern is "the state passes through
1435
- some specific value at some point".
1436
-
1437
- ---
1438
-
1439
- *This document is the canonical NAC3 v2.5 specification.
1440
- Sections 0-14 are unchanged from v2.4 stable. Sections 15-18 ship
1441
- in v2.5. Edits to this file constitute spec changes and require an
1442
- RFC; see `CONTRIBUTING.md`.*
1
+ # NAC3 -- Native Agent Contract
2
+
3
+ **Version:** 2.5.0 (stable -- the complete v2.5 surface: narrate, context+tree, expect+diff)
4
+ **Status:** v2.5.0-alpha.5 -- all 8 SHIPPED RFCs (V24-01/02/04/05 + V25-01/02/03/04) have runtime + Layer 2 visual + Layer 3 Pilot LIVE evidence. Promoted to npm dist-tag `latest`.
5
+ **License:** Apache-2.0
6
+ **Editor:** Yujin (yujin.app)
7
+
8
+ ---
9
+
10
+ ## 0. Purpose
11
+
12
+ NAC3 is a contract between web UIs and the agents that drive them.
13
+ Agents include voice runners, LLM intermediaries, RPA bots,
14
+ accessibility tools, and end-to-end test runners. The contract
15
+ specifies:
16
+
17
+ 1. **How elements are named** -- so an agent can ask "click the
18
+ save button" and resolve it to a single DOM node.
19
+ 2. **How verbs apply** -- so an agent can call `NAC.click(id)`,
20
+ `NAC.fill(id, value)`, `NAC.tab(plugin, key)`, etc., without
21
+ per-app glue.
22
+ 3. **How completion is signalled** -- so an agent knows when a
23
+ step finished, with a deterministic event family per role.
24
+ 4. **How provenance is preserved** -- so a downstream system can
25
+ tell a real user click from a synthesised one.
26
+
27
+ NAC3 adds a thin layer on top of whatever framework you already
28
+ render with. It does not replace ARIA, React, Vue, or your design
29
+ system.
30
+
31
+ ---
32
+
33
+ ## 1. Roles
34
+
35
+ Every agent-relevant DOM element carries `data-nac-role`. The
36
+ canonical roles are:
37
+
38
+ | Role | Meaning | Example |
39
+ |------|---------|---------|
40
+ | `plugin` | A self-contained UI module (a page, a panel, a widget collection). | `<article data-nac-plugin="invoice">` |
41
+ | `section` | A landmark inside a plugin (header, body, footer, sidebar). | `<section data-nac-role="section">` |
42
+ | `region` | A nameable area inside a section (a card cluster, a result list). | `<div data-nac-role="region">` |
43
+ | `action` | A clickable widget that triggers a verb (button, link-as-button). | `<button data-nac-role="action" data-nac-action="save">` |
44
+ | `field` | An input the user types or toggles (text, number, checkbox, radio, date, file). | `<input data-nac-role="field">` |
45
+ | `option` | A selectable option inside a field (combobox / select / radio group child). | `<li data-nac-role="option">` |
46
+ | `tab` | A switchable panel selector. **Required when `data-nac-id` matches `^tab\.`** | `<button data-nac-role="tab" data-nac-id="tab.lines">` |
47
+ | `breadcrumb-item` | A breadcrumb hop. | `<a data-nac-role="breadcrumb-item">` |
48
+ | `accordion-toggle` | An expand/collapse control. | `<button data-nac-role="accordion-toggle">` |
49
+ | `step` | A wizard step indicator. | `<li data-nac-role="step">` |
50
+ | `pagination-item` | A page-jump control in a paginated list. | `<button data-nac-role="pagination-item">` |
51
+ | `confirm-button` | A confirm/cancel button inside a confirm dialog. | `<button data-nac-role="confirm-button">` |
52
+ | `sort-control` | A column sort header. | `<th data-nac-role="sort-control">` |
53
+ | `filter-control` | A column filter trigger. | `<button data-nac-role="filter-control">` |
54
+ | `data-table` | A data-table host (since 2.1). | `<table data-nac-role="data-table">` |
55
+ | `navigation` | A landmark navigation region. **Not a tab.** | `<nav data-nac-role="navigation">` |
56
+ | `confirm-dialog` | The modal of a confirmation request. | `<div data-nac-role="confirm-dialog">` |
57
+ | `draggable` | An element the user can pick up and move (since 1.6.2). | `<li data-nac-role="draggable">` |
58
+ | `drop-target` | A place a `draggable` can be dropped (since 1.6.2). | `<ul data-nac-role="drop-target">` |
59
+ | `button` | **Tolerated, not recommended.** A legacy button that only needs to be clickable, with no action contract. The runtime treats it as `action`. Prefer `action` with an explicit `data-nac-action`. | `<button data-nac-role="button">` |
60
+
61
+ Roles outside this list are reserved for future use. A NAC-strict
62
+ runtime SHOULD reject unknown roles at register-time (v2.2). A
63
+ NAC-permissive runtime MAY treat unknown roles as `action` for
64
+ back-compat (v1.9 and v2.0 default).
65
+
66
+ This table is the normative list, and it is published as data: the
67
+ machine-readable catalogue at `api/latest/contract.json` carries
68
+ every role the reference runtime accepts, each flagged with
69
+ `declared_in_spec_table` so the two lists can be compared without
70
+ reading prose. They agree as of v2.5. Any future divergence is
71
+ visible in that flag rather than hidden in a difference of opinion
72
+ between a document and an implementation.
73
+
74
+ ---
75
+
76
+ ## 2. Names
77
+
78
+ Every agent-resolvable element carries `data-nac-id`. The id is:
79
+
80
+ - **A dotted path** (e.g. `deals.list.row.42.actions.delete`).
81
+ Dots separate semantic levels; the runtime does not interpret
82
+ them, but humans and LLMs do.
83
+ - **Globally unique within a `data-nac-plugin` scope.** Two
84
+ different plugins MAY share an id; the runtime resolves by
85
+ `(plugin, id)` pair.
86
+ - **Stable across re-renders.** Frameworks that produce a new id
87
+ per render (random hashes, instance counters) break the contract.
88
+ - **Stable across UI redesigns.** A button moves from the toolbar
89
+ to a dropdown; its id MUST stay the same.
90
+
91
+ Reserved id prefixes (since 2.1):
92
+
93
+ | Prefix | Reserved for |
94
+ |--------|--------------|
95
+ | `tab.` | Tab buttons. Role MUST be `tab`. |
96
+ | `modal.` | Modal-scoped elements. Role is the leaf widget's role. |
97
+ | `field.` | Form field shorthand. Role MUST be `field` or `option`. |
98
+ | `confirm.` | Confirm dialogs. |
99
+
100
+ ---
101
+
102
+ ## 3. Verbs
103
+
104
+ A `data-nac-role="action"` element MAY carry `data-nac-action="<verb>"`
105
+ naming what it does. The verb is a free-form snake-case identifier
106
+ agreed between the host and the agent. Common verbs:
107
+
108
+ `save`, `cancel`, `submit`, `delete`, `edit`, `view`, `create`,
109
+ `approve`, `reject`, `send`, `download`, `upload`, `refresh`,
110
+ `expand`, `collapse`, `open`, `close`, `add_row`, `remove_row`.
111
+
112
+ `NAC.click_by_verb(plugin, verb)` resolves a verb to the unique
113
+ action under that plugin and clicks it. Multiple actions sharing
114
+ the same verb under one plugin is a manifest error (lint:
115
+ `duplicate_verb`).
116
+
117
+ ---
118
+
119
+ ## 4. Manifest
120
+
121
+ Every plugin MAY register a manifest via:
122
+
123
+ ```js
124
+ NAC.register({
125
+ plugin_slug: 'invoice',
126
+ version: '1.0.0',
127
+ nac_version: '2.1',
128
+ elements: [
129
+ { id: 'invoice.save', role: 'action',
130
+ actions: [{ verb: 'save', label_i18n: { es: 'Guardar', en: 'Save', ... } }],
131
+ label_i18n: { es: 'Guardar factura', en: 'Save invoice', ... } },
132
+ ...
133
+ ],
134
+ tabs: [
135
+ { nac_id: 'tab.lines', label_i18n: { es: 'Lineas', en: 'Lines' } },
136
+ ...
137
+ ],
138
+ fields: [
139
+ { id: 'field.client_name', type: 'text', required: true,
140
+ label_i18n: { es: 'Cliente', en: 'Customer' } },
141
+ ...
142
+ ],
143
+ data_tables: [...]
144
+ });
145
+ ```
146
+
147
+ The manifest is the agent-facing source of truth. An LLM
148
+ intermediary that decides "the user said 'guardar'" looks up the
149
+ plugin manifest, finds the verb `save`, and emits
150
+ `NAC.click_by_verb('invoice', 'save')`.
151
+
152
+ ### 4.1 Required fields
153
+
154
+ - `plugin_slug` -- matches `data-nac-plugin` on the host element.
155
+ - `nac_version` -- the NAC3 version this manifest claims to comply
156
+ with. Runtime rejects manifests claiming a version higher than
157
+ itself.
158
+
159
+ ### 4.2 Optional fields
160
+
161
+ - `elements[]` -- the catalogue of named widgets. Each entry MUST
162
+ have `id` and `role`.
163
+ - `tabs[]` -- a separate top-level array for tabs. Equivalent to
164
+ `elements[]` entries with `role:'tab'`. Both shapes valid.
165
+ - `fields[]`, `actions[]`, `kpis[]`, `data_tables[]` -- typed
166
+ sub-collections; same semantics as `elements[]` filtered by
167
+ role. Demos pick the shape that reads cleanest to humans.
168
+
169
+ ### 4.3 i18n
170
+
171
+ Every `label_i18n` MUST cover all 10 NAC3 locales:
172
+
173
+ ```
174
+ es, en, pt, fr, ja, zh, hi, ar, de, it
175
+ ```
176
+
177
+ `i18n_strict: 'permissive'` on `NAC.autoRegister.watch()` allows
178
+ partial coverage during brownfield migration; production manifests
179
+ should ship 10 locales.
180
+
181
+ ---
182
+
183
+ ## 5. Public API
184
+
185
+ ### 5.1 Imperative
186
+
187
+ ```ts
188
+ NAC.click(nac_id: string, opts?: ClickOpts): Promise<{ok: true}>
189
+ NAC.click_by_verb(plugin: string|null, verb: string, opts?): Promise<...>
190
+ NAC.fill(nac_id: string, value: string|number|boolean): Promise<...>
191
+ NAC.select(nac_id: string, value: string): Promise<...>
192
+ NAC.tab(plugin: string, tab_key: string): Promise<...>
193
+ NAC.tab_by_label(plugin: string|null, label: string): Promise<...>
194
+ NAC.go_to_section(nac_id: string): Promise<...>
195
+ NAC.drag_drop(source_id, target_id, opts?: {to_index?: number}): Promise<...>
196
+ NAC.set_mode(mode: 'modal'|'maximized'|'new_tab'|'new_window'): void
197
+ NAC.screenshot(): Promise<string> // data URL
198
+ NAC.bindAction(el, handler, {plugin, action_id}): () => void // v2.2
199
+ ```
200
+
201
+ ### 5.1.1 Conformance helper (v2.2)
202
+
203
+ `NAC.bindAction(el, handler, ctx)` is the spec-conformant way to
204
+ wire a click handler. It emits `nac:action:succeeded` (or
205
+ `:failed`) automatically after the handler runs (sync, throw, or
206
+ Promise). Returns an unbinder. Use this instead of raw
207
+ `addEventListener('click', ...)` whenever the host supports it;
208
+ brownfield code can still emit the event manually as before.
209
+
210
+ ### 5.1.3 Field editor (v2.3)
211
+
212
+ `NAC.edit_field(nac_id)` opens a modal that lets a user (or an
213
+ agent on their behalf) edit any text field with Word-style tools:
214
+
215
+ ```ts
216
+ NAC.edit_field(nac_id: string): Promise<{ok:true}>
217
+ ```
218
+
219
+ The modal registers under `plugin_slug='nac_editor'` with these
220
+ NAC3-callable verbs:
221
+
222
+ | Verb | Effect |
223
+ |------|--------|
224
+ | `select_word` | select the word at the caret |
225
+ | `select_sentence` | select the sentence at the caret |
226
+ | `select_all` | ctrl-A within the editor |
227
+ | `replace` | replace selection with given text |
228
+ | `delete_selection` | remove current selection |
229
+ | `ai_correct_syntax` | POST current value to the LLM intermediary with system prompt "fix grammar + spelling, return only fixed text"; replace value with response |
230
+ | `save` | write back to source field, dispatch input + change events, close |
231
+ | `cancel` | discard, close |
232
+
233
+ Esc closes (cancel). Ctrl/Cmd+Enter saves. Click on overlay
234
+ backdrop cancels.
235
+
236
+ Spec sec 13 will formalise the contract in v2.3; the v2.2 runtime
237
+ ships a working reference impl so adopters can wire it today.
238
+ Available on any field via:
239
+
240
+ ```js
241
+ NAC.edit_field('invoice.client_name');
242
+ // or by intermediary:
243
+ NAC.click_by_verb('myplugin', 'edit_field', { nac_id: 'invoice.client_name' });
244
+ ```
245
+
246
+ ### 5.1.4 Action payload + invoke (v2.3)
247
+
248
+ NAC v2.2 actions are click-and-go: an agent triggers `NAC.click(id)`
249
+ or `NAC.click_by_verb(plugin, verb)` and the host runs whatever it
250
+ does. This works for verb-and-state actions (`save`, `cancel`,
251
+ `submit`, `delete`) but collapses when an action needs **data**
252
+ from the agent -- `utter(text)`, `search(query)`,
253
+ `send_message(body)`, `upload(file)`, `schedule(date)`,
254
+ `translate(text, target_lang)`. The host has no way to receive
255
+ the agent's payload via a synthetic click.
256
+
257
+ v2.3 closes this gap. The contract is additive: click-style
258
+ verbs continue to work unchanged.
259
+
260
+ ```ts
261
+ NAC.invoke(action_id: string, payload: object, opts?: { timeout?: number })
262
+ : Promise<{ok: true, request_id: string, ack: object|null}>
263
+
264
+ NAC.utter(action_id: string,
265
+ opts: { text: string, lang?: string, voice?: string, metadata?: object })
266
+ : Promise<{ok: true, request_id: string, ack: object|null}>
267
+ ```
268
+
269
+ `NAC.invoke` dispatches a `nac:action:requested` `CustomEvent`
270
+ on the host element (bubbles to document) with:
271
+
272
+ ```ts
273
+ detail: {
274
+ action_id: string, // canonical nac_id of the host element
275
+ verb: string, // payload.verb || el's data-nac-action
276
+ payload: object, // arbitrary, action-specific
277
+ plugin: string|null,
278
+ request_id: string, // correlation token assigned by the runtime
279
+ ts: number, // Date.now()
280
+ }
281
+ ```
282
+
283
+ The host listens for `nac:action:requested`, processes the
284
+ payload, and emits `nac:action:succeeded` (or `nac:action:failed`)
285
+ with the same `request_id` in the detail. The runtime correlates
286
+ by `request_id` and resolves the agent's Promise.
287
+
288
+ Default timeout is **30 seconds** (vs 5 s for click). Override
289
+ with `opts.timeout`. On timeout, the Promise rejects with
290
+ `NacError('timeout', ...)`. As with click, a timeout means real
291
+ failure: callers MUST treat it as such unless they have side-
292
+ effect proof via another channel.
293
+
294
+ `NAC.utter(id, opts)` is the ergonomic shortcut for the most
295
+ common payload-bearing verb. It is equivalent to:
296
+
297
+ ```js
298
+ NAC.invoke(id, { verb: 'utter', text: opts.text, lang: opts.lang });
299
+ ```
300
+
301
+ #### Manifest declaration
302
+
303
+ A payload-bearing action declares its payload schema in the
304
+ manifest entry for traceability and tooling:
305
+
306
+ ```js
307
+ NAC.register({
308
+ plugin_slug: 'atlas_pro_ad',
309
+ version: '2.1.0',
310
+ nac_version: '2.3',
311
+ elements: [
312
+ { id: 'atlas_pro_ad.mic', role: 'action',
313
+ actions: [
314
+ { verb: 'listen' },
315
+ { verb: 'utter',
316
+ payload_schema: {
317
+ text: { type: 'string', required: true, max: 4000 },
318
+ lang: { type: 'string',
319
+ enum: ['en','es','pt','fr','it','de','ja','zh','hi','ar'] }
320
+ },
321
+ label_i18n: { es:'Decir', en:'Utter', /* ... 10 locales */ } }
322
+ ],
323
+ label_i18n: { /* ... */ } }
324
+ ]
325
+ });
326
+ ```
327
+
328
+ `payload_schema` is **informational as of v2.5**, and the
329
+ reference runtime does not read it at all: the field is accepted
330
+ in a manifest, carried in `NAC.manifest()`, and never validated
331
+ against. `NAC.STRICT_VALIDATION` -- whose default did flip to
332
+ `true` in 2.3.0 -- covers manifest/DOM role findings only;
333
+ it has never covered payloads. So an agent MUST NOT assume a
334
+ payload was checked because a schema was declared: today the only
335
+ validation that happens is the one the agent does before sending.
336
+
337
+ Schemas are intentionally simple (a JSON-Schema-shaped subset) so
338
+ that a runtime can validate without shipping a full JSON-Schema
339
+ validator, and that remains the design intent for enforcement.
340
+
341
+ An earlier revision of this section promised, for the 2.4
342
+ release, to formalise the schema grammar and make enforcement
343
+ the default. **That did not happen in 2.4 and has not happened
344
+ through 2.5.** The sentence is removed rather than re-dated: a
345
+ promise with a version number attached, left standing past that
346
+ version, reads to an agent as a capability it can expect. Formalising the
347
+ grammar and wiring enforcement is tracked as an open question in
348
+ section 13, where it is listed as open and undated.
349
+
350
+ #### Disabled-state semantics (v2.3 hotfix from alpha.2)
351
+
352
+ `NAC.invoke` does NOT reject when the target element has
353
+ `disabled` or `aria-disabled='true'` set. The `disabled` HTML
354
+ attribute is a UX click guard; `invoke` is a logical
355
+ payload-bearing request, not a synthetic click. Hosts that need
356
+ to refuse an invoke based on UI state MUST do it in their
357
+ `nac:action:requested` listener and emit `nac:action:failed`
358
+ with a meaningful error code.
359
+
360
+ `NAC.click`, by contrast, STILL rejects on disabled elements
361
+ (click semantics preserved). Test coverage:
362
+ `runtime/test/v23-invoke.mjs` T7/T8/T9.
363
+
364
+ #### Conformance: hosts that support invoke MUST
365
+
366
+ 1. Declare `actions[].payload_schema` in the manifest entry.
367
+ 2. Listen for `nac:action:requested` (or use a generic listener
368
+ that filters by `detail.action_id` + `detail.verb`).
369
+ 3. Emit `nac:action:succeeded` -- with `detail.request_id`
370
+ echoed back -- after processing, or `nac:action:failed`
371
+ (with `detail.error` code) on failure.
372
+ 4. NEVER emit a `:succeeded` event with a `request_id` they did
373
+ not receive (prevents cross-talk between concurrent invocations).
374
+
375
+ Hosts that do NOT support invoke continue to operate normally
376
+ under `NAC.click()` and `NAC.click_by_verb()`. Agents that call
377
+ `NAC.invoke()` against a host without an `actions[].payload_schema`
378
+ entry will still receive a `request_id` but the runtime cannot
379
+ guarantee delivery; the timeout fires after 30 s.
380
+
381
+ #### Why this matters
382
+
383
+ The full agentic surface stops being "list of buttons" and
384
+ becomes "list of buttons + structured inputs". A voice ad becomes
385
+ NAC.invoke-able. A search bar becomes NAC.invoke-able. A
386
+ file upload becomes NAC.invoke-able. Same protocol, same
387
+ provenance, same ack semantics.
388
+
389
+ The first reference adopter is **Atlas Pro** -- its
390
+ `atlas_pro_ad.mic` element declares both `listen` (click-only,
391
+ existing) and `utter` (payload-bearing) verbs. The same
392
+ `/parse` + `/tts` conversational loop drives in either case;
393
+ agents that have STT call `listen`, agents that have their own
394
+ language model call `utter`.
395
+
396
+ #### Forward modalities (anticipated, no spec change required)
397
+
398
+ `invoke` is intentionally modality-agnostic so future input
399
+ families plug in without breaking the contract:
400
+
401
+ | Modality | Verb (sketch) | Payload (sketch) |
402
+ |----------|-----------------------|--------------------------------------------------|
403
+ | Text | `utter` | `{text, lang?}` |
404
+ | Search | `search` | `{query, scope?, limit?}` |
405
+ | File | `upload` | `{filename, mime, data_url \| stream_id}` |
406
+ | Image | `analyze_image` | `{image_url \| data_url, prompt?}` |
407
+ | Video | `analyze_stream` | `{stream_url, frame_window_ms?, return?}` |
408
+ | Schedule | `schedule` | `{datetime, duration_min, attendees?}` |
409
+ | Code | `apply_diff` | `{file_path, unified_diff}` |
410
+ | Voice | `transcribe` | `{audio_url \| data_url, lang?}` |
411
+
412
+ Each modality follows the same `nac:action:requested` ->
413
+ `nac:action:succeeded` / `:failed` event protocol, the same
414
+ `request_id` correlation, the same timeout semantics. The
415
+ runtime stays small; the verb vocabulary grows by convention
416
+ between hosts and agents. Ergonomic shortcuts (`NAC.utter`,
417
+ `NAC.search`, `NAC.watch`, etc.) can be added later without
418
+ re-spec because each is a thin wrapper over `invoke`.
419
+
420
+ ### 5.1.5 Shadow DOM resolution -- open roots (v2.3)
421
+
422
+ The runtime resolves `data-nac-id` references through open
423
+ shadow roots recursively. A page can mount Web Components
424
+ using `attachShadow({mode:'open'})`, place
425
+ `data-nac-*` attributes on elements inside the shadow tree,
426
+ and any NAC3 caller (`NAC.click`, `NAC.fill`, `NAC.invoke`,
427
+ etc.) resolves the target transparently.
428
+
429
+ #### Resolution algorithm
430
+
431
+ For a selector `S` (typically `[data-nac-id="..."]`) against a
432
+ root `R` (typically `document`):
433
+
434
+ 1. `R.querySelector(S)` -> if non-null, return immediately.
435
+ 2. For every descendant `el` of `R`:
436
+ - If `el.shadowRoot` is non-null (i.e. open shadow root):
437
+ recurse with `R := el.shadowRoot`, depth +1.
438
+ - Else if `el.nac3` is an object exposing a `query` method,
439
+ delegate (see sec 5.1.6).
440
+ 3. The recursion is **depth-capped at 10 levels**. Targets
441
+ deeper than 10 are unreachable; the caller receives
442
+ `code='not_found'`. The cap exists to prevent pathological
443
+ walks; in practice no production codebase nests more than
444
+ 3-4 shadow levels.
445
+ 4. The walk is breadth-of-DOM-order: siblings before nested
446
+ shadows. First match wins.
447
+
448
+ #### Event propagation
449
+
450
+ Events emitted by hosts inside shadow roots MUST set
451
+ `composed: true` for document-level listeners to receive them.
452
+ The NAC3 runtime emits all its own events with `composed:true`
453
+ already; host code that emits manual `nac:*` events is
454
+ responsible for the same. Without `composed:true` the event
455
+ stops at the shadow boundary and the runtime's correlation
456
+ machinery never sees it.
457
+
458
+ #### Author responsibility
459
+
460
+ The component author needs to:
461
+
462
+ 1. Place `data-nac-id`, `data-nac-role`, `data-nac-action` on
463
+ operable elements inside the shadow root.
464
+ 2. Set `composed:true` on any custom event the host emits to
465
+ signal a NAC3 contract (`nac:action:succeeded`,
466
+ `nac:field:changed`, etc.).
467
+ 3. Avoid `<slot>` for elements that need to be
468
+ shadow-isolated -- slotted nodes live in light DOM and are
469
+ resolved there instead.
470
+
471
+ No manifest hint or runtime opt-in is required for open shadow
472
+ roots; the resolution is automatic.
473
+
474
+ #### Reference implementation
475
+
476
+ The reference runtime exposes two internal helpers,
477
+ `_deepQuery(selector, root)` and
478
+ `_deepQueryAll(selector, root)`, that perform the walk. Public
479
+ helpers `NAC.click`, `NAC.fill`, `NAC.invoke`,
480
+ `NAC.describe`, etc. all go through the deep variants.
481
+
482
+ #### Demos and tests
483
+
484
+ - `example-v23-shadow-open.php` -- 1-, 2-, and 3-level nested
485
+ open shadow demos.
486
+ - `runtime/test/v23-shadow.mjs` T1-T3, T10 -- unit
487
+ coverage including depth cap.
488
+
489
+ ### 5.1.6 Shadow DOM resolution -- closed roots, voluntary exposure (v2.3)
490
+
491
+ Closed shadow roots (`attachShadow({mode:'closed'})`) are
492
+ opaque from outside the component author's code -- a browser
493
+ security boundary, not a NAC3 decision. NAC3 cannot reach
494
+ inside unless the component author voluntarily exposes a
495
+ queriable surface via the contract below.
496
+
497
+ #### The `el.nac3` interface contract
498
+
499
+ A custom element MAY expose an interface object on its host
500
+ via a getter named `nac3`:
501
+
502
+ ```ts
503
+ interface NAC3HostInterface {
504
+ query(selector: string): Element | null; // MANDATORY
505
+ queryAll(selector: string): Element[]; // RECOMMENDED
506
+ describe?(): Array<{ // OPTIONAL
507
+ id: string;
508
+ role: string;
509
+ action?: string;
510
+ label?: string;
511
+ }>;
512
+ }
513
+ ```
514
+
515
+ Components opt in by implementing the getter. Components that
516
+ do NOT opt in remain inaccessible to NAC3 callers (their
517
+ internals stay private, as the browser intends).
518
+
519
+ #### Resolution semantics
520
+
521
+ During `_deepQuery(selector)`, for every visited element `el`
522
+ with `el.shadowRoot === null`:
523
+
524
+ 1. If `typeof el.nac3 === 'object'` and `el.nac3.query` is a
525
+ function, the runtime calls `el.nac3.query(selector)`:
526
+ - Return value is an Element -> resolved.
527
+ - Return value is `null` -> not a match in this shadow.
528
+ - Return value is anything else -> emit
529
+ `nac:shadow_protocol_violation` (once per host) and skip.
530
+ - Throws -> emit `nac:shadow_blocked` (reason
531
+ `'exposure_threw'`, once per host) and skip.
532
+ 2. Else if `el.hasAttribute('data-nac-shadow') === true` and
533
+ the attribute value is `'closed'` AND there is no `nac3`
534
+ interface present, the runtime emits `nac:shadow_blocked`
535
+ (reason `'not_exposed'`, once per host). Author opt-in to
536
+ the "I am a deliberately closed component" debug signal.
537
+ 3. Else: the element is treated as a normal light-DOM
538
+ element with no shadow root.
539
+
540
+ #### Error event detail shapes
541
+
542
+ `nac:shadow_blocked` detail:
543
+
544
+ ```ts
545
+ {
546
+ host: Element, // the closed-shadow host
547
+ reason: 'exposure_threw' | 'not_exposed',
548
+ ts: number // Date.now()
549
+ }
550
+ ```
551
+
552
+ `nac:shadow_protocol_violation` detail:
553
+
554
+ ```ts
555
+ {
556
+ host: Element,
557
+ message: string, // diagnostic message
558
+ value_snapshot: string, // truncated value preview
559
+ ts: number
560
+ }
561
+ ```
562
+
563
+ Both events bubble (`bubbles: true`) and cross shadow
564
+ boundaries (`composed: true`). Dedup is per-host via a
565
+ WeakSet kept by the runtime; the same host emits each event
566
+ **at most once per page load**.
567
+
568
+ #### Why voluntary
569
+
570
+ The browser enforces closed-shadow opacity. Even if NAC3
571
+ defined a non-voluntary mechanism, the browser would prevent
572
+ it. Voluntary exposure puts the component author in full
573
+ control of what their public surface looks like for agents.
574
+
575
+ The cost is per-component opt-in; the benefit is that
576
+ NAC3-compliant agents work against design systems with closed
577
+ shadow components (Salesforce Lightning, some GitHub Primer
578
+ components, security-sensitive widgets) without per-component
579
+ adapter code.
580
+
581
+ #### Demos and tests
582
+
583
+ - `example-v23-shadow-closed.php` -- positive
584
+ (`<todo-card-closed-exposed>`) and negative
585
+ (`<todo-card-closed-blind>`) side-by-side with verdict
586
+ panels + live event log.
587
+ - `runtime/test/v23-shadow.mjs` T4-T9 -- unit coverage
588
+ for every error event family plus dedup semantics.
589
+ - `guides/SHADOW_DOM_CLOSED.md` -- authoring guide.
590
+
591
+ ### 5.1.7 Auth-aware capabilities (v2.3)
592
+
593
+ NAC3 v2.3 lets the manifest declare per-action capability
594
+ requirements that gate `NAC.click` and `NAC.invoke` before
595
+ dispatch. The agent receives a fast rejection
596
+ (`code='capability_required'`) instead of a round-trip that
597
+ fails server-side.
598
+
599
+ #### Manifest declaration
600
+
601
+ A capability requirement attaches at the element level or at
602
+ the verb level. Verb-level wins if both are present.
603
+
604
+ ```js
605
+ NAC.register({
606
+ plugin_slug: 'fin',
607
+ version: '1.0.0',
608
+ nac_version: '2.3',
609
+ elements: [
610
+ // Element-level (covers all verbs on this id).
611
+ { id: 'fin.invoice.delete', role: 'action',
612
+ requires_capability: 'finance.delete_invoice',
613
+ actions: [{ verb: 'delete' }] },
614
+
615
+ // Verb-level (more granular).
616
+ { id: 'fin.invoice.edit', role: 'action',
617
+ actions: [
618
+ { verb: 'edit',
619
+ requires_capability: 'finance.edit_invoice' },
620
+ { verb: 'view',
621
+ /* no capability -> always allowed */ }
622
+ ] },
623
+
624
+ // Array value: OR semantics.
625
+ // ("at least one of these capabilities matches")
626
+ { id: 'fin.invoice.approve', role: 'action',
627
+ requires_capability: ['finance.approve',
628
+ 'finance.admin'],
629
+ actions: [{ verb: 'approve' }] }
630
+ ]
631
+ });
632
+ ```
633
+
634
+ For AND semantics ("user needs ALL of these caps"), declare
635
+ each via separate gated actions or compose at the host level
636
+ in the `nac:action:requested` listener.
637
+
638
+ #### Public API
639
+
640
+ ```ts
641
+ NAC.setCapabilities(caps: string | string[] | null): void
642
+ NAC.grantCapability(cap: string): void
643
+ NAC.revokeCapability(cap: string): void
644
+ NAC.userCapabilities(): string[]
645
+ ```
646
+
647
+ `setCapabilities` replaces the entire set (use for login /
648
+ session refresh). `grantCapability` / `revokeCapability` are
649
+ incremental. `userCapabilities` returns a snapshot array.
650
+ `setCapabilities(null)` clears the set.
651
+
652
+ Hosts call these whenever the user's role changes. The set
653
+ lives in the runtime; no manifest reload is required.
654
+
655
+ #### Gate semantics
656
+
657
+ Before dispatch, `NAC.click(id)` and `NAC.invoke(id, payload)`
658
+ look up the matching manifest entry (element + verb), read
659
+ `requires_capability`, and call `_hasCapability`:
660
+
661
+ - No requirement declared -> allow.
662
+ - Requirement declared, current set satisfies it -> allow.
663
+ - Requirement declared, current set does NOT satisfy -> reject
664
+ with `NacError('capability_required', ...)` AND emit
665
+ `nac:command:rejected` with `detail.reason='capability_required'`.
666
+
667
+ The gate runs AFTER `not_found` / `disabled` / `hidden` checks
668
+ on `click` so the most specific failure surfaces. On `invoke`,
669
+ the gate runs before the request event fires (the host never
670
+ sees an unauthorised attempt).
671
+
672
+ #### Why this matters
673
+
674
+ Without the gate, an agent calling `NAC.click('finance.delete')`
675
+ either succeeds (no auth gate at all -> security hole) or
676
+ fails server-side with a 403 several seconds later. With the
677
+ gate, the agent learns synchronously that it lacks the
678
+ capability and can react appropriately (request a different
679
+ flow, ask for elevation, surface the constraint to the user).
680
+
681
+ This complements -- it does not replace -- server-side
682
+ authorisation. Hosts MUST still enforce permissions on the
683
+ server. The client gate is a UX optimisation and an
684
+ intent-level signal, not a security boundary.
685
+
686
+ #### Demos and tests
687
+
688
+ - `runtime/test/v23-capabilities.mjs` -- 17 assertions
689
+ covering set/get, grant/revoke, click gate, invoke gate,
690
+ verb-level vs element-level resolution, OR semantics,
691
+ null-clear, invalid-input rejection, regression for
692
+ unguarded actions.
693
+
694
+ ### 5.1.2 Strict validation flag (v2.2; default-flipped in v2.3)
695
+
696
+ `NAC.STRICT_VALIDATION` (boolean). When `true`, `NAC.register()`
697
+ throws an `Error` with `code='strict_validation'` and a
698
+ `findings` array on any of:
699
+
700
+ - `manifest_role_unknown` -- entry's role outside the canonical set.
701
+ - `tab_id_manifest_role_drift` -- id matches `^tab\.` but role
702
+ is not `'tab'`.
703
+ - `manifest_dom_role_mismatch` -- mounted DOM element's
704
+ `data-nac-role` differs from manifest entry's role.
705
+
706
+ **Default value:**
707
+
708
+ - **v2.2.x:** `false` (warning-only). Adopters needed a migration
709
+ window.
710
+ - **v2.3.x:** **`true`** (throwing). The migration window closed
711
+ with the v2.2 line. Adopters with drift-laden manifests opt
712
+ out by setting `NAC.STRICT_VALIDATION = false` BEFORE any
713
+ `register()` call.
714
+ - **v3.0:** flag removed (strict is the only mode).
715
+
716
+ See `guides/MIGRATION_v2.2_to_v2.3.md` for the playbook to clean
717
+ up drift findings.
718
+
719
+ All async methods reject with `NacError` whose `code` is one of:
720
+
721
+ - `not_found` -- the named element/role/verb is not in the DOM.
722
+ - `invalid` -- argument shape is wrong.
723
+ - `disabled` -- element has `disabled` or `aria-disabled='true'`
724
+ (`NAC.click` only; `NAC.invoke` no longer checks per v2.3
725
+ hotfix, see sec 5.1.4).
726
+ - `hidden` -- element is offscreen / `aria-hidden='true'` /
727
+ zero-dimension.
728
+ - `capability_required` -- manifest declared
729
+ `requires_capability` and the current
730
+ `NAC.userCapabilities()` set does not satisfy it (v2.3, see
731
+ sec 5.1.7).
732
+ - `timeout` -- side effect dispatched but the conformance ack
733
+ event did not arrive within 5 seconds (30 seconds for
734
+ `invoke`). **A timeout means real failure**: the handler may
735
+ have hung, the ack was never wired, a network race occurred.
736
+ Callers MUST treat timeout as failure unless they have proof
737
+ of side effect via another channel.
738
+
739
+ ### 5.2 Introspection
740
+
741
+ ```ts
742
+ NAC.describe(): { active: string|null, plugins: PluginSnap[] }
743
+ NAC.describe_v2(): { v2_scope_entries: [...], sitemap: ..., data_tables: [...] }
744
+ NAC.manifest(plugin_slug: string): Manifest|null
745
+ NAC.validate_global(opts?: {probe?: boolean}): GlobalReport // named buckets, see 10.1
746
+ ```
747
+
748
+ ### 5.3 Data tables (since 2.1)
749
+
750
+ The data-table primitives are NOT part of the core runtime
751
+ (`js/nac.js` / `@nac3/runtime`'s `nac.mjs`). They ship in the
752
+ brownfield extensions module `js/nac-v2-extensions.js`
753
+ (published as `@nac3/runtime/extensions`), which attaches them
754
+ onto the same `window.NAC` object after it loads. Load the
755
+ extensions module after the core runtime to get the `dt_*`
756
+ surface:
757
+
758
+ ```html
759
+ <script src="https://yujin.app/nac-spec/js/nac.js"></script>
760
+ <script src="https://yujin.app/nac-spec/js/nac-v2-extensions.js"></script>
761
+ ```
762
+
763
+ ```js
764
+ // or with the npm package:
765
+ import '@nac3/runtime';
766
+ import '@nac3/runtime/extensions';
767
+ ```
768
+
769
+ The methods below are present only when the extensions module
770
+ is loaded; calling them on a core-only runtime is a no-op /
771
+ `undefined`.
772
+
773
+ ```ts
774
+ NAC.registerDataTable(spec: DataTableSpec): string // returns table_id
775
+ NAC.dt_add_row(table_id, values): {ok, row_id}
776
+ NAC.dt_remove_row(table_id, row_id): {ok}
777
+ NAC.dt_edit_cell(table_id, row_id, column, value): {ok} | {ok:false, error}
778
+ NAC.dt_set_cell(table_id, row, col, value): {ok} | {ok:false, error}
779
+ NAC.dt_select(table_id, target): {ok}
780
+ NAC.dt_commit(table_id): {ok, final_state} | {ok:false, errors:[...]}
781
+ NAC.dt_discard(table_id): {ok}
782
+ NAC.dt_state(table_id): TableState
783
+ NAC.dt_read_aggregate(table_id, agg_key, column): number|null
784
+ NAC.registerDataTableComputed(table_id, column, fn): void
785
+ ```
786
+
787
+ A data table has a `subkind`:
788
+
789
+ - `collection` -- ordered rows with optional transactional commit.
790
+ Used for invoice lines, cart items, log entries.
791
+ - `matrix` -- row x column grid where every cell carries a value.
792
+ Used for permission matrices, schedule grids.
793
+ - `matrix-singletree` -- matrix where each row collapses into a
794
+ tree (rare).
795
+
796
+ ---
797
+
798
+ ### 5.4 Strict resolution + disambiguation (v2.4)
799
+
800
+ NAC3 v2.4 makes id / verb / qualifier / label resolution
801
+ **strict**. The verbs that resolve a request to a single DOM
802
+ element -- `click_by_verb`, `tab` (single-arg form), and
803
+ `tab_by_label` -- no longer guess. When a request resolves to
804
+ zero candidates or to more than one, the runtime throws a
805
+ `NacError` carrying the candidate list AND emits a
806
+ `nac:disambiguation_requested` event, instead of silently
807
+ dispatching to the first near-match.
808
+
809
+ This is the **zero-silent-damage** invariant. It exists for
810
+ assistive-software and agent callers, where a silent dispatch to
811
+ the wrong element with no recovery path is a safety blocker. The
812
+ pre-2.4 lenient behaviour -- a substring `indexOf` fallback that
813
+ resolved to the first near-match -- is removed.
814
+
815
+ > Backward compatibility: v2.4 is a *behaviour-of-contract*
816
+ > change. Code paths that already supplied unambiguous arguments
817
+ > keep working unchanged. Code paths that depended on the lenient
818
+ > `indexOf` fallback to resolve to the first near-match will now
819
+ > throw -- by design.
820
+
821
+ #### 5.4.1 Strict qualifier matching (`click_by_verb`)
822
+
823
+ `click_by_verb(plugin, verb, opts?)` selects among DOM nodes that
824
+ share `data-nac-action="<verb>"`. When `opts.qualifier` (a string)
825
+ is supplied, an element matches **only** if its `data-nac-id`
826
+ satisfies:
827
+
828
+ ```js
829
+ id === qualifier || id.endsWith('__' + qualifier)
830
+ ```
831
+
832
+ That is: exact id equality, or an anchored suffix after a `__`
833
+ separator. There is **no substring fallback**. A qualifier that
834
+ is a mere substring of an id (not equal, not an anchored
835
+ `__suffix`) does NOT match.
836
+
837
+ - 0 matches -> throw `NacError('no_matching_instance', ...)`.
838
+ - exactly 1 match -> resolves and clicks.
839
+ - >1 matches -> throw `NacError('ambiguous_qualifier', ...)`.
840
+
841
+ `opts.qualifier_ordinal` (a number) selects positionally across
842
+ all DOM elements sharing the verb, bypassing qualifier matching.
843
+
844
+ #### 5.4.2 Strict id resolution (`tab`)
845
+
846
+ `tab(plugin, id)` single-arg form: an exact `data-nac-id` match
847
+ in the DOM wins. Otherwise the runtime looks for instances whose
848
+ id starts with `id + "__"`:
849
+
850
+ - 0 qualified instances and no exact id -> `no_matching_instance`.
851
+ - exactly 1 -> resolves.
852
+ - >1 -> `ambiguous_tab` (pass the full qualified id).
853
+
854
+ #### 5.4.3 Strict label resolution (`tab_by_label`)
855
+
856
+ `tab_by_label(plugin, label)` resolves a human label to a tab,
857
+ trying, in order: exact manifest-label match, fuzzy/substring
858
+ manifest match, exact DOM-text match, fuzzy DOM-text match. If
859
+ any tier yields more than one match it throws
860
+ `NacError('ambiguous_label', ...)`; if no tier matches it throws
861
+ `NacError('not_found', ...)`. The emitted event's `reason` field
862
+ records which tier was ambiguous (`ambiguous_label_exact`,
863
+ `ambiguous_label_fuzzy`, `ambiguous_label_exact_dom`,
864
+ `ambiguous_label_fuzzy_dom`, or `no_matching_label`).
865
+
866
+ #### 5.4.4 Error codes
867
+
868
+ | `err.code` | Thrown by | Meaning |
869
+ |------------|-----------|---------|
870
+ | `no_matching_instance` | `click_by_verb` (qualifier), `tab` | zero elements match the qualifier / id |
871
+ | `ambiguous_qualifier` | `click_by_verb` | >1 element matches the qualifier |
872
+ | `ambiguous_tab` | `tab` | >1 qualified `id__` instance matches |
873
+ | `ambiguous_label` | `tab_by_label` | >1 tab matches the label (any tier) |
874
+ | `not_found` | `tab_by_label` | no tab matches the label at all |
875
+
876
+ #### 5.4.5 The `err.candidates` shape
877
+
878
+ Every disambiguation error carries a `candidates` array. Each
879
+ candidate is exactly:
880
+
881
+ ```ts
882
+ { nac_id: string, label: string }
883
+ ```
884
+
885
+ `nac_id` is the element's `data-nac-id`. `label` is resolved by
886
+ preferring `aria-label`, then trimmed `textContent` (sliced to
887
+ 120 chars), then falling back to the `data-nac-id`. The list is
888
+ DOM-validated -- it names the real elements the caller can pick
889
+ from. `NacError` merges `candidates` onto the thrown `Error`, so
890
+ `err.code`, `err.message`, and `err.candidates` are all
891
+ populated.
892
+
893
+ #### 5.4.6 The `nac:disambiguation_requested` event
894
+
895
+ Whenever a strict-resolution call fails (no match OR too many
896
+ matches), the runtime dispatches a `nac:disambiguation_requested`
897
+ `CustomEvent` on `document` *in addition to* throwing. Emission
898
+ is best-effort: if dispatch fails the runtime still throws.
899
+
900
+ ```ts
901
+ document.addEventListener('nac:disambiguation_requested', (e) => {
902
+ e.detail; /* {
903
+ method: 'click_by_verb' | 'tab' | 'tab_by_label',
904
+ plugin: string | null,
905
+ query: { verb?, qualifier?, label?, id? },
906
+ reason: string, // finer-grained than err.code (see 5.4.3)
907
+ candidates: Array<{ nac_id: string, label: string }>,
908
+ } */
909
+ });
910
+ ```
911
+
912
+ #### 5.4.7 How a caller disambiguates
913
+
914
+ Given the candidate list (from `err.candidates` or
915
+ `event.detail.candidates`), the caller picks one and re-dispatches
916
+ by any of:
917
+
918
+ 1. **Full `nac_id`** -- `NAC.click(candidate.nac_id)`. This is the
919
+ canonical recovery path: the candidate already carries the
920
+ exact id.
921
+ 2. **Anchored `__suffix`** -- pass the instance's exact suffix as
922
+ the qualifier to `click_by_verb`.
923
+ 3. **`opts.qualifier_ordinal`** -- positional selection across the
924
+ elements sharing the verb (DOM order).
925
+
926
+ The worked reference is `example-v24-disambiguation.php`; the
927
+ contract is covered by `runtime/test/stage2-disambiguation.mjs`
928
+ and `runtime/test/stage7-strict-resolution.mjs`.
929
+
930
+ ---
931
+
932
+ ## 6. Events
933
+
934
+ Every action emits a deterministic completion event. The runtime's
935
+ `NAC.click()` polls for this event and resolves when it fires.
936
+
937
+ | Role | Success event | Failure event |
938
+ |------|---------------|---------------|
939
+ | `action` | `nac:action:succeeded` | `nac:action:failed` |
940
+ | `field` | `nac:field:changed` | -- |
941
+ | `option` | `nac:field:changed` | -- |
942
+ | `tab` | `nac:tab:activated` | -- |
943
+ | `breadcrumb-item` | `nac:breadcrumb:navigated` | -- |
944
+ | `accordion-toggle` | `nac:accordion:expanded` / `:collapsed` | -- |
945
+ | `step` | `nac:step:advanced` | -- |
946
+ | `pagination-item` | `nac:table:page_changed` | -- |
947
+ | `confirm-button` | `nac:confirm:resolved` / `:cancelled` | -- |
948
+ | `sort-control` | `nac:table:sort_changed` | -- |
949
+ | `filter-control` | `nac:table:filter_changed` | -- |
950
+
951
+ ### 6.1 Event detail shape
952
+
953
+ Every event detail carries the canonical id field plus `plugin`:
954
+
955
+ ```js
956
+ nac:action:succeeded {
957
+ detail: { plugin: 'invoice', action_id: 'invoice.save', ... }
958
+ }
959
+ nac:tab:activated {
960
+ detail: { plugin: 'invoice_edit_modal', tab_id: 'tab.lines', ... }
961
+ }
962
+ nac:field:changed {
963
+ detail: { plugin: 'invoice', field_id: 'field.client_name',
964
+ value: 'Acme Corp', ... }
965
+ }
966
+ ```
967
+
968
+ ### 6.2 Emitting from a host handler
969
+
970
+ A click handler MUST emit the corresponding success event after
971
+ its synchronous side effect:
972
+
973
+ ```js
974
+ button.addEventListener('click', function (ev) {
975
+ // ... do the work ...
976
+ document.dispatchEvent(new CustomEvent('nac:action:succeeded', {
977
+ detail: { plugin: 'invoice', action_id: 'invoice.save' }
978
+ }));
979
+ });
980
+ ```
981
+
982
+ If the work is asynchronous, emit after resolution. If the work
983
+ fails, emit `nac:action:failed` with `{detail: {plugin, action_id,
984
+ error: <message>}}`.
985
+
986
+ The v2.2 runtime will provide `NAC.bindAction(el, handler, ctx)`
987
+ that wraps `addEventListener` and emits automatically.
988
+
989
+ ### 6.3 Why not use the click event itself?
990
+
991
+ A DOM `click` event fires before the handler runs. NAC3's contract
992
+ needs to know when the **side effect completed**, not when the
993
+ click started. Hence the separate event family.
994
+
995
+ ---
996
+
997
+ ## 7. Provenance
998
+
999
+ ### 7.1 isTrusted
1000
+
1001
+ `event.isTrusted` is `true` for user-initiated clicks (real mouse,
1002
+ real keypress, screen reader activation) and `false` for
1003
+ synthesised clicks (`element.click()`, dispatchEvent of a built
1004
+ MouseEvent, automation).
1005
+
1006
+ NAC3 MUST surface this via `event.detail.is_trusted` in the
1007
+ success event. Hosts that take security-sensitive actions
1008
+ (payment, deletion) MAY require `is_trusted === true` and reject
1009
+ synthetic clicks. The reference demo `example-v20-full.php`
1010
+ includes a button pair (`v20_panel.istrusted_real` and
1011
+ `v20_panel.istrusted_fake`) that demonstrates the distinction.
1012
+
1013
+ ### 7.2 HMAC-signed manifests
1014
+
1015
+ A manifest MAY carry a `provenance` block:
1016
+
1017
+ ```js
1018
+ NAC.set_provenance_secret('your-tenant-secret');
1019
+ NAC.register({
1020
+ plugin_slug: 'invoice',
1021
+ ...,
1022
+ provenance: {
1023
+ signed_at: '2026-05-09T10:00:00Z',
1024
+ signed_by: 'tenant-X',
1025
+ signature: '<HMAC-SHA256 of manifest body>'
1026
+ }
1027
+ });
1028
+ ```
1029
+
1030
+ The runtime computes the expected HMAC over a stable
1031
+ serialisation of the manifest (excluding the signature itself)
1032
+ and rejects manifests whose signature does not match. Used by
1033
+ multi-tenant deployments to prevent a tenant from spoofing
1034
+ another tenant's manifest.
1035
+
1036
+ ### 7.3 Threat model
1037
+
1038
+ See `SECURITY.md` for the full threat model. Short version:
1039
+
1040
+ - NAC3 does not authenticate the **user**. That is your auth
1041
+ layer's job.
1042
+ - NAC3 authenticates the **manifest** (HMAC).
1043
+ - NAC3 distinguishes real clicks from synthesised clicks
1044
+ (isTrusted) so a host can refuse the latter for sensitive verbs.
1045
+ - NAC3 does not protect against a malicious agent running with
1046
+ user-level access. Such an agent can do anything the user can.
1047
+
1048
+ ---
1049
+
1050
+ ## 8. Conformance levels
1051
+
1052
+ A level is written **NAC3 Conformance Level 1**, **2** or **3**. The
1053
+ name of a level is not the name of the protocol: a validator, a report
1054
+ or a conformance claim MUST cite a level by the identifier
1055
+ `nac3-conformance-level-<1|2|3>` published in `api/latest/levels.json`,
1056
+ never by a display name. Section 8.1 records the names these levels
1057
+ carried before 2.5.0.
1058
+
1059
+ A page is at **NAC3 Conformance Level 1** if:
1060
+
1061
+ - Every clickable widget that an agent should be able to operate
1062
+ carries `data-nac-id` and `data-nac-role`.
1063
+ - Every `data-nac-role="action"` element fires
1064
+ `nac:action:succeeded` after its side effect.
1065
+ - The page registers at least one plugin manifest via
1066
+ `NAC.register()`.
1067
+ - `NAC.click(id)` works for every advertised id.
1068
+
1069
+ A page is at **NAC3 Conformance Level 2** if it also:
1070
+
1071
+ - Registers `tabs[]`, `fields[]`, `actions[]` arrays explicitly
1072
+ in its manifest (not inferred from DOM).
1073
+ - Provides `label_i18n` covering all 10 NAC3 locales for every
1074
+ user-facing label.
1075
+ - Implements the v2.0 brownfield primitives: scope tree,
1076
+ ephemeral capture, autoRegister.watch.
1077
+ - Passes `NAC.validate_global({probe: false})` with zero
1078
+ `error`-severity findings.
1079
+
1080
+ A page is at **NAC3 Conformance Level 3** if it also:
1081
+
1082
+ - Carries HMAC-signed manifests.
1083
+ - Distinguishes `isTrusted` for security-sensitive verbs.
1084
+ - Passes `NAC.validate_global({probe: true})` with zero
1085
+ findings.
1086
+
1087
+ The NPM package's CLI (`npx nac3 validate <url>`) reports
1088
+ the highest level a page reaches. (The package ships `nac3` and
1089
+ `nac` bins; both resolve to the same CLI.)
1090
+
1091
+ ### 8.1 Historical level names (v2.5)
1092
+
1093
+ Before 2.5.0 the three levels were written `NAC-1`, `NAC-2` and
1094
+ `NAC-3`. Those names are one dash away from the protocol name `NAC3`,
1095
+ so "this page is NAC-3 conformant" could not be told apart from "this
1096
+ page implements NAC3", and an agent asked to report a level had no
1097
+ unambiguous string to report.
1098
+
1099
+ The old names stay readable as historical aliases:
1100
+ `api/latest/levels.json` publishes each one as `legacy_display_name`
1101
+ beside the level it belonged to, so a document written before 2.5.0
1102
+ can still be mapped onto a level. They are NOT normative. New text,
1103
+ validator output and conformance claims use the level number or the
1104
+ published identifier.
1105
+
1106
+ ---
1107
+
1108
+ ## 9. Versioning
1109
+
1110
+ NAC3 follows semver:
1111
+
1112
+ - **Major** bump: breaking change to public API or wire formats.
1113
+ Adopters edit code.
1114
+ - **Minor** bump: new features, backward-compatible. Old code
1115
+ keeps working.
1116
+ - **Patch** bump: bug fixes, doc-only changes.
1117
+
1118
+ Deprecation policy: a feature marked `@deprecated` in version
1119
+ `X.Y.0` is removed no earlier than `(X+1).0.0`. The release notes
1120
+ document every removal explicitly.
1121
+
1122
+ The NPM package version mirrors the spec version:
1123
+ `@nac3/runtime@X.Y.Z` implements NAC3 vX.Y, with Z patch
1124
+ revisions on top of it. The example is written with placeholders
1125
+ on purpose -- a concrete version in this sentence goes stale the
1126
+ next release, and this document used to carry `2.1.3` long after
1127
+ the package had moved on.
1128
+
1129
+ ### 9.1 Prereleases and dist-tags
1130
+
1131
+ A version with a prerelease tail (`-alpha.N`, `-beta.N`,
1132
+ `-rc.N`) is **not** a release of this specification. It exists so
1133
+ a change can be exercised before it is promised.
1134
+
1135
+ - **`latest` only ever points at a stable version.** `npm install
1136
+ @nac3/runtime` without a tag MUST resolve to a version with no
1137
+ prerelease tail. An adopter who installs the default never gets
1138
+ a prerelease by accident.
1139
+ - **Prereleases are published under their own dist-tag** (`alpha`,
1140
+ `beta`, `rc`). Opting in is explicit: `npm install
1141
+ @nac3/runtime@alpha`.
1142
+ - **Nothing in a prerelease is a promise.** Any surface introduced
1143
+ in one may change or disappear before the stable release that
1144
+ carries it. The stability guarantees of section 10 and the
1145
+ finding-code guarantees of section 12 begin at the stable
1146
+ version.
1147
+ - **Prereleases are never unpublished** and never retagged into
1148
+ `latest` retroactively. The record of what was published stays
1149
+ readable.
1150
+
1151
+ The authoritative version of the reference runtime is the
1152
+ `NAC.version` constant in `js/nac.js`, and it is published as
1153
+ data: `api/latest.json` carries a separate `stable` and
1154
+ `prerelease` pointer (either may be `null`), and every published
1155
+ artefact carries its own `channel` field. A consumer that
1156
+ requires a stable contract reads one field and refuses, with no
1157
+ version string to parse and no tag to trust.
1158
+
1159
+ ---
1160
+
1161
+ ## 10. Validators
1162
+
1163
+ ### 10.1 Runtime: `NAC.validate_global()`
1164
+
1165
+ Walks the live DOM + the registered manifests and returns an
1166
+ **object of named buckets** -- one bucket per condition, each one an
1167
+ array of findings. Since 2.5.0 every finding of every bucket carries
1168
+ `code` and `severity`, so a CI integration can gate on a code
1169
+ without parsing a message:
1170
+
1171
+ ```ts
1172
+ {
1173
+ ok: boolean, // false when any error-severity finding exists
1174
+ has_errors: boolean,
1175
+ duplicates: [{ code: 'nac_id_duplicate_across_plugins',
1176
+ severity: 'error', nac_id, plugins: string[] }],
1177
+ orphans: [{ code: 'nac_id_orphan_in_dom',
1178
+ severity: 'warn', nac_id, in_dom, in_manifest,
1179
+ plugin_root }],
1180
+ unmounted: [{ code: 'nac_id_declared_not_mounted',
1181
+ severity: 'warn', nac_id, in_manifest, in_dom,
1182
+ plugin }],
1183
+ convention_violations:
1184
+ [{ code: 'nac_id_missing_plugin_prefix',
1185
+ severity: 'warn', nac_id, plugin, hint }],
1186
+ plugin_instance_violations:
1187
+ [{ code: 'duplicate_plugin_no_instance_id',
1188
+ severity: 'error', slug, instance_count, ... }],
1189
+ tolerated: [{ kind, nac_id, until, original }],
1190
+ plugin_count: number,
1191
+ total_ids: number,
1192
+ timestamp: number
1193
+ }
1194
+ ```
1195
+
1196
+ The five codes, their severity and what to do about each are
1197
+ published as data at `api/latest/findings.json`, under
1198
+ `global_buckets`. Finding codes are stable across patch releases;
1199
+ new codes only in minor bumps, and a code is never reused for a
1200
+ different condition (section 12, promise 4).
1201
+
1202
+ **Versions before 2.5.0 attached no code to these buckets**, and
1203
+ this section described a flat array of findings that the reference
1204
+ runtime never returned (audit N-14, N-34).
1205
+
1206
+ **Behaviour change in 2.5.0 (audit N-33).** Before 2.5.0 the
1207
+ collector behind this validator read only the legacy manifest
1208
+ groups (`actions`, `fields`, `tabs`, `kpis`, `charts`, keyed by
1209
+ `nac_id`) and never the canonical `elements: [{ id }]` shape of
1210
+ section 4. Against a manifest written the documented way it
1211
+ therefore reported `total_ids: 0`, listed every declared element as
1212
+ an orphan, could not report a duplicate, an unmounted id or a
1213
+ convention violation at all, and still answered `ok: true`. Both
1214
+ shapes are read from 2.5.0 on. A host that gated CI on `has_errors`
1215
+ may see its first failure after upgrading: that is a true positive
1216
+ that was always there, not a new rule.
1217
+
1218
+ ### 10.2 CLI: `npx nac3 validate <target>`
1219
+
1220
+ Wraps `validate_global` plus a static lint of HTML/manifest
1221
+ coherence. Exit codes:
1222
+
1223
+ - `0` -- no findings of severity >= configured threshold.
1224
+ - `1` -- findings.
1225
+ - `2` -- the target itself failed to load.
1226
+
1227
+ Useful in CI: `npx nac3 validate ./dist/index.html
1228
+ --severity=error`. The package exposes the CLI under two bin
1229
+ names, `nac3` and `nac`; use whichever does not collide with
1230
+ another tool on your PATH.
1231
+
1232
+ ---
1233
+
1234
+ ## 11. The system around NAC3
1235
+
1236
+ NAC3 is a contract layer. To turn a page that conforms to NAC3 into a
1237
+ voice-driven app, you also need:
1238
+
1239
+ 1. **A speech-to-text source** (browser SpeechRecognition,
1240
+ Whisper API, etc).
1241
+ 2. **An LLM intermediary** that takes user text + the page's
1242
+ `NAC.describe()` snapshot + an i18n hint and emits structured
1243
+ actions: `[{kind: 'click', nac_id: 'X'}, {kind: 'fill', nac_id:
1244
+ 'Y', value: 'Z'}]`. See `guides/LLM_WIRING.md`.
1245
+ 3. **A chat client** that holds the conversation and dispatches
1246
+ the actions. The reference is `js/nac-chat-client.js`.
1247
+ 4. **A text-to-speech sink** for spoken replies (browser
1248
+ SpeechSynthesis, ElevenLabs, etc).
1249
+
1250
+ NAC3 standardises only step 2's input/output shape (the
1251
+ `NAC.describe()` snapshot + the action shape). Steps 1, 3, 4 are
1252
+ outside the spec; you compose what you like.
1253
+
1254
+ ---
1255
+
1256
+ ## 12. Stability guarantees
1257
+
1258
+ What this spec promises:
1259
+
1260
+ 1. The set of canonical roles in section 1 will not shrink.
1261
+ New roles MAY be added in minor versions.
1262
+ 2. The event family in section 6 will not be renamed.
1263
+ New events MAY be added in minor versions.
1264
+ 3. The verbs of `NAC.click`, `NAC.fill`, etc. will not change
1265
+ shape in minor versions. New optional `opts` fields MAY appear.
1266
+ 4. The `validate_global` finding codes will not be reused for
1267
+ different conditions across minor versions. Since 2.5.0 every
1268
+ bucket of that validator carries a code, and all of them are
1269
+ published with their severity at `api/latest/findings.json`:
1270
+ compare two published versions and a reused code is visible
1271
+ without reading any source.
1272
+
1273
+ What this spec does NOT promise:
1274
+
1275
+ 1. Precise wording of error messages (those are i18n catalog
1276
+ strings; localisations may shift).
1277
+ 2. The DOM strategy for finding elements (`querySelector` today;
1278
+ may move to a faster index later).
1279
+ 3. The internal manifest cache layout. Treat manifests as
1280
+ write-only from the host side, read-only from the agent side.
1281
+
1282
+ ---
1283
+
1284
+ ## 13. Open questions
1285
+
1286
+ These are tracked **here**, in this section. An earlier revision
1287
+ titled this "Open questions (tracked separately)" and never said
1288
+ where "separately" was; there was no other register. A question
1289
+ that reaches a decision moves out of the table below and into the
1290
+ section it affects. A question that becomes a concrete proposal
1291
+ gets an RFC, and those are indexed at
1292
+ [`rfcs/README.md`](rfcs/README.md), with the process in
1293
+ [`CONTRIBUTING.md`](CONTRIBUTING.md).
1294
+
1295
+ Every row carries the version where it was last assessed, so a
1296
+ reader can tell a live question from an abandoned one. **No row
1297
+ carries a target version**: a dated promise that passes its date
1298
+ is worse than an undated one, which is the mistake section 5 used
1299
+ to make about `payload_schema`.
1300
+
1301
+ | Question | State | Last assessed | Where it stands |
1302
+ |----------|-------|---------------|-----------------|
1303
+ | Should `data-nac-role="navigation"` ever resolve to a tab? | **DECIDED: no** | v2.5 | Decided in 2.2.0 and enforced since: a `tab.`-prefixed id with role `navigation` raises `tab_id_manifest_role_drift`, and with `STRICT_VALIDATION` (default `true` since 2.3.0) `NAC.register` throws. `tab_by_label` resolves tabs only from `m.tabs[]` and `elements[role=='tab']`. `navigation` is a landmark region, never a switchable panel. See sections 1 and 10. |
1304
+ | Should `NAC.click()` accept relative ids (e.g. `'./save'`)? | **OPEN, not implemented** | v2.5 | The resolver matches `data-nac-id` exactly and scopes by plugin -- the active one, or `opts.plugin`. That scoping already covers the case the question was asking for (`NAC.click('save', {plugin:'invoice'})`), so the pressure for a relative syntax is low and nothing is in progress. Deciding it would mean adding a path grammar to section 2, where ids are declared opaque to the runtime. |
1305
+ | Should manifests support inheritance / extension across plugins (one base manifest extended by a tenant)? | **OPEN, candidate for the next major** | v2.5 | Not implemented. **Not to be confused with section 15**, "plugin extension contract": that shipped in v2.5 and is a backend-routing mechanism (`registerPlugin` / `call` / `read` / `subscribe`), not manifest inheritance. The question here is about one manifest deriving from another, which touches the id-uniqueness rules of section 2 and is why it is held for a major. |
1306
+ | Should `payload_schema` enforcement be formalised and turned on? | **OPEN, undated** | v2.5 | Moved here from section 5, which promised it for v2.4. It did not land in v2.4 and has not landed through v2.5; the reference runtime does not read the field. See section 5 for exactly what is and is not validated today. |
1307
+ | Should `validate_global()` findings carry a code from the published catalogue? | **DECIDED: yes, shipped in 2.5.0** | v2.5 | Every item of every bucket carries `code` + `severity`, so section 12 promise 4 now covers a real set instead of an empty one. The five codes are published under `global_buckets` in `api/latest/findings.json`, and the generator READS them off a fixture that provokes each bucket rather than writing them by hand -- the previous version wrote `code: null` for a bucket that had carried a code since 2.5.0 and published both claims in the same file. Building that fixture is also what found audit N-33: the validator could not see a manifest written in the canonical shape. See 10.1. |
1308
+
1309
+ ---
1310
+
1311
+ ## 13.5 Governance
1312
+
1313
+ NAC3 is currently stewarded by Yujin. The spec, the docs, and
1314
+ the reference runtime are all published under Apache-2.0. (The
1315
+ runtime was tagged MIT in the pre-2.5 dual-repo era; it was
1316
+ harmonised to Apache-2.0 across every NAC3 artefact in the
1317
+ 2026-05-23 consolidation. See `LICENSE` and `runtime/LICENSE`.)
1318
+ Yujin commits to moving NAC3 to a neutral foundation (W3C
1319
+ community group, Linux Foundation, or equivalent industry body)
1320
+ if and when adoption justifies neutral governance. Until then,
1321
+ spec changes follow the RFC process documented in
1322
+ `CONTRIBUTING.md`, with public comment period of at least 14
1323
+ days for any change that affects the public API or wire
1324
+ formats.
1325
+
1326
+ Adopters: the uniform Apache-2.0 licensing guarantees that the
1327
+ spec and runtime survive any change in Yujin's corporate status.
1328
+ You can fork either, run either, and ship either, today and
1329
+ after we are gone. This document records the commitment so the
1330
+ path to that survival is explicit, not implicit.
1331
+
1332
+ ---
1333
+
1334
+ ## 14. Reference implementation
1335
+
1336
+ The canonical implementation is the reference runtime distributed
1337
+ as the NPM package `@nac3/runtime`. The normative version source
1338
+ is the runtime's own `NAC.version` constant, published as data at
1339
+ `api/latest.json` (see section 9.1). This section deliberately
1340
+ does not restate a version number: it carried `2.5.0-alpha.5`
1341
+ while the package had already moved, which is the same class of
1342
+ defect as the stale examples removed from sections 5 and 9. It
1343
+ ships:
1344
+
1345
+ - `js/nac.js` -- the core runtime: the public imperative +
1346
+ introspection API of section 5 (click/fill/select/tab,
1347
+ click_by_verb/tab_by_label, invoke/utter, edit_field,
1348
+ setCapabilities, syncPlugin, request_authority/confirm_action,
1349
+ registerPlugin/call/read/subscribe, narrate/context/tree,
1350
+ expect/diff, describe, validate_global, ...). Published as the
1351
+ package's `main`/`module`/`browser` entry (`dist/nac.mjs`).
1352
+ - `js/nac-v2-extensions.js` -- the brownfield + data-table
1353
+ primitives that attach onto the same `window.NAC` after the
1354
+ core loads: scope tree, autoRegister, capture ephemeral, HMAC,
1355
+ isTrusted attestation, i18n catalog (`t`/`locale`), and the
1356
+ entire `registerDataTable` / `dt_*` data-table family
1357
+ (section 5.3). Published as `@nac3/runtime/extensions`
1358
+ (`dist/nac-v2-extensions.mjs`). The core runtime does NOT carry
1359
+ the `dt_*` surface; load this module to get it.
1360
+ - `js/nac-chat-client.js` -- a reference chat client that wires
1361
+ voice + LLM + dispatcher. Published as `@nac3/runtime/chat-client`.
1362
+
1363
+ The package also exposes a CLI under the bin names `nac3` and
1364
+ `nac` (`dist/cli.js`, section 10.2).
1365
+
1366
+ Other implementations are welcome (Python for native automation
1367
+ runners, Rust for embedded agents, etc). The spec, not the JS
1368
+ code, is the authority.
1369
+
1370
+ ---
1371
+
1372
+ ## 15. Plugin extension contract -- canvas + API surfaces (v2.5)
1373
+
1374
+ Sections 1-14 assume the agent-relevant surface is **DOM**. Every
1375
+ addressable element has a `data-nac-id` attribute, every verb fires
1376
+ through `el.click()`, every state read comes from
1377
+ `el.getAttribute(...)`. This works for apps whose chrome AND
1378
+ content live in DOM nodes.
1379
+
1380
+ It does not work for apps where part of the surface is **canvas**
1381
+ (LibreOffice / Collabora Online, Figma, Excalidraw, Miro, every
1382
+ custom WebGL editor). The chrome may still be DOM (toolbars,
1383
+ dialogs), but commands often need to flow through the app's own
1384
+ public API (postMessage, plugin SDK, script bridge), and state may
1385
+ not be readable from the DOM at all.
1386
+
1387
+ v2.5 adds a small set of primitives that let a NAC3 plugin declare
1388
+ its own routing contract to such surfaces. The runtime stays
1389
+ agnostic of any specific app -- it learns how to talk to one only
1390
+ by reading the plugin's manifest.
1391
+
1392
+ ### 15.1 Why a new primitive set
1393
+
1394
+ DOM-only `NAC.click(id)` cannot:
1395
+
1396
+ - Send a `Send_UNO_Command` postMessage to a sandboxed Collabora
1397
+ iframe.
1398
+ - Call `figma.currentPage.selection = [...]` inside the Figma
1399
+ plugin sandbox.
1400
+ - Invoke `excalidrawAPI.setElements(...)` on a React ref.
1401
+ - Read whether Bold is active on the current Collabora selection
1402
+ (the toolbar reflects it; the canvas hides it).
1403
+
1404
+ The fix is **not** to extend `NAC.click` with backend-detection
1405
+ heuristics. The fix is to add an explicit, agnostic verb that
1406
+ takes a plugin slug and a verb path, and lets the plugin's
1407
+ manifest declare how that verb is routed.
1408
+
1409
+ ### 15.2 The three primitives
1410
+
1411
+ ```ts
1412
+ NAC.registerPlugin(slug: string, manifest: PluginManifest): void
1413
+ NAC.call(plugin: string, verb_path: string, args?: object): Promise<any>
1414
+ NAC.read(plugin: string, state_path: string): Promise<any>
1415
+ NAC.subscribe(plugin: string, event_path: string,
1416
+ cb: (data: any) => void): SubscriptionHandle
1417
+ NAC.unsubscribe(handle: SubscriptionHandle): void
1418
+ ```
1419
+
1420
+ - `registerPlugin(slug, manifest)` registers a v2.5 plugin. A given
1421
+ `slug` MAY appear in both the DOM manifest registry (section 5)
1422
+ and the v2.5 extension registry; the two coexist. v2.5 calls
1423
+ resolve only through the v2.5 registry.
1424
+ - `call` invokes a declared verb. Routing is chosen by the
1425
+ manifest, not by the agent. Resolves with whatever the backend
1426
+ returned (often `undefined` / `{ok: true}`); rejects with
1427
+ `NacError` if the verb is unknown, the backend fails, or the
1428
+ response shape is invalid.
1429
+ - `read` returns a declared state value. The runtime walks the
1430
+ state's fallback chain in declared order and returns the first
1431
+ source that resolves; rejects only when every source in the
1432
+ chain failed.
1433
+ - `subscribe` attaches a listener to a declared event. Returns a
1434
+ handle that the caller passes to `unsubscribe` to clean up.
1435
+ Events MAY be backed by a real upstream event source or
1436
+ synthesised via polling / MutationObserver -- the manifest
1437
+ declares which.
1438
+
1439
+ All four functions are async (Promise-returning) except
1440
+ `unsubscribe`, which is synchronous and idempotent.
1441
+
1442
+ ### 15.3 Plugin manifest shape
1443
+
1444
+ ```ts
1445
+ interface PluginManifest {
1446
+ slug: string;
1447
+ verbs: { [verb_path: string]: VerbBinding };
1448
+ state: { [state_path: string]: StateBinding[] };
1449
+ events: { [event_path: string]: EventBinding };
1450
+ }
1451
+
1452
+ interface VerbBinding {
1453
+ backend: BackendKind;
1454
+ /* backend-specific fields (see 15.4) */
1455
+ [k: string]: any;
1456
+ }
1457
+
1458
+ interface StateBinding {
1459
+ backend: BackendKind;
1460
+ /* backend-specific fields (see 15.4) */
1461
+ extract?: string; /* extractor DSL string (see 15.5) */
1462
+ [k: string]: any;
1463
+ }
1464
+
1465
+ interface EventBinding {
1466
+ backend: BackendKind;
1467
+ /* backend-specific fields */
1468
+ [k: string]: any;
1469
+ }
1470
+
1471
+ type BackendKind =
1472
+ | 'postmessage'
1473
+ | 'postmessage-listen'
1474
+ | 'sdk-call'
1475
+ | 'script-bridge'
1476
+ | 'dom-mirror'
1477
+ | 'same-origin-window'
1478
+ | 'synthetic-mutation'
1479
+ | 'synthetic-poll';
1480
+ ```
1481
+
1482
+ Manifests are pure JSON (no JS callbacks). Forge, Sumi, and any
1483
+ future tooling generates them as data; the runtime interprets the
1484
+ backend names from a fixed vocabulary.
1485
+
1486
+ Verbs and events have **exactly one** binding. State has an
1487
+ **ordered array** of bindings: the runtime walks the chain in
1488
+ order, returning the first source that successfully resolved.
1489
+
1490
+ ### 15.4 Backend vocabulary
1491
+
1492
+ | Kind | Used for | Required fields |
1493
+ |------|----------|-----------------|
1494
+ | `postmessage` | Verb: post a message to an iframe via `postMessage`. | `target` (CSS selector of the iframe to send to), `message` (MessageId string), `values` (object literal interpolated with args), `values_from_args` (optional array of arg keys to forward verbatim) |
1495
+ | `postmessage-listen` | Event: listen for a specific incoming `MessageId` on `window.message`. | `source` (CSS selector of the iframe to filter origin by; if omitted, accept any source), `message` (MessageId to match), `extract` (extractor DSL into the message data) |
1496
+ | `sdk-call` | Verb: call a globally-exposed JS function (e.g. Figma plugin, Excalidraw API). | `path` (dotted path into `window`, e.g. `figma.currentPage.selection`), `mode` (`assign` to set the path to the args value, `invoke` to call it as a function with the args object) |
1497
+ | `script-bridge` | Verb or state: invoke an app's scripting bridge (Collabora's `CallPythonScript`, LibreOffice UNO bridge, Google Apps Script). | `bridge` (a backend-specific identifier like `collabora.python`), `script` (script identifier), `function` (function name to run), `args` (object literal interpolated with the call args), `response_match` (for state: the response MessageId to wait on), `timeout_ms` (optional, default 5000) |
1498
+ | `dom-mirror` | State: read from a DOM element whose attribute / class / text mirrors a canvas-internal state (e.g. a toolbar button highlighted when its formatting is active on the current selection). | `selector` (CSS selector to query), `extract` (extractor DSL, see 15.5) |
1499
+ | `same-origin-window` | State: read from `iframe.contentWindow.<path>` when the iframe is same-origin. The runtime detects cross-origin and falls through. | `target` (CSS selector of the iframe), `path` (dotted path into `contentWindow`) |
1500
+ | `synthetic-mutation` | Event: synthesise an event by observing DOM mutations on one or more state sources and re-emitting when the observed value changes. | `observe` (array of state paths to watch; the runtime calls `read` on each and diffs across mutations), `throttle_ms` (optional, default 100) |
1501
+ | `synthetic-poll` | Event: synthesise an event by polling state sources. | `observe` (array of state paths), `interval_ms` (default 250) |
1502
+
1503
+ Each backend MUST be implemented by the runtime as a self-contained
1504
+ dispatcher (`dispatch(binding, args, context) -> Promise<value>`).
1505
+ Adding a new backend type to the spec requires bumping the spec
1506
+ version; runtimes ignoring unknown backends MUST reject manifests
1507
+ that declare them (no silent skip).
1508
+
1509
+ ### 15.5 Extractor mini-DSL
1510
+
1511
+ State backends and the `postmessage-listen` event backend often
1512
+ need to pluck a field out of a larger object. The runtime ships
1513
+ a tiny declarative DSL so manifests stay JSON-only:
1514
+
1515
+ | Syntax | Meaning | Example input -> output |
1516
+ |--------|---------|-------------------------|
1517
+ | `field.path.to.value` | Dotted path traversal. | `{a:{b:1}}` with `a.b` -> `1` |
1518
+ | `attribute:NAME` | DOM only: read `el.getAttribute(NAME)`. | `<i data-x="hi">` with `attribute:data-x` -> `'hi'` |
1519
+ | `text` | DOM only: read `el.textContent`. | `<span>hi</span>` with `text` -> `'hi'` |
1520
+ | `classList.contains:CLASS` | DOM only: `el.classList.contains(CLASS)` -> boolean. | `<button class="active">` with `classList.contains:active` -> `true` |
1521
+ | `value` | DOM only: read `el.value`. | `<input value="x">` with `value` -> `'x'` |
1522
+ | `present` | DOM only: returns `true` if the selector resolved an element, `false` otherwise. | selector matched -> `true` |
1523
+
1524
+ Composition is not supported in v2.5; an extractor is exactly one
1525
+ of the rows above. A manifest needing complex transformation
1526
+ declares a `script-bridge` instead.
1527
+
1528
+ ### 15.6 Fallback chain semantics for `state`
1529
+
1530
+ `state[path]` is an array of bindings. `NAC.read(plugin, path)` walks
1531
+ the array in order. For each binding:
1532
+
1533
+ 1. The runtime invokes the backend's dispatcher.
1534
+ 2. If the dispatcher resolves with a value (including `false`, `0`,
1535
+ empty string, but NOT `undefined`), `read` returns that value.
1536
+ 3. If the dispatcher rejects, or resolves with `undefined`, the
1537
+ runtime advances to the next binding in the array.
1538
+ 4. If no binding produced a value, `read` rejects with
1539
+ `NacError('state_unreadable', ...)` whose `err.attempts: [...]`
1540
+ carries one entry per attempted backend with `{backend, reason}`.
1541
+
1542
+ Rationale: the chain encodes the manifest author's preference
1543
+ order. The fastest, cheapest, freshest source is declared first;
1544
+ fallbacks degrade gracefully. The runtime never silently picks an
1545
+ inferior source first.
1546
+
1547
+ ### 15.7 Provenance for synthetic actions
1548
+
1549
+ Every `NAC.call` dispatch emits a `nac:plugin:invoked` event on
1550
+ `document` after the backend returns. The detail payload:
1551
+
1552
+ ```js
1553
+ {
1554
+ plugin: 'collabora.writer',
1555
+ verb_path: 'uno.Bold',
1556
+ backend: 'postmessage',
1557
+ request_id: 'pi_<random hex>',
1558
+ source: 'agent', // see sec 7
1559
+ trusted: false,
1560
+ duration_ms: 12,
1561
+ ok: true,
1562
+ error: null,
1563
+ }
1564
+ ```
1565
+
1566
+ Same shape for `nac:plugin:read` (after a `read`) and
1567
+ `nac:plugin:event` (synthesised event re-emit). `source` defaults
1568
+ to `'agent'`; hosts that wrap the runtime in a user-facing UI MAY
1569
+ override via the existing `NAC.set_source(...)` mechanism (sec 7).
1570
+
1571
+ ### 15.8 Worked example -- Collabora Writer
1572
+
1573
+ ```json
1574
+ {
1575
+ "slug": "collabora.writer",
1576
+ "verbs": {
1577
+ "uno.Bold": {
1578
+ "backend": "postmessage",
1579
+ "target": "iframe[data-collabora-frame]",
1580
+ "message": "Send_UNO_Command",
1581
+ "values": { "Command": ".uno:Bold" }
1582
+ },
1583
+ "doc.save": {
1584
+ "backend": "postmessage",
1585
+ "target": "iframe[data-collabora-frame]",
1586
+ "message": "Action_Save",
1587
+ "values_from_args": ["DontTerminateEdit", "Notify"]
1588
+ }
1589
+ },
1590
+ "state": {
1591
+ "selection.isBold": [
1592
+ { "backend": "dom-mirror",
1593
+ "selector": "[data-nac-id='toolbar.bold']",
1594
+ "extract": "classList.contains:selected" },
1595
+ { "backend": "script-bridge",
1596
+ "bridge": "collabora.python",
1597
+ "script": "yujin_state.py",
1598
+ "function": "GetSelectionState",
1599
+ "response_match": "CallPythonScript-Result",
1600
+ "extract": "Values.is_bold" }
1601
+ ],
1602
+ "doc.modified": [
1603
+ { "backend": "same-origin-window",
1604
+ "target": "iframe[data-collabora-frame]",
1605
+ "path": "app.file.modified" }
1606
+ ]
1607
+ },
1608
+ "events": {
1609
+ "doc.modified": {
1610
+ "backend": "postmessage-listen",
1611
+ "source": "iframe[data-collabora-frame]",
1612
+ "message": "Doc_ModifiedStatus",
1613
+ "extract": "Values.Modified"
1614
+ },
1615
+ "selection.changed": {
1616
+ "backend": "synthetic-mutation",
1617
+ "observe": ["selection.isBold", "selection.isItalic"],
1618
+ "throttle_ms": 100
1619
+ }
1620
+ }
1621
+ }
1622
+ ```
1623
+
1624
+ The agent calls `NAC.call('collabora.writer', 'uno.Bold')`; the
1625
+ runtime routes through the `postmessage` backend, posts
1626
+ `Send_UNO_Command` to the iframe. To confirm the effect occurred
1627
+ (see sec 17), the agent calls
1628
+ `await NAC.read('collabora.writer', 'selection.isBold')`; the
1629
+ runtime tries the toolbar mirror first (fast, free), falls back to
1630
+ the Python script bridge if the mirror is unavailable. The agent
1631
+ never knows or cares which source answered.
1632
+
1633
+ ### 15.9 Errors
1634
+
1635
+ `NAC.call` / `read` / `subscribe` reject with `NacError` whose `code`
1636
+ is one of:
1637
+
1638
+ - `plugin_not_registered` -- the slug has no v2.5 manifest.
1639
+ - `verb_not_declared` -- the verb path is not in the manifest.
1640
+ - `state_not_declared` -- the state path is not in the manifest.
1641
+ - `event_not_declared` -- the event path is not in the manifest.
1642
+ - `backend_unknown` -- the manifest declares a backend the runtime
1643
+ does not implement. Manifest MUST be rejected at register time;
1644
+ this error only surfaces if a runtime accepts a future manifest
1645
+ format it then cannot dispatch.
1646
+ - `backend_target_missing` -- the backend's target (iframe, JS
1647
+ path, DOM selector) is not findable.
1648
+ - `cross_origin_blocked` -- `same-origin-window` was attempted
1649
+ against a cross-origin iframe.
1650
+ - `state_unreadable` -- every binding in a state chain failed; see
1651
+ 15.6.
1652
+ - `timeout` -- a backend did not respond within its declared
1653
+ `timeout_ms` (default 5000 for verbs, 1000 for state reads).
1654
+ - `invalid` -- argument shape is wrong (bad slug, malformed
1655
+ manifest at register time, etc).
1656
+
1657
+ ---
1658
+
1659
+ ## 16. Tree navigation (v2.5 -- SHIPPED in 2.5.0-alpha.5 / RFC V25-02)
1660
+
1661
+ Hierarchical command navigation primitives for assistive flows and
1662
+ voice runners that need to describe what they can do from the
1663
+ current focus.
1664
+
1665
+ **API surface:**
1666
+
1667
+ - `NAC.context(plugin) -> { breadcrumb: [{nac_id, label}, ...] }`
1668
+ Walks up from `document.activeElement` through ancestor elements
1669
+ carrying `data-nac-id`, stopping at the plugin root. Returns an
1670
+ empty breadcrumb if nothing is focused inside the plugin. Each
1671
+ crumb's `label` comes from `narrate` (sec 17).
1672
+
1673
+ - `NAC.tree(plugin, rootId?) -> [{nac_id, label, opens?, leaf?}, ...]`
1674
+ Enumerates the IMMEDIATE addressable children of `rootId` (or the
1675
+ plugin root if omitted). "Immediate" means no other `data-nac-id`
1676
+ element lies between the start and the child. For each entry:
1677
+ - `label` resolved via `narrate`
1678
+ - `opens` mirrors the `data-nac-opens` attribute when present
1679
+ - `leaf` is `true` when `data-nac-leaf` is present
1680
+
1681
+ **Authoring attributes:**
1682
+
1683
+ - `data-nac-opens="<target-nac-id>"`: declares this node opens /
1684
+ drills into the element identified by the target id. Lets agents
1685
+ follow the navigation chain without guessing names.
1686
+ - `data-nac-leaf`: explicit terminal marker; downstream agents know
1687
+ no further drill is possible.
1688
+
1689
+ **Errors:** `tree` returns `[]` for an unknown rootId (silent
1690
+ empty, not an error). `context` always returns
1691
+ `{ breadcrumb: [] }` for unknown plugins.
1692
+
1693
+ ---
1694
+
1695
+ ## 17. Assistive labels (v2.5 -- SHIPPED in 2.5.0-alpha.5 / RFC V25-03)
1696
+
1697
+ Canonical human-readable label resolution. One function for screen
1698
+ readers, TTS, voice flows, audit logs, mobile assistive surfaces.
1699
+
1700
+ **API surface:**
1701
+
1702
+ - `NAC.narrate(plugin, nac_id) -> string | null`
1703
+ Returns `null` if the plugin or nac_id cannot be found. Otherwise
1704
+ the label following this strict priority order:
1705
+
1706
+ 1. **`aria-label`** -- a11y-first; respected unless whitespace-only.
1707
+ 2. **visible text** -- `textContent` of the element excluding any
1708
+ nested `data-nac-id` subtrees (those have their own narrate
1709
+ resolution; they get excluded so spoken output stays scoped).
1710
+ 3. **`data-nac-label`** -- explicit author override; useful when
1711
+ visible text contains icon glyphs or i18n keys.
1712
+ 4. **`nac_id` fallback** -- worst case; signals "no label authored".
1713
+
1714
+ Whitespace-only values at any tier collapse to the next tier.
1715
+
1716
+ **Validation:** `validate_global()` may emit warnings in the
1717
+ `plugin_instance_violations` bucket for ordinal-shaped nac_ids
1718
+ (`btn-1`, `btn-2`, ...) lacking any of the upper-tier labels.
1719
+
1720
+ ---
1721
+
1722
+ ## 18. Effect detection (v2.5 -- SHIPPED in 2.5.0-alpha.5 / RFC V25-04)
1723
+
1724
+ Closes the "silent damage" gap: an agent confirms the EFFECT of
1725
+ an action, not just that the command was emitted. Both primitives
1726
+ compose with `NAC.read()` so any V25-01 backend works (postmessage,
1727
+ sdk-call, dom-mirror, ...).
1728
+
1729
+ **API surface:**
1730
+
1731
+ - `NAC.expect(plugin, statePath, value, opts?) -> Promise<value>`
1732
+ Polls `NAC.read(plugin, statePath)` until the comparator returns
1733
+ truthy or the deadline fires. Resolves with the resolved value;
1734
+ rejects with `NacError('timeout', ...)` on deadline.
1735
+
1736
+ Read failures during polling are retried until the deadline
1737
+ (treated as "not yet observable", not as a hard error).
1738
+
1739
+ Options:
1740
+ - `timeout_ms` (default `5000`)
1741
+ - `poll_ms` (default `100`)
1742
+ - `comparator` (default `(cur, want) => cur === want`)
1743
+ Receives `(current, expected)`, returns boolean.
1744
+
1745
+ - `NAC.diff(plugin, statePath, actionFn) -> Promise<{before, after, changed}>`
1746
+ Reads state, awaits `actionFn()`, reads state again. Returns
1747
+ both snapshots and a `changed` boolean computed via JSON-stringify
1748
+ compare (so `undefined`-vs-value still flags as changed).
1749
+ Read failures collapse to `undefined`.
1750
+
1751
+ **Composition notes:** `diff` only captures the START and END
1752
+ snapshot; it does NOT observe intermediate states inside the
1753
+ action. Use `expect` if your concern is "the state passes through
1754
+ some specific value at some point".
1755
+
1756
+ ---
1757
+
1758
+ *This document is the canonical NAC3 v2.5 specification.
1759
+ Sections 0-14 are unchanged from v2.4 stable. Sections 15-18 ship
1760
+ in v2.5. Edits to this file constitute spec changes and require an
1761
+ RFC; see `CONTRIBUTING.md`.*