@popovych.co/witness 0.26.2 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -255,7 +255,7 @@ an older file keeps working: witness reads it as `migrate` would, changes nothin
255
255
  There is no `provider:` key. `witness gate` spawns the DECLARED harness's headless
256
256
  mode for every reviewer (Decisions 88, 105): claude-code renders bare Anthropic ids, pi
257
257
  renders `provider/model[:thinking]` with the provider witness knows it needs. The pi
258
- reviewer runs hermetic (`--no-extensions --no-skills --no-context-files`); machine
258
+ reviewer runs hermetic (`--no-extensions --no-skills --no-context-files`); claude's runs with `--safe-mode` (no hooks, `CLAUDE.md`, plugins or MCP servers) and saves no session; every reviewer gets no tools, or read-only file tools where it must open files, and witness refuses any verb but read, index, log and diff inside one; machine
259
259
  extensions it must keep — e.g. an OAuth adapter that supplies your Anthropic auth —
260
260
  are declared in machine config, not env:
261
261
 
@@ -280,7 +280,7 @@ the wrong file refuses. There are no `WITNESS_*` env vars for configuration.
280
280
  | `draft <key> [--file <json>]` | a grill's or design session's local draft — saved after every settled answer, read back to resume; never committed or journaled |
281
281
  | `write <id> --effort <e> --meta <json> --body <md>` | validated manifest → spec/plan on disk + journal entry; a spec's `covers` and `carries` map it to the recap's goals and decisions |
282
282
  | `diff <spec-id>` | delta since the last realized state (plan pin → empty), and the decisions that moved since that plan |
283
- | `read <id> [--design] [--outline] [--lines <a>-<b>] [--decisions]` | print a spec/plan/design from the primary root — the read route, since a worktree carries no canon copy; `--outline` names each anchor's line range for fat artifacts; `--decisions` prints the decisions a spec carries with its effort's constraints and non-goals, or an effort's whole recap |
283
+ | `read <id> [--design] [--outline] [--lines <a>-<b>] [--decisions]` | print a spec/plan/design from the primary root — the read route, since a worktree carries no canon copy; `--outline` names each anchor's line range for fat artifacts, and for a look its controls and hidden states; `--decisions` prints the decisions a spec carries with its effort's constraints and non-goals, or an effort's whole recap |
284
284
  | `check` | schema, graph, invariants, needs, trailer audit, probes |
285
285
  | `index` | id · summary · status · depends across the canon, then each spec's plans |
286
286
  | `satisfy <id> --need <id\|n\|text>` | journal a manual need as met — the spec is never rewritten |
@@ -291,6 +291,7 @@ the wrong file refuses. There are no `WITNESS_*` env vars for configuration.
291
291
  | `gate <decompose\|plan\|implement\|ship\|design> <id>` | run the reviewer gate; journals the round, stamps on pass |
292
292
  | `decide <gate> <id> --approve\|--revise [--pin <policy>]` | record the human decision on a stopped gate; `--pin` adds a standing content policy |
293
293
  | `design <spec-id> --file <html>\|--open\|--reconfirm\|--preview <html>` | register/show a `ui` spec's approved look; `--preview` opens a page and records nothing |
294
+ | `review design <spec-id> [--file <html>]` | the design gate's reviewers on a look — the registered one, or a page not yet registered — asking the gate's full-review question; journals nothing, decides nothing, and replays the gate's answer when the gate already judged the same bytes in full |
294
295
  | `start <plan-id>` | create/re-attach the plan's worktree (`.witness/worktrees/<id>`) — code only: the canon dirs are excluded from it, so a plan cannot go stale in there |
295
296
  | `next` | the one next action across every effort |
296
297
  | `drive [--flow <plan-id>] [--max-spawns <n>] [--manual] [--detach]` | runs every session itself · under autonomy it needs no terminal and reports when nothing else can move. Up to `drive.parallel` targets at once, one session per target; usage limits are waited out; a target past a cap is parked. `--detach` (autonomy only) runs it in the background into `.witness/drive.log` — each session's start, every command and file its agent touches, every act it journals for its flow, a `still running` line after 5 quiet minutes, and how it ended; drive's pi sessions are kept in pi's session store under `witness-drive/`; `--manual` runs serially and asks you at every stop. One drive per repo. A session drive spawned is refused — agents are what drive spawns, never what spawns drive |
package/dist/battery.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { SESSION_DEFAULT } from './model.js';
2
2
  import { ok, refuse } from './refusal.js';
3
- import { invokeReviewerAsync, parseVerdictText } from './reviewer.js';
3
+ import { invokeReviewerAsync, parseVerdictText, toolsFor } from './reviewer.js';
4
4
  import { parseVerdict, verdictViolations } from './verdict.js';
5
5
  // Row 169, amended by row 212: every lens is asked on the stage's one model, and a lens that
6
6
  // cannot be invoked refuses at once — there is no stand-in to fall back to.
@@ -10,6 +10,7 @@ async function runLens(ctx, harness, model, lens, opts) {
10
10
  for (let attempt = 0;; attempt++) {
11
11
  const r = await invokeReviewerAsync(ctx, harness, {
12
12
  ...opts, prompt, model: model === SESSION_DEFAULT ? undefined : model, lens: lens.name,
13
+ tools: toolsFor(lens.reviewed), // row 217: read-only file tools only for content named by path
13
14
  });
14
15
  if (!r.ok)
15
16
  return refuse(r.violations);
package/dist/cli.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { existsSync } from 'node:fs';
2
2
  import { configPath } from './config.js';
3
3
  import { journalStamp } from './context.js';
4
+ import { isReviewer } from './drive-presence.js';
4
5
  import { stateFloor } from './floor.js';
5
6
  import { primaryRoot } from './gitio.js';
6
7
  import { withJournalCtx } from './journal.js';
@@ -39,6 +40,8 @@ const VERBS = {
39
40
  gate: () => import('./verbs/gate.js'),
40
41
  decide: () => import('./verbs/decide.js'),
41
42
  design: () => import('./verbs/design.js'),
43
+ // Row 215. The design gate's reviewers on demand: the gate's question, journaled nowhere.
44
+ review: () => import('./verbs/review.js'),
42
45
  start: () => import('./verbs/start.js'),
43
46
  // The orientation screen has a name (D101). Bare `witness` stays as its alias, but
44
47
  // an unnamed command cannot be referenced — commands/witness.md instructs the
@@ -86,6 +89,7 @@ const VERB_USAGE = {
86
89
  recover: 'witness recover [--complete | --rollback]',
87
90
  rename: 'witness rename <old-id> <new-id>',
88
91
  retry: 'witness retry <target>',
92
+ review: 'witness review design <spec-id> [--file <html>]',
89
93
  satisfy: 'witness satisfy <doc-id> --need <id | index | text>',
90
94
  dismiss: 'witness dismiss <artifact> --deferral <id|index> --cause <superseded|lens-retired|judged-wrong> --note "<why>"',
91
95
  ship: 'witness ship <plan-id> [--manual]',
@@ -98,6 +102,8 @@ const VERB_USAGE = {
98
102
  'verify-red': 'witness verify-red <plan-id> [--base <ref>] [--step <id>]',
99
103
  wait: 'witness wait [--since <token>] — blocks until something new needs you · the chat runs it under autonomy',
100
104
  };
105
+ // Row 217. The verbs a reviewer may run: each only reads.
106
+ const REVIEWER_VERBS = new Set(['read', 'index', 'log', 'diff']);
101
107
  // Row 116 moved the body to version.ts, which journal.ts can import without closing a
102
108
  // cycle. Re-exported here because eleven call sites already ask the CLI shell for it and
103
109
  // the question they are asking has not changed.
@@ -145,6 +151,13 @@ export async function main(ctx, argv) {
145
151
  // the human nothing they can act on.
146
152
  const helpRequested = verb === 'help' || verb === '--help'
147
153
  || rest.includes('--help') || rest.includes('-h');
154
+ // Row 217. A reviewer reads; it never acts. Its tools are already gone (the spawn flags); this tripwire
155
+ // refuses what a harness that ignored them could still run. Checked directly: a reviewer spawned inside
156
+ // a drive session carries both markers, and `sessionMarker` names the drive's first.
157
+ if (isReviewer(ctx.env) && !helpRequested && !REVIEWER_VERBS.has(verb ?? '')) {
158
+ renderRefusal([v('witness', 'reviewer-cannot', `${verb ?? '(no verb)'} under WITNESS_REVIEWER`, 'nothing — a reviewer reads and never acts; it may run witness read, index, log or diff')]).forEach((l) => ctx.err(l));
159
+ return EXIT.REFUSED;
160
+ }
148
161
  if (!helpRequested && verb !== 'floor') {
149
162
  const gateRoot = primaryRoot(ctx.cwd);
150
163
  if (gateRoot.ok) {
package/dist/deferral.js CHANGED
@@ -26,8 +26,9 @@ export function openDeferrals(entries) {
26
26
  }
27
27
  return [...open.values()];
28
28
  }
29
- // Injected into every lens, exactly as `pinsBlock` is, and joined to `prompts_sha` so a new
30
- // obligation invalidates the verdict cache and the next round cannot judge without it.
29
+ // Injected into every lens that can read the debt (row 216), beside `pinsBlock`, and joined to
30
+ // `prompts_sha` so a new obligation invalidates the verdict cache and the next round cannot
31
+ // judge without it.
31
32
  // Deliberately the INVERSE of a pin: a pin tells reviewers not to re-litigate, this tells
32
33
  // them to report the thing if it is still there. Pins suppress findings; obligations
33
34
  // solicit them — which is what makes the discharge automatic and evidence-shaped.
@@ -50,8 +51,8 @@ export function deferralsBlock(open) {
50
51
  return '## Open deferrals (approved over findings — report these if they still hold)\n\n' +
51
52
  'This artifact was approved over the findings below rather than fixed. They are NOT settled ' +
52
53
  'policy and they are NOT pins. If a defect is still present, report it as a finding anchored ' +
53
- 'exactly as listed: that keeps its obligation open. Silence is read as fixed: an obligation ' +
54
- 'this round does not report is discharged.\n\n' +
54
+ 'exactly as listed: that keeps its obligation open. The gate reads silence as fixed: an ' +
55
+ 'obligation a gate round does not report is discharged.\n\n' +
55
56
  open.map(line).join('\n') + '\n\n';
56
57
  }
57
58
  // D122 + D166. A debt changes homes when the artifact holding it stops being the one the next
package/dist/design.js CHANGED
@@ -1,18 +1,551 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { existsSync, readFileSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
+ import { serializeDoc } from './fm.js';
4
5
  import { latestRecap, readStream } from './journal.js';
5
6
  import { v } from './refusal.js';
6
7
  import { effortOf } from './reviewed.js';
7
8
  import { canonicalSha } from './sha.js';
9
+ import { cmd, logSafe, rows } from './toon.js';
10
+ // What `--outline` and the critic's anchor menu call an id. `lookControls` reads the same
11
+ // matches, so a control's anchor is always one the outline lists.
12
+ const ID_ATTR = /\bid\s*=\s*["']([^"']+)["']/g;
8
13
  export function elementIds(html) {
9
14
  const ids = [];
10
- const re = /\bid\s*=\s*["']([^"']+)["']/g;
15
+ const re = new RegExp(ID_ATTR.source, 'g');
11
16
  let m;
12
17
  while ((m = re.exec(html)) !== null)
13
18
  ids.push(m[1].trim());
14
19
  return ids;
15
20
  }
21
+ export const CONTROLS_NOTE = 'from markup only — states a CSS class or a script draws, :hover and :focus styles, and content past a scrolling pane are not listed; read the source for those';
22
+ const RAW_TEXT = new Set(['script', 'style', 'textarea', 'title', 'xmp', 'iframe', 'noembed', 'noframes', 'noscript']);
23
+ // The raw-text bodies a browser shows: each is one text run. The others emit nothing.
24
+ const SHOWN_RAW = new Set(['textarea', 'title', 'xmp']);
25
+ // The HTML spec's breakout tags: any of them inside an svg or math left open is HTML again.
26
+ const BREAKOUT = new Set(['b', 'big', 'blockquote', 'body', 'br', 'center', 'code', 'dd', 'div', 'dl', 'dt', 'em',
27
+ 'embed', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'hr', 'i', 'img', 'li', 'listing', 'menu', 'meta', 'nobr', 'ol',
28
+ 'p', 'pre', 'ruby', 's', 'small', 'span', 'strong', 'strike', 'sub', 'sup', 'table', 'tt', 'u', 'ul', 'var']);
29
+ const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);
30
+ // Elements a browser lays out as their own box: their tags separate words as a `br` does, so
31
+ // `<div>Step 1</div><div>Open</div>` reads "Step 1 Open" — inline tags (`<b>reject</b>?`) join.
32
+ const BLOCK = new Set(['address', 'article', 'aside', 'blockquote', 'br', 'dd', 'details', 'dialog', 'div', 'dl', 'dt',
33
+ 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', 'li',
34
+ 'main', 'nav', 'ol', 'p', 'pre', 'section', 'summary', 'table', 'td', 'th', 'tr', 'ul']);
35
+ const ROLES = new Set(['menu', 'listbox', 'tooltip', 'tabpanel', 'alertdialog', 'dialog']);
36
+ const NEVER = new Set(['option', 'optgroup', 'summary']);
37
+ const GATHER = 240; // code points of text read per element
38
+ const HOLDS_MAX = 120;
39
+ const isLetter = (c) => (c >= 65 && c <= 90) || (c >= 97 && c <= 122);
40
+ const isWs = (c) => c === 0x20 || c === 0x09 || c === 0x0a || c === 0x0c || c === 0x0d;
41
+ // Only ASCII is lowercased: `toLowerCase` on the source turns `İ` into two code units and shifts
42
+ // every offset after it (P3).
43
+ const lowerAscii = (s) => s.replace(/[A-Z]+/g, (m) => m.toLowerCase());
44
+ // Does `src` hold `name` (ASCII-case-insensitively) at `at`, followed by whitespace, `/` or `>`?
45
+ function nameAt(src, at, name) {
46
+ if (lowerAscii(src.slice(at, at + name.length)) !== name)
47
+ return false;
48
+ const c = src.charCodeAt(at + name.length);
49
+ return isWs(c) || c === 47 || c === 62;
50
+ }
51
+ // D7.1–7.2: one forward pass by index over the original string. A template's body runs through
52
+ // the same pass with its output suppressed, so its comments, raw text and quotes still count.
53
+ function tokenize(src) {
54
+ const toks = [];
55
+ const n = src.length;
56
+ let i = 0;
57
+ let textStart = 0;
58
+ let foreign = 0; // svg/math depth
59
+ let inert = 0; // open templates; >0 suppresses
60
+ let foreignAtTemplate = 0;
61
+ const emit = (tk) => { if (inert === 0)
62
+ toks.push(tk); };
63
+ const flush = (end) => { if (end > textStart)
64
+ emit({ t: 'text', start: textStart, end }); };
65
+ // Forward cursors for a comment's two closers: each remembers its last hit and searches again
66
+ // only once the scan has passed it, so neither ever rescans the source.
67
+ let arrow = -2;
68
+ let bang = -2;
69
+ const nextArrow = (from) => {
70
+ if (arrow !== -1 && arrow < from)
71
+ arrow = src.indexOf('-->', from);
72
+ return arrow;
73
+ };
74
+ const nextBang = (from) => {
75
+ if (bang !== -1 && bang < from)
76
+ bang = src.indexOf('--!>', from);
77
+ return bang;
78
+ };
79
+ // The first `</name` + whitespace, `/` or `>` at or after `from`, else the end. The pass
80
+ // resumes there, so what this reads is never read again.
81
+ const rawEnd = (from, name) => {
82
+ for (let p = src.indexOf('</', from); p !== -1; p = src.indexOf('</', p + 2))
83
+ if (nameAt(src, p + 2, name))
84
+ return p;
85
+ return n;
86
+ };
87
+ const nameEnd = (from) => {
88
+ let j = from;
89
+ while (j < n) {
90
+ const c = src.charCodeAt(j);
91
+ if (isWs(c) || c === 47 || c === 62)
92
+ break;
93
+ j++;
94
+ }
95
+ return j;
96
+ };
97
+ while (i < n) {
98
+ const lt = src.indexOf('<', i);
99
+ if (lt === -1)
100
+ break;
101
+ const c1 = src.charCodeAt(lt + 1);
102
+ if (src.startsWith('<!--', lt)) {
103
+ flush(lt);
104
+ let end;
105
+ if (src.charCodeAt(lt + 4) === 62)
106
+ end = lt + 5; // <!-->
107
+ else if (src.startsWith('->', lt + 4))
108
+ end = lt + 6; // <!--->
109
+ else {
110
+ const a = nextArrow(lt + 4);
111
+ const b = nextBang(lt + 4);
112
+ end = Math.min(a === -1 ? n : a + 3, b === -1 ? n : b + 4);
113
+ }
114
+ i = textStart = end;
115
+ continue;
116
+ }
117
+ if (c1 === 33 || c1 === 63) { // <! or <?: a bogus comment
118
+ flush(lt);
119
+ const g = src.indexOf('>', lt + 2);
120
+ i = textStart = g === -1 ? n : g + 1;
121
+ continue;
122
+ }
123
+ if (c1 === 47 && isLetter(src.charCodeAt(lt + 2))) { // a close tag
124
+ flush(lt);
125
+ const j = nameEnd(lt + 2);
126
+ const name = lowerAscii(src.slice(lt + 2, j));
127
+ // A template's balanced close ends its suppressed body, and is itself emitted.
128
+ if (name === 'template' && inert > 0 && --inert === 0)
129
+ foreign = foreignAtTemplate;
130
+ emit({ t: 'close', name, start: lt });
131
+ if ((name === 'svg' || name === 'math') && foreign > 0)
132
+ foreign--;
133
+ const g = src.indexOf('>', j);
134
+ i = textStart = g === -1 ? n : g + 1;
135
+ continue;
136
+ }
137
+ if (!isLetter(c1)) {
138
+ i = lt + 1;
139
+ continue;
140
+ } // `<` is text
141
+ // An open tag: its name, then its attributes. A quote opens a value only after `=`.
142
+ flush(lt);
143
+ let j = nameEnd(lt + 1);
144
+ const name = lowerAscii(src.slice(lt + 1, j));
145
+ const attrs = new Map();
146
+ let slash = false;
147
+ let closed = false;
148
+ while (j < n) {
149
+ const c = src.charCodeAt(j);
150
+ if (isWs(c)) {
151
+ j++;
152
+ continue;
153
+ }
154
+ if (c === 62) {
155
+ j++;
156
+ closed = true;
157
+ break;
158
+ }
159
+ if (c === 47) {
160
+ if (src.charCodeAt(j + 1) === 62) {
161
+ j += 2;
162
+ slash = true;
163
+ closed = true;
164
+ break;
165
+ }
166
+ j++;
167
+ continue;
168
+ }
169
+ const ns = j++;
170
+ while (j < n) {
171
+ const d = src.charCodeAt(j);
172
+ if (isWs(d) || d === 47 || d === 62 || d === 61)
173
+ break;
174
+ j++;
175
+ }
176
+ const aname = lowerAscii(src.slice(ns, j));
177
+ let k = j;
178
+ while (k < n && isWs(src.charCodeAt(k)))
179
+ k++;
180
+ let attr = { v: '', quoted: false };
181
+ if (src.charCodeAt(k) === 61) {
182
+ k++;
183
+ while (k < n && isWs(src.charCodeAt(k)))
184
+ k++;
185
+ const q = src.charCodeAt(k);
186
+ if (q === 34 || q === 39) {
187
+ const e = src.indexOf(q === 34 ? '"' : "'", k + 1);
188
+ if (e === -1) {
189
+ j = n;
190
+ break;
191
+ } // a quote that never closes
192
+ attr = { v: src.slice(k + 1, e), quoted: true };
193
+ j = e + 1;
194
+ }
195
+ else {
196
+ let e = k;
197
+ while (e < n) {
198
+ const d = src.charCodeAt(e);
199
+ if (isWs(d) || d === 62)
200
+ break;
201
+ e++;
202
+ }
203
+ attr = { v: src.slice(k, e), quoted: false };
204
+ j = e;
205
+ }
206
+ }
207
+ if (!attrs.has(aname))
208
+ attrs.set(aname, attr);
209
+ }
210
+ // A tag the source ends inside is one broken tag: no token, and no more tokens after it.
211
+ if (!closed) {
212
+ i = textStart = n;
213
+ break;
214
+ }
215
+ if (foreign > 0 && BREAKOUT.has(name))
216
+ foreign = 0;
217
+ // `/>` closes only a foreign element; on an HTML one a browser ignores it.
218
+ const self = slash && (foreign > 0 || name === 'svg' || name === 'math');
219
+ const html = foreign === 0 && name !== 'svg' && name !== 'math';
220
+ emit({ t: 'open', name, attrs, start: lt, end: j, self, html });
221
+ i = textStart = j;
222
+ if (self)
223
+ continue;
224
+ if (name === 'svg' || name === 'math')
225
+ foreign++;
226
+ else if (foreign > 0 && name !== 'script')
227
+ continue;
228
+ else if (name === 'template') {
229
+ if (inert++ === 0)
230
+ foreignAtTemplate = foreign;
231
+ }
232
+ else if (name === 'plaintext') {
233
+ i = n;
234
+ break;
235
+ } // the rest is one text run
236
+ else if (RAW_TEXT.has(name)) {
237
+ const e = rawEnd(j, name);
238
+ if (SHOWN_RAW.has(name) && e > j)
239
+ emit({ t: 'text', start: j, end: e });
240
+ i = textStart = e;
241
+ }
242
+ }
243
+ flush(n);
244
+ return toks;
245
+ }
246
+ const ENTITY = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ' };
247
+ // One pass: `&amp;lt;` is `&lt;`, never `<`.
248
+ const decode = (s) => s.replace(/&(amp|lt|gt|quot|apos|nbsp);|&#(\d+);|&#[xX]([0-9a-fA-F]+);/g, (_m, named, dec, hex) => {
249
+ if (named !== undefined)
250
+ return ENTITY[named];
251
+ const cp = dec !== undefined ? Number(dec) : Number.parseInt(hex, 16);
252
+ return cp === 0 || (cp >= 0xd800 && cp <= 0xdfff) || !(cp <= 0x10ffff) ? '\u{fffd}' : String.fromCodePoint(cp);
253
+ });
254
+ // Decoded, then whitespace collapsed and trimmed: what a `holds` candidate says.
255
+ const clean = (raw) => decode(raw).replace(/\s+/g, ' ').trim();
256
+ // D7.4's last two steps: spelled out, then cut to 120 code points, ending `…` on any cut.
257
+ function finish(said, truncated) {
258
+ const safe = logSafe(said);
259
+ const cps = Array.from(safe);
260
+ return truncated || cps.length > HOLDS_MAX ? cps.slice(0, HOLDS_MAX - 1).join('') + '…' : safe;
261
+ }
262
+ // The first `max` code points of src[from, to), how many there were, and whether that cut it.
263
+ function head(src, from, to, max) {
264
+ let at = from;
265
+ let count = 0;
266
+ while (at < to && count < max) {
267
+ at += src.codePointAt(at) > 0xffff ? 2 : 1;
268
+ count++;
269
+ }
270
+ return [src.slice(from, Math.min(at, to)), count, at < to];
271
+ }
272
+ const styleHides = (style) => {
273
+ let css = '';
274
+ let from = 0;
275
+ for (let o = style.indexOf('/*'); o !== -1; o = style.indexOf('/*', from)) {
276
+ css += style.slice(from, o);
277
+ const e = style.indexOf('*/', o + 2);
278
+ from = e === -1 ? style.length : e + 2;
279
+ }
280
+ if (from < style.length)
281
+ css += style.slice(from);
282
+ return /(?<![\w-])display\s*:\s*none(?![\w-])/i.test(css) || /(?<![\w-])visibility\s*:\s*hidden(?![\w-])/i.test(css);
283
+ };
284
+ export function lookControls(html) {
285
+ const toks = tokenize(html);
286
+ const n = toks.length;
287
+ const blank = new Uint8Array(n);
288
+ toks.forEach((tk, p) => { if (tk.t === 'text' && /^\s*$/.test(html.slice(tk.start, tk.end)))
289
+ blank[p] = 1; });
290
+ // D7.3, each index in one pass. Element ends: each open tag's matching close, by per-name
291
+ // stacks; a void or self-closed element has none, an unmatched one ends at the source's end.
292
+ const endOf = new Int32Array(n).fill(n);
293
+ const stacks = new Map();
294
+ toks.forEach((tk, p) => {
295
+ if (tk.t === 'open') {
296
+ if (VOID.has(tk.name) || tk.self)
297
+ endOf[p] = p;
298
+ else {
299
+ const s = stacks.get(tk.name);
300
+ if (s)
301
+ s.push(p);
302
+ else
303
+ stacks.set(tk.name, [p]);
304
+ }
305
+ }
306
+ else if (tk.t === 'close') {
307
+ const open = stacks.get(tk.name)?.pop();
308
+ if (open !== undefined)
309
+ endOf[open] = p;
310
+ }
311
+ });
312
+ // The text chain: the next text run, `br` or block tag after each token.
313
+ const chain = new Int32Array(n).fill(-1);
314
+ for (let p = n - 1, next = -1; p >= 0; p--) {
315
+ chain[p] = next;
316
+ const tk = toks[p];
317
+ if (tk.t === 'text' || BLOCK.has(tk.name))
318
+ next = p;
319
+ }
320
+ // Ids: each quoted id to its first open tag (aria-labelledby's targets).
321
+ const byId = new Map();
322
+ toks.forEach((tk, p) => {
323
+ const id = tk.t === 'open' ? tk.attrs.get('id') : undefined;
324
+ if (id?.quoted && !byId.has(id.v.trim()))
325
+ byId.set(id.v.trim(), p);
326
+ });
327
+ // Line anchors: the `--outline`'s ids, per line as it reads them, at their source offsets.
328
+ const nl = [];
329
+ for (let o = html.indexOf('\n'); o !== -1; o = html.indexOf('\n', o + 1))
330
+ nl.push(o);
331
+ // Each id is spelled out and cut once, here, so a long id over many controls costs its length
332
+ // once rather than once per row — and a row's anchor stays as short as its `holds`.
333
+ const shown = (id) => {
334
+ const cps = Array.from(logSafe(id));
335
+ return cps.length > HOLDS_MAX ? cps.slice(0, HOLDS_MAX - 1).join('') + '…' : cps.join('');
336
+ };
337
+ const hits = [];
338
+ for (let l = 0, from = 0; l <= nl.length; l++) {
339
+ const to = l < nl.length ? nl[l] : html.length;
340
+ const re = new RegExp(ID_ATTR.source, 'g');
341
+ const text = html.slice(from, to);
342
+ for (let m = re.exec(text); m !== null; m = re.exec(text))
343
+ hits.push({ at: from + m.index, line: l + 1, id: shown(m[1].trim()) });
344
+ from = to + 1;
345
+ }
346
+ // D7.4. An element's text: the chain from its open tag to its end, text runs as written, a
347
+ // whitespace-only run, a `br` or a block tag one space, every other tag nothing; at most 240
348
+ // code points.
349
+ const textOf = (k) => {
350
+ let raw = '';
351
+ let count = 0;
352
+ let spaced = false;
353
+ for (let p = chain[k], end = endOf[k]; p !== -1 && p < end; p = chain[p]) {
354
+ if (count >= GATHER)
355
+ return { raw, truncated: true };
356
+ const tk = toks[p];
357
+ if (tk.t !== 'text' || blank[p] === 1) { // one space, collapsed as it goes
358
+ if (!spaced)
359
+ raw += ' ';
360
+ spaced = true;
361
+ count++;
362
+ continue;
363
+ }
364
+ const [h, c, cut] = head(html, tk.start, tk.end, GATHER - count);
365
+ raw += h;
366
+ count += c;
367
+ spaced = false;
368
+ if (cut)
369
+ return { raw, truncated: true };
370
+ }
371
+ return { raw, truncated: false };
372
+ };
373
+ const attr = (tk, a) => tk.attrs.get(a)?.v ?? '';
374
+ // D7.6: aria-label, aria-labelledby's elements, title, the element's own text, <name>.<class>.
375
+ const named = (tk, k) => {
376
+ const label = clean(attr(tk, 'aria-label'));
377
+ if (label !== '')
378
+ return finish(label, false);
379
+ let by = '';
380
+ let byCut = false;
381
+ for (const id of attr(tk, 'aria-labelledby').split(/\s+/)) {
382
+ const at = id === '' ? undefined : byId.get(id);
383
+ if (at === undefined)
384
+ continue;
385
+ if ([...by].length >= GATHER) {
386
+ byCut = true;
387
+ break;
388
+ }
389
+ const t = textOf(at);
390
+ by += ' ' + t.raw;
391
+ byCut ||= t.truncated;
392
+ }
393
+ if (clean(by) !== '')
394
+ return finish(clean(by), byCut);
395
+ const title = clean(attr(tk, 'title'));
396
+ if (title !== '')
397
+ return finish(title, false);
398
+ const own = textOf(k);
399
+ if (clean(own.raw) !== '')
400
+ return finish(clean(own.raw), own.truncated);
401
+ const cls = clean(attr(tk, 'class')).split(' ')[0];
402
+ return finish(cls !== '' ? `${tk.name}.${cls}` : tk.name, false);
403
+ };
404
+ const out = [];
405
+ let line = 1;
406
+ let hit = 0; // hits before the element
407
+ let nextSelect = 0;
408
+ const selects = [];
409
+ toks.forEach((tk, p) => { if (tk.t === 'open' && tk.html && tk.name === 'select')
410
+ selects.push(p); });
411
+ toks.forEach((tk, k) => {
412
+ if (tk.t !== 'open' || NEVER.has(tk.name))
413
+ return;
414
+ const has = (a) => tk.attrs.has(a);
415
+ const role = lowerAscii(attr(tk, 'role').trim().split(/\s+/)[0]);
416
+ let kind;
417
+ if (tk.html && tk.name === 'select')
418
+ kind = 'select';
419
+ else if (tk.html && tk.name === 'details' && !has('open'))
420
+ kind = 'details';
421
+ else if (tk.html && tk.name === 'dialog' && !has('open'))
422
+ kind = 'dialog';
423
+ else if (tk.html && has('popover'))
424
+ kind = 'popover';
425
+ else if (ROLES.has(role))
426
+ kind = role;
427
+ else if (lowerAscii(attr(tk, 'aria-expanded').trim()) === 'false')
428
+ kind = 'collapsed';
429
+ else if (has('hidden') || styleHides(attr(tk, 'style')))
430
+ kind = 'hidden';
431
+ else if (tk.html && tk.name === 'template')
432
+ kind = 'template';
433
+ if (kind === undefined)
434
+ return;
435
+ let holds = '';
436
+ if (kind === 'select') {
437
+ // D7.5: the region runs to its matching close or the next select open; an option is its
438
+ // label, else its text up to the next option, optgroup or hr open, or option or select close.
439
+ while (selects[nextSelect] !== undefined && selects[nextSelect] <= k)
440
+ nextSelect++;
441
+ const region = Math.min(endOf[k], selects[nextSelect] ?? n);
442
+ const options = [];
443
+ let size = 0;
444
+ let cut = false;
445
+ let cur;
446
+ const done = () => {
447
+ if (cur === undefined)
448
+ return;
449
+ const label = clean(cur.label);
450
+ const said = label !== '' ? label : clean(cur.raw);
451
+ if (said !== '') {
452
+ options.push(said);
453
+ size += [...said].length + 3;
454
+ }
455
+ cur = undefined;
456
+ };
457
+ for (let p = k + 1; p < region && !cut; p++) {
458
+ const o = toks[p];
459
+ if (o.t === 'open') {
460
+ if (o.name === 'option') {
461
+ done();
462
+ cur = { raw: '', count: 0, label: attr(o, 'label') };
463
+ }
464
+ else if (o.name === 'optgroup' || o.name === 'hr')
465
+ done();
466
+ else if (BLOCK.has(o.name) && cur !== undefined) {
467
+ cur.raw += ' ';
468
+ cur.count++;
469
+ } // as in an element's text
470
+ }
471
+ else if (o.t === 'close') {
472
+ if (o.name === 'option' || o.name === 'select')
473
+ done();
474
+ else if (BLOCK.has(o.name) && cur !== undefined) {
475
+ cur.raw += ' ';
476
+ cur.count++;
477
+ }
478
+ }
479
+ else if (cur !== undefined && cur.count < GATHER) {
480
+ const [h, c, more] = head(html, o.start, o.end, GATHER - cur.count);
481
+ cur.raw += blank[p] === 1 ? ' ' : h;
482
+ cur.count += c;
483
+ if (more)
484
+ cut = true;
485
+ }
486
+ if (size >= GATHER)
487
+ cut = true;
488
+ }
489
+ done();
490
+ if (options.length > 0)
491
+ holds = finish(options.join(' | '), cut);
492
+ }
493
+ else if (kind === 'details') {
494
+ // The text of its first child element when that child is a summary, else "Details".
495
+ let c = k + 1;
496
+ while (toks[c]?.t === 'text' && blank[c] === 1)
497
+ c++;
498
+ const first = toks[c];
499
+ if (first?.t === 'open' && first.name === 'summary') {
500
+ const t = textOf(c);
501
+ if (clean(t.raw) !== '')
502
+ holds = finish(clean(t.raw), t.truncated);
503
+ }
504
+ else
505
+ holds = 'Details';
506
+ }
507
+ if (holds === '')
508
+ holds = named(tk, k);
509
+ // D7.7–7.8: the element's own id — the first outline id inside its start tag — else the id
510
+ // whose `--outline` span holds its line: the last id before it on its line, else the first
511
+ // id on its line, else the last id on an earlier line.
512
+ while (nl[line - 1] !== undefined && nl[line - 1] < tk.start)
513
+ line++;
514
+ while (hits[hit] !== undefined && hits[hit].at < tk.start)
515
+ hit++;
516
+ const before = hits[hit - 1];
517
+ const after = hits[hit];
518
+ let anchor;
519
+ if (after !== undefined && after.at < tk.end)
520
+ anchor = after.id;
521
+ else if (before?.line === line)
522
+ anchor = before.id;
523
+ else if (after?.line === line)
524
+ anchor = after.id;
525
+ else
526
+ anchor = before?.id ?? '-';
527
+ out.push({ anchor, line, kind, holds });
528
+ });
529
+ return out;
530
+ }
531
+ // The `--outline` block and the critic's input: the rows, then what markup cannot show.
532
+ export function controlsBlock(html) {
533
+ return [...rows('controls', ['anchor', 'line', 'kind', 'holds'], lookControls(html)), cmd('controls-note', CONTROLS_NOTE)];
534
+ }
535
+ // Row 215 (D2). The one home for what the design critic reads, for the gate and for a review: the
536
+ // look — named by its spec, never a path, so a scratch page and the same bytes registered are one
537
+ // question — then its controls, then the spec. With no artifact the checks already fail-stop,
538
+ // and the body still names what is missing.
539
+ export function designReviewed(html, spec) {
540
+ const id = String(spec.meta.id);
541
+ const promptBody = [
542
+ `### Design artifact: the look for ${id}`, html ?? '(missing — no artifact to review)',
543
+ ...(html !== undefined ? ['### Controls in the look (from markup)', controlsBlock(html).join('\n')] : []),
544
+ `### Parent spec: ${id}`, serializeDoc({ meta: spec.meta, body: spec.body }),
545
+ ].join('\n\n');
546
+ const ids = html !== undefined ? elementIds(html) : [];
547
+ return { reviewed: { kind: 'design', artifact: { ids }, spec: { id, body: spec.body } }, promptBody };
548
+ }
16
549
  // A design artifact is a portable, self-contained mockup: it must render with no
17
550
  // network, and it must expose id-attributed sections so the design-critic can anchor
18
551
  // findings to concrete parts of the screen (the anchor grammar's targets).