dsh-model-everything 0.5.2 → 0.6.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.
@@ -11,7 +11,7 @@ import { writeSvg } from './render/write.js';
11
11
  export const DIAGRAM_TOOL_NAME = 'diagram_render';
12
12
  export const diagramRenderTool = defineTool({
13
13
  name: DIAGRAM_TOOL_NAME,
14
- description: 'Draw a diagram from its source text and get back SVG. Accepts Mermaid (flowchart, stateDiagram) and PlantUML (component, package, state) for the subset this renderer draws, lays out boxes and arrows itself, and reports every line it refused with its line number instead of drawing half a diagram. Pass `out` to write the SVG next to a document. This tool draws; it does not parse a diagram back into a model, and it does not review one - uml_parse and uml_review do that.',
14
+ description: 'Draw a diagram from its source text and get back SVG. Structure is read from a picture, so reach for this whenever the answer is a layout, a flow, a set of boundaries or a change between two of them - not only when the request says draw. Pass `out` to write the SVG and show it to the reader beside the explanation it carries, and read the model-everything-diagram skill for what this notation subset covers and what it refuses. It accepts Mermaid (flowchart, stateDiagram) and PlantUML (component, package, state), lays out boxes and arrows itself, and reports every line it refused with its line number instead of drawing half a diagram. This tool draws; it does not parse a diagram back into a model, and it does not review one - uml_parse and uml_review do that.',
15
15
  parameters: {
16
16
  source: {
17
17
  type: 'string',
@@ -58,6 +58,18 @@ export const diagramRenderTool = defineTool({
58
58
  }
59
59
  return [{ type: 'text', text: lines.join('\n') }];
60
60
  },
61
+ // The card a UI shows. The host keeps this on the settled call as `block.meta`, which is the one place a
62
+ // view can find the drawing's own source: by then the arguments are gone. Measured against how
63
+ // dsh-deepread's card reads its payload - the same field.
64
+ presentationMeta(args, value) {
65
+ const result = value;
66
+ const asked = args;
67
+ return {
68
+ source: typeof asked.source === 'string' ? asked.source : '',
69
+ scheme: typeof asked.scheme === 'string' ? asked.scheme : 'default',
70
+ caption: typeof result.caption === 'string' ? result.caption : '',
71
+ };
72
+ },
61
73
  },
62
74
  timeoutMs: 10_000,
63
75
  isConcurrencySafe: () => true,
@@ -19,7 +19,7 @@ function limitsOf(args) {
19
19
  }
20
20
  export const diagramReviewTool = defineTool({
21
21
  name: DIAGRAM_REVIEW_TOOL_NAME,
22
- description: 'Review the structure of a diagram from its source text: how wide each boundary is, how deep they nest, and how many nodes the drawing holds, against budgets you can set. Accepts the same Mermaid and PlantUML subset as diagram_render and reports what it measured, so an empty report cannot be mistaken for a clean one. Read `verdict`, never `ok`. This reviews structure; it does not draw (diagram_render does) and it does not check behaviour (model_verify does).',
22
+ description: 'Review the structure of a diagram from its source text: how wide each boundary is, how deep they nest, and how many nodes the drawing holds, against budgets you can set. Run it before a drawing goes in front of a reader: a picture that needs scrolling is no longer a summary. Accepts the same Mermaid and PlantUML subset as diagram_render and reports what it measured, so an empty report cannot be mistaken for a clean one. Read `verdict`, never `ok`. This reviews structure; it does not draw (diagram_render does) and it does not check behaviour (model_verify does).',
23
23
  parameters: {
24
24
  source: {
25
25
  type: 'string',
package/lib/diagram.js CHANGED
@@ -10,6 +10,7 @@
10
10
  * boot, from the Plugins page, or by disabling this row, and none of those touches the tools or the skills.
11
11
  */
12
12
  import z from '@deepseek-ai/schemastery';
13
+ import { createUserMessage } from '@deepseek-ai/dsh-llm';
13
14
  import { diagramDiffTool } from './diagram-diff-tool.js';
14
15
  import { diagramRenderTool } from './diagram-render-tool.js';
15
16
  import { diagramReviewTool } from './diagram-review-tool.js';
@@ -39,5 +40,37 @@ export function apply(ctx, config) {
39
40
  ctx.tools.register(diagramRenderTool);
40
41
  ctx.tools.register(diagramReviewTool);
41
42
  ctx.tools.register(diagramDiffTool);
43
+ registerAnnotateCommand(ctx);
44
+ }
45
+ /**
46
+ * Offer an annotation as a session command, so a page can send one without a composer.
47
+ *
48
+ * Optional on purpose, and failure-tolerant on purpose: a host without the commands service keeps the
49
+ * composer path, and a registration that throws must not take the drawing tools down with it.
50
+ */
51
+ export function registerAnnotateCommand(ctx) {
52
+ const commands = ctx.get?.('commands');
53
+ if (commands === undefined || typeof commands.register !== 'function')
54
+ return;
55
+ try {
56
+ commands.register({
57
+ name: 'annotate',
58
+ description: 'Send a diagram annotation to this session',
59
+ handler: (invocation) => {
60
+ const raw = typeof invocation.rawInput === 'string' ? invocation.rawInput.trim().replace(/^\/?annotate\s*/i, '') : '';
61
+ const agent = invocation.agent;
62
+ const followup = agent?.followup;
63
+ if (raw === '' || typeof followup !== 'function')
64
+ return { kind: 'error', text: 'this host cannot take a follow-up note' };
65
+ // A follow-up takes a UserMessage, not a bag of fields: the runtime stamps the id and the time, and a
66
+ // hand-built object reaches the inbox without them. `createUserMessage` is the host's own constructor.
67
+ followup.call(agent, createUserMessage({ content: [{ type: 'text', text: raw }], source: { kind: 'user' } }));
68
+ return { kind: 'success', text: 'annotation sent' };
69
+ },
70
+ });
71
+ }
72
+ catch {
73
+ // A host whose command API differs keeps the composer path; the tools above are already registered.
74
+ }
42
75
  }
43
76
  export const inject = ['tools'];
package/lib/gate.js CHANGED
@@ -10,13 +10,15 @@
10
10
  *
11
11
  * Why it is a separate row. The plugin's doctrine is that a capability is discoverable
12
12
  * through its own tool description or skill text. Injection departs from that, so it is
13
- * opt-in and mounted as its own component: install it, disable it, or never enable it,
14
- * without touching the tools or the skills. `enabled` is a live switch, so the Web Plugins
15
- * page flips it inside a running host.
13
+ * mounted as its own component: the bundle's patch enables it, and the row can be turned off
14
+ * or removed without touching the tools or the skills. `enabled` is a live switch, so the Web
15
+ * Plugins page flips it inside a running host.
16
16
  *
17
- * Why it is off by default. It costs tokens in every session that turns it on, to fix a
18
- * problem text-only routing was measured not to have once the session engages. A deployment
19
- * that wants it says so; the default pays nothing.
17
+ * Why the bundle turns it on. Measured: a session that never decides to load a skill is never
18
+ * routed, and the catalog line is cut at 500 characters, so a domain the request names can be
19
+ * invisible at the moment of choosing. The cost is a fixed message in every session, which is
20
+ * why the switch is live and documented: turn it off where the bundle's default is wrong. The
21
+ * component's own `enabled` script default is off, so a bare `app.add(gate)` injects nothing.
20
22
  *
21
23
  * What it does not do. It routes; it checks nothing. It cannot make a skill load, and it
22
24
  * does not restate the doctrine - the skill bodies carry that, and duplicating them here
@@ -91,9 +93,9 @@ export function renderGateText(skills = shippedSkills(), extraGuidance = '') {
91
93
  const rows = skills.map((skill) => '| ' + (SKILL_ROWS[skill] ?? 'see its catalog line') + ' | `' + skill + '` |');
92
94
  const extra = extraGuidance.trim();
93
95
  return `<EXTREMELY_IMPORTANT>
94
- Before answering anything about code, a design or a diagram: load the skill whose row matches and let its tool decide. Do not answer from memory.
96
+ Before answering anything about code, a design or a diagram: load the matching skill and let its tool decide. Do not answer from memory.
95
97
 
96
- dsh-model-everything is active: it checks claims about designs and code - facts against the source, behaviour as a model, structure as a graph.
98
+ dsh-model-everything checks claims about designs and code: facts against the source, behaviour as a model, structure as a graph.
97
99
 
98
100
  **Unsure which row applies?** Load \`model-everything\` first: it owns the doctrine, the schema and the routing to its siblings.
99
101
 
@@ -103,17 +105,19 @@ ${rows.join('\n')}
103
105
 
104
106
  **Tools** (dsh):
105
107
 
106
- - \`model_verify\` — one state machine: structural checks, adversarial probes, budgets, deadlines, regression.
107
- - \`model_compose_verify\` — two or more machines: deadlock, a rendezvous that never fires, and - with \`shared\` + \`accesses\` - an unordered write (C4) or a non-atomic update (C5).
108
- - \`model_datamodel_verify\` — a data model and its migration: keys, domains, coverage, copy consistency, rollback symmetry.
109
- - \`model_design_review\` — a design against its own declarations: layering, boundaries, substitutability, interface width. Graph shape is reported, not judged.
110
- - \`model_interleaving_scan\` — finds claims about threads, async and interrupts, names the family and routes each to what decides it. It proves nothing itself.
111
- - \`model_export\` — UPPAAL, TLA+, PRISM or SPIN input from a model. It exports; it does not check the target.
112
- - \`uml_render\`, \`uml_parse\`, \`uml_review\` — draw a model, read a diagram into one, audit one. Round-trip fidelity is measured.
113
- - \`uml_explain_labels\` — the accepted label and comment forms for one notation.
114
- - \`uml_structure_verify\` — dependency review of a structure drawing, one level or several. It audits the drawing, not the code.
115
- - \`diagram_render\`, \`diagram_review\`, \`diagram_diff\` — draw, size and compare a Mermaid or PlantUML source. Undrawable lines are refused by number.
116
- - \`report_diff\` — baseline against current: what a change added, removed or changed.
108
+ - \`model_verify\` — a state machine: structural checks, adversarial probes, budgets, deadlines, regression.
109
+ - \`model_compose_verify\` — several machines: deadlock, a handshake that never fires, an unordered write (C4), a non-atomic update (C5).
110
+ - \`model_datamodel_verify\` — a data model and its migration: keys, domains, coverage, copy consistency, rollback.
111
+ - \`model_design_review\` — a design against its own declarations: layering, boundaries, substitutability, interface width.
112
+ - \`model_interleaving_scan\` — finds concurrency claims, names the family, routes each to what decides it. Proves nothing itself.
113
+ - \`model_export\` — UPPAAL, TLA+, PRISM or SPIN input from a model. It does not check the target.
114
+ - \`uml_render\`, \`uml_parse\`, \`uml_review\` — draw a model, read a diagram into one, audit one; round-trip measured.
115
+ - \`uml_explain_labels\` — the label and comment forms a notation accepts.
116
+ - \`uml_structure_verify\` — dependency review of a structure drawing. It audits the drawing, not the code.
117
+ - \`diagram_render\`, \`diagram_review\`, \`diagram_diff\` — draw, size, compare a Mermaid or PlantUML source. Undrawable lines are refused by number.
118
+ - \`model_automaton_verify\` — an automaton or two: what it accepts, trap states, language relation, with a witness word.
119
+ - \`model_edit\` — one named change to a model file plus the finding delta. Refuses an edit that leaves the model invalid.
120
+ - \`report_diff\` — baseline against current: findings added, removed or changed.
117
121
 
118
122
  **Read a report**: gate on \`verdict\`, never on \`ok\`. \`verdictReason\` says why and \`nextSteps\` says what to do. \`ran\` says whether it executed, \`checksRun\` how much it examined: a \`skip\` is not a \`pass\`, and a code ending \`_UNDECIDED\` means the search hit its limit and decided nothing. Keys starting with \`_\` are notes: ignored, and left out of the model hash.
119
123
 
@@ -366,6 +366,7 @@ export function paintWith(diagram, overrides = {}, options = {}) {
366
366
  const text = textOf(node);
367
367
  shapes.push({
368
368
  kind: 'box',
369
+ id: node.id,
369
370
  x: box.x,
370
371
  y: box.y,
371
372
  width: box.width,
@@ -1335,6 +1336,8 @@ export function paintWith(diagram, overrides = {}, options = {}) {
1335
1336
  const width = Math.max(contentRight + MARGIN, captionWidth, 240);
1336
1337
  const contentBottom = Math.max(topOffset, ...Array.from(boxes.values(), (box) => box.y + box.height), ...Array.from(groupRects.values(), (rect) => rect.y + rect.height));
1337
1338
  const captionTop = contentBottom + CAPTION_GAP;
1339
+ // Anchored at the left margin, where the title is. The writer starts the text there: centred on a left-edge x,
1340
+ // half of a long caption fell outside the drawing and was clipped at the bottom edge of the picture.
1338
1341
  shapes.push({ kind: 'caption', x: MARGIN, y: captionTop, lines: captionLines, colour: captionRole(diagram.caption) });
1339
1342
  const height = captionTop + captionLines.length * CAPTION_LINE + MARGIN / 2;
1340
1343
  // Everything drawn counts, including the parts that leave the box grid: an edge routed beside the drawing and a
package/lib/render/svg.js CHANGED
@@ -115,7 +115,9 @@ const writers = {
115
115
  const lines = shape.lines
116
116
  .map((line, index) => '<tspan x="' + n(shape.x) + '" dy="' + (index === 0 ? 0 : 15) + '">' + escape(line) + '</tspan>')
117
117
  .join('');
118
- return '<text x="' + n(shape.x) + '" y="' + n(shape.y + 11) + '" font-size="10" text-anchor="middle" fill="' + colour + '">' + lines + '</text>';
118
+ // Start-anchored: the caption begins at the margin the title uses, so a long one grows right into the space
119
+ // the canvas has already reserved for it instead of hanging off the left edge.
120
+ return '<text x="' + n(shape.x) + '" y="' + n(shape.y + 11) + '" font-size="10" fill="' + colour + '">' + lines + '</text>';
119
121
  },
120
122
  };
121
123
  /** The dash pattern a route's source stated, or nothing for a solid line. */
@@ -218,7 +220,11 @@ export function toSvg(canvas, colours, label) {
218
220
  dropped += 1;
219
221
  continue;
220
222
  }
221
- body.push(writer(shape, colours));
223
+ const drawn = writer(shape, colours);
224
+ // A node carries its id in the markup, so a card or a board can target one node by delegation, the way a
225
+ // boundary already carries `data-group-id`, instead of working it out from the click's geometry.
226
+ const nodeId = shape.id;
227
+ body.push(shape.kind === 'box' && typeof nodeId === 'string' ? '<g data-node-id="' + escape(nodeId) + '">' + drawn + '</g>' : drawn);
222
228
  }
223
229
  const header = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ' + n(canvas.width) + ' ' + n(canvas.height) +
224
230
  '" width="' + n(canvas.width) + '" height="' + n(canvas.height) + '" role="img"' +
package/lib/routing.js CHANGED
@@ -70,6 +70,18 @@ export const ROUTES = {
70
70
  owns: 'a dependency graph as a graph - cycles, layers, dangling edges - from a drawing or a source tree',
71
71
  notFor: { when: 'the question is a rule the design declared for itself, not an edge that exists', tool: 'model_design_review' },
72
72
  },
73
+ diagram_render: {
74
+ owns: 'one drawing: source text in, a laid-out SVG out, every refused line named',
75
+ notFor: { when: 'the drawing has to fit a budget or a pane before a reader sees it', tool: 'diagram_review' },
76
+ },
77
+ diagram_review: {
78
+ owns: 'the structure of one drawing against budgets: boundary width, nesting depth, node count',
79
+ notFor: { when: 'the diagram has to be read as a model, and its modelling judged', tool: 'uml_review' },
80
+ },
81
+ diagram_diff: {
82
+ owns: 'what moved between two drawings: boundaries added, removed, renamed or re-parented',
83
+ notFor: { when: 'two reports have to be compared rather than two drawings', tool: 'report_diff' },
84
+ },
73
85
  };
74
86
  /** The route for a tool, or undefined when the tool has none. */
75
87
  export function routeFor(tool) {
@@ -0,0 +1,327 @@
1
+ /**
2
+ * What an annotation message looks like after it has been sent.
3
+ *
4
+ * The message is one block of plain lines: a fixed opening, numbered items, a question line, then the reader's
5
+ * own words. That is the right thing for the model and the wrong thing to read as a human - the reader wrote one
6
+ * note about one node, and what landed is a page of protocol.
7
+ *
8
+ * The host renders a user message as text inside elements it owns and re-renders. So this never assigns an
9
+ * element's text: that deletes its children, React reconciles from a tree that no longer matches, and whole
10
+ * turns come back mangled. It edits the text NODES instead - trim the run before the cut, remove the runs that
11
+ * held the block - and puts the chip in as a sibling, exactly the way the shipped annotation plugin does it.
12
+ *
13
+ * Everything here is defensive: a page without the elements, an element without text nodes, an element already
14
+ * handled. A decorator that throws would take a render pass with it.
15
+ */
16
+ /** The first words of every annotation block, used to recognise one in the transcript. */
17
+ export const TRANSCRIPT_MARKER = 'Diagram annotations -';
18
+ /** Where the block hands over to the reader's own question. */
19
+ const QUESTION = 'Question:';
20
+ /** Marks an element the decorator has handled, and remembers the block it came from. */
21
+ const HANDLED = 'data-dme-annotated';
22
+ const ORIGINAL = 'data-dme-annotation-text';
23
+ /** Elements whose text can be the message. Nested containers are excluded by the descendant test below. */
24
+ const SELECTOR = 'div, p, span, li';
25
+ /**
26
+ * Another plugin's territory, which this one must never touch.
27
+ *
28
+ * The shipped annotation plugin marks its own nodes `data-annotation-*` and folds its own blocks by their own
29
+ * markers. Two plugins doing DOM work in the same transcript collide in exactly three ways: they fight over the
30
+ * same message element, they overwrite each other's chip, and they both react to the other's mutations. The
31
+ * rules this file follows, and that a future change here has to keep:
32
+ *
33
+ * 1. only our own marker starts work - `Diagram annotations -`, never a generic word like "annotation";
34
+ * 2. every attribute we add is `data-dme-*`, and anything already carrying `data-annotation-*` is skipped;
35
+ * 3. our inserted nodes carry `data-dme-own`, so a neighbouring plugin can skip them as easily as we skip its;
36
+ * 4. one pass over a message, marked, so a second plugin's re-render cannot make us fold the same block twice.
37
+ *
38
+ * The draft is the fourth surface: both plugins write it through the host's `setDraft`, and a blind overwrite
39
+ * would drop the other's block. `placeBlock` re-reads the draft immediately before writing and prepends,
40
+ * keeping the rest verbatim - never a replace.
41
+ */
42
+ const FOREIGN = '[data-annotation-for-dsh], [data-annotation-overlay], [data-annotation-chip], [data-annotation-tip-layer]';
43
+ const BORDER = '1px solid var(--dsw-alias-border-l1, rgba(127,127,127,0.35))';
44
+ /** The count in the opening line, for the chip; null when the line says something unexpected. */
45
+ export function annotationCountOf(text) {
46
+ const found = /Diagram annotations - (\d+)/.exec(text);
47
+ return found === null ? null : Number(found[1]);
48
+ }
49
+ /** The reader's own words: what follows the question line, or nothing when the note was the whole message. */
50
+ export function questionOf(text) {
51
+ const at = text.lastIndexOf(QUESTION);
52
+ return at === -1 ? '' : text.slice(at + QUESTION.length).trim();
53
+ }
54
+ /** The notes the block carries, read back out of its lines, so a reader sees what the model saw. */
55
+ export function itemsOf(text) {
56
+ const items = [];
57
+ for (const raw of text.split(String.fromCharCode(10))) {
58
+ const line = raw.trim();
59
+ const head = /^Diagram note \[(\d+)\] node (.+)$/.exec(line);
60
+ if (head !== null) {
61
+ const rest = head[2];
62
+ const dash = rest.lastIndexOf(' - ');
63
+ items.push({ index: Number(head[1]), node: dash === -1 ? rest : rest.slice(0, dash), note: dash === -1 ? '' : rest.slice(dash + 3) });
64
+ continue;
65
+ }
66
+ const note = /^Note: (.*)$/.exec(line);
67
+ if (note !== null && items.length > 0)
68
+ items[items.length - 1].note = note[1];
69
+ }
70
+ return items;
71
+ }
72
+ /** Every text node inside an element, in document order. */
73
+ function textNodesOf(root) {
74
+ const out = [];
75
+ const visit = (node) => {
76
+ const children = node.childNodes;
77
+ if (children === undefined || children === null || children.length === 0) {
78
+ if (typeof node.nodeValue === 'string')
79
+ out.push(node);
80
+ return;
81
+ }
82
+ for (let index = 0; index < children.length; index += 1)
83
+ visit(children[index]);
84
+ };
85
+ visit(root);
86
+ return out;
87
+ }
88
+ /**
89
+ * Drop everything before the cut from the text nodes, and leave the reader's own words.
90
+ *
91
+ * The nodes are the only thing written: an element's `textContent` would take its child elements with it.
92
+ */
93
+ export function cutTextNodes(nodes, cut) {
94
+ let position = 0;
95
+ let done = false;
96
+ for (const node of nodes) {
97
+ const value = typeof node.nodeValue === 'string' ? node.nodeValue : '';
98
+ const length = value.length;
99
+ if (done) {
100
+ position += length;
101
+ continue;
102
+ }
103
+ if (cut <= position + length) {
104
+ node.nodeValue = value.slice(cut - position).replace(/^\s+/, '');
105
+ done = true;
106
+ }
107
+ else {
108
+ node.nodeValue = '';
109
+ }
110
+ position += length;
111
+ }
112
+ return done;
113
+ }
114
+ /** Whether another plugin owns this node, or any of its ancestors. */
115
+ /**
116
+ * Whether this element IS another plugin's node.
117
+ *
118
+ * Only the element itself counts. An ancestor test looked safer and was wrong: that plugin marks the message
119
+ * container it has folded, so every message it touched also carried an ancestor marker - and this plugin then
120
+ * skipped the very message it was looking for.
121
+ */
122
+ function isForeign(node) {
123
+ for (const name of ['data-annotation-for-dsh', 'data-annotation-overlay', 'data-annotation-chip', 'data-annotation-tip-layer']) {
124
+ const value = node.getAttribute?.(name);
125
+ if (value !== undefined && value !== null)
126
+ return true;
127
+ }
128
+ return false;
129
+ }
130
+ /** Kept for the tests that assert the selector exists; the ancestor walk is deliberately not used. */
131
+ export const FOREIGN_SELECTOR = FOREIGN;
132
+ function holdsAnotherBlock(node) {
133
+ const inner = node.querySelectorAll?.(SELECTOR);
134
+ if (inner === undefined || inner === null)
135
+ return false;
136
+ for (let index = 0; index < inner.length; index += 1) {
137
+ const text = inner[index].textContent;
138
+ if (typeof text === 'string' && text.indexOf(TRANSCRIPT_MARKER) !== -1)
139
+ return true;
140
+ }
141
+ return false;
142
+ }
143
+ /** The card listing the notes, styled from the host's tokens so it reads as part of the page. */
144
+ function cardFor(doc, items, title, full) {
145
+ const card = doc.createElement?.('div');
146
+ if (card === undefined)
147
+ return undefined;
148
+ styleOf(card, {
149
+ position: 'fixed', zIndex: '40', display: 'none', maxWidth: '360px', padding: '8px 10px', borderRadius: '10px',
150
+ background: 'var(--dsw-alias-bg-overlay, var(--dsw-alias-bg-layer-1, Canvas))',
151
+ border: BORDER, boxShadow: '0 10px 30px rgba(0,0,0,0.28)',
152
+ color: 'var(--dsw-alias-label-primary, CanvasText)', font: '12px system-ui, sans-serif',
153
+ });
154
+ const head = doc.createElement?.('div');
155
+ if (head !== undefined) {
156
+ head.textContent = title;
157
+ styleOf(head, {
158
+ color: 'var(--dsw-alias-label-secondary, GrayText)', paddingBottom: '6px', marginBottom: '4px',
159
+ borderBottom: BORDER, fontSize: '11px',
160
+ });
161
+ card.appendChild?.(head);
162
+ }
163
+ for (const item of items) {
164
+ const row = doc.createElement?.('div');
165
+ if (row === undefined)
166
+ continue;
167
+ styleOf(row, { display: 'flex', gap: '6px', alignItems: 'flex-start', padding: '3px 0' });
168
+ const badge = doc.createElement?.('span');
169
+ if (badge !== undefined) {
170
+ badge.textContent = String(item.index);
171
+ styleOf(badge, {
172
+ flex: '0 0 auto', width: '16px', height: '16px', lineHeight: '16px', textAlign: 'center',
173
+ borderRadius: '8px', fontSize: '10px',
174
+ background: 'var(--dsw-alias-brand-primary, #2563eb)', color: '#fff',
175
+ });
176
+ row.appendChild?.(badge);
177
+ }
178
+ const body = doc.createElement?.('div');
179
+ if (body !== undefined) {
180
+ body.textContent = item.node + (item.note === '' ? '' : String.fromCharCode(10) + item.note);
181
+ styleOf(body, { flex: '1 1 auto', whiteSpace: 'pre-wrap', wordBreak: 'break-word' });
182
+ row.appendChild?.(body);
183
+ }
184
+ card.appendChild?.(row);
185
+ }
186
+ const more = doc.createElement?.('div');
187
+ if (more !== undefined) {
188
+ more.textContent = full;
189
+ styleOf(more, {
190
+ display: 'none', marginTop: '6px', paddingTop: '6px', borderTop: BORDER, fontSize: '11px',
191
+ whiteSpace: 'pre-wrap', color: 'var(--dsw-alias-label-secondary, GrayText)', maxHeight: '40vh', overflow: 'auto',
192
+ });
193
+ card.appendChild?.(more);
194
+ }
195
+ return card;
196
+ }
197
+ /**
198
+ * Apply a style map to a real element.
199
+ *
200
+ * Assigning an object to element.style applies nothing on a real element - the browser keeps its own
201
+ * CSSStyleDeclaration - which is why a chip built that way rendered as plain words. Each property goes through
202
+ * setProperty; a fake node without one keeps the map so a test can read it back.
203
+ */
204
+ function styleOf(node, map) {
205
+ const decl = node.style;
206
+ if (typeof decl?.setProperty === 'function') {
207
+ const target = decl;
208
+ for (const key of Object.keys(map)) {
209
+ const value = map[key];
210
+ if (value === undefined)
211
+ continue;
212
+ target.setProperty(key.replace(/[A-Z]/g, (letter) => '-' + letter.toLowerCase()), value);
213
+ }
214
+ return;
215
+ }
216
+ node.style = map;
217
+ }
218
+ function chipFor(doc, label, title, text) {
219
+ const chip = doc.createElement?.('div');
220
+ if (chip === undefined)
221
+ return undefined;
222
+ chip.textContent = label;
223
+ chip.setAttribute?.('role', 'button');
224
+ // A pill that sits in the reader's line, not a block that pushes it: the conversation is theirs, and the chip
225
+ // is a footnote to it.
226
+ styleOf(chip, {
227
+ display: 'inline-flex', alignItems: 'center', height: '20px', padding: '0 8px', margin: '4px 0 0',
228
+ fontSize: '11px', lineHeight: '20px', borderRadius: '10px', verticalAlign: 'middle', userSelect: 'none',
229
+ border: BORDER, background: 'var(--dsw-alias-bg-layer-2, rgba(127,127,127,0.10))',
230
+ color: 'var(--dsw-alias-label-secondary, GrayText)', cursor: 'pointer', maxWidth: '100%',
231
+ });
232
+ const card = cardFor(doc, itemsOf(text), title, text);
233
+ if (card === undefined)
234
+ return chip;
235
+ const place = () => {
236
+ const box = chip.getBoundingClientRect?.();
237
+ styleOf(card, box === undefined
238
+ ? { display: 'block' }
239
+ : { display: 'block', left: String(Math.max(8, box.left)) + 'px', top: String(box.top + box.height + 6) + 'px' });
240
+ };
241
+ const hide = () => { styleOf(card, { display: 'none' }); };
242
+ chip.addEventListener?.('mouseenter', place);
243
+ chip.addEventListener?.('mouseleave', hide);
244
+ chip.addEventListener?.('click', () => {
245
+ if ((card.style ?? {}).display === 'block') {
246
+ hide();
247
+ }
248
+ else {
249
+ place();
250
+ }
251
+ });
252
+ // The card travels with the chip, so a bubble that re-renders cannot leave one behind.
253
+ chip.appendChild?.(card);
254
+ return chip;
255
+ }
256
+ /**
257
+ * Fold every annotation message in the transcript behind its count, and answer how many were folded.
258
+ *
259
+ * Idempotent: an element that already carries the marker is skipped, so the observer can call this on every
260
+ * change without stacking chips. Only the element whose text is the message is touched, and only its text nodes.
261
+ */
262
+ export function decorateTranscript(doc, label = 'Notes', title = 'Notes in this message') {
263
+ if (doc === undefined || typeof doc.querySelectorAll !== 'function')
264
+ return 0;
265
+ let nodes;
266
+ try {
267
+ nodes = doc.querySelectorAll(SELECTOR);
268
+ }
269
+ catch {
270
+ return 0;
271
+ }
272
+ let folded = 0;
273
+ for (let index = 0; index < nodes.length; index += 1) {
274
+ const element = nodes[index];
275
+ const text = typeof element.textContent === 'string' ? element.textContent : '';
276
+ if (!text.includes(TRANSCRIPT_MARKER))
277
+ continue;
278
+ if (element.getAttribute?.(HANDLED) === '1')
279
+ continue;
280
+ // Another plugin's node: it may be folding its own block in the same message, and two folders would take
281
+ // turns rewriting each other's text.
282
+ if (isForeign(element))
283
+ continue;
284
+ if (holdsAnotherBlock(element))
285
+ continue;
286
+ const texts = textNodesOf(element);
287
+ if (texts.length === 0)
288
+ continue;
289
+ const joined = texts.map((node) => (typeof node.nodeValue === 'string' ? node.nodeValue : '')).join('');
290
+ if (!joined.includes(TRANSCRIPT_MARKER))
291
+ continue;
292
+ const at = joined.lastIndexOf(QUESTION);
293
+ const cut = at === -1 ? joined.length : at + QUESTION.length;
294
+ const count = annotationCountOf(joined);
295
+ const chip = chipFor(doc, label + (count === null ? '' : ' ×' + String(count)), title, joined);
296
+ if (chip === undefined)
297
+ continue;
298
+ try {
299
+ if (!cutTextNodes(texts, cut))
300
+ continue;
301
+ element.setAttribute?.(ORIGINAL, joined);
302
+ element.setAttribute?.(HANDLED, '1');
303
+ const parent = element.parentNode;
304
+ if (parent?.insertBefore !== undefined)
305
+ parent.insertBefore(chip, element.nextSibling ?? null);
306
+ else
307
+ element.appendChild?.(chip);
308
+ folded += 1;
309
+ }
310
+ catch {
311
+ // A page that refuses the write keeps the plain message, which reads on its own.
312
+ }
313
+ }
314
+ return folded;
315
+ }
316
+ /**
317
+ * One pass, and nothing that keeps running.
318
+ *
319
+ * There is deliberately no observer and no timer here. Both were tried: an observer over the document plus a
320
+ * one-second interval turns every DOM change into a full selector scan, and a streaming conversation changes the
321
+ * DOM many times a second - the container stopped responding. A caller that wants the fold has to decide when
322
+ * to run it, on a container it chose.
323
+ */
324
+ export function startTranscriptDecoration(doc, label = 'Notes', title = 'Notes in this message') {
325
+ decorateTranscript(doc, label, title);
326
+ return () => { };
327
+ }