@nac3/runtime 2.5.0-alpha.5 → 2.5.1

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