truemap-cli 0.5.2 → 0.5.3

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/kit/tokens.css CHANGED
@@ -19,6 +19,7 @@
19
19
  --tm-pencil: #9a9a92; /* hints */
20
20
  --tm-rule: #e6e6e1;
21
21
  --tm-rule-strong: #d2d2cb;
22
+ --tm-wire: #989892; /* wires at rest: about 2.6:1 on a group, 2.9:1 on the page; the main path is ink */
22
23
  --tm-accent: #141413; /* the primary action; the project's own colour when truemap finds one */
23
24
  --tm-accent-text: #ffffff; /* text on the accent */
24
25
  --tm-chrome: #fafaf9; /* the workspace bars and panel */
@@ -50,6 +51,7 @@
50
51
  --tm-pencil: #75756e;
51
52
  --tm-rule: #2f2f2c;
52
53
  --tm-rule-strong: #44443f;
54
+ --tm-wire: #62625c;
53
55
  --tm-accent: #f2f2ee;
54
56
  --tm-accent-text: #141413;
55
57
  --tm-chrome: #1b1b1a;
package/kit/truemap.css CHANGED
@@ -89,10 +89,10 @@ html[style*="--tm-vw"] .tm-map, html[style*="--tm-vw"] .tm-blueprint { width: ca
89
89
  /* Wires (drawn by truemap into svg.tm-wires) */
90
90
  .tm-wires { position: absolute; top: 0; left: 0; max-width: none; pointer-events: none; overflow: visible; z-index: 0; }
91
91
  /* Quiet by default: the main path is the only strong line. Hover a box and its own wires come forward. */
92
- .tm-wire { fill: none; stroke: var(--tm-rule-strong); stroke-width: 1.25; }
92
+ .tm-wire { fill: none; stroke: var(--tm-wire, var(--tm-rule-strong)); stroke-width: 1.25; }
93
93
  .tm-wire.is-key { stroke: var(--tm-route); stroke-width: 2; }
94
94
  .tm-wire.is-ext { stroke-dasharray: 4 4; }
95
- .tm-wire-head { fill: var(--tm-rule-strong); }
95
+ .tm-wire-head { fill: var(--tm-wire, var(--tm-rule-strong)); }
96
96
  .tm-wire-head.is-key { fill: var(--tm-route); }
97
97
  /* Labels: the main path's always show; any other wire's label shows when its box is hovered or its path is lit. */
98
98
  .tm-wire-label { font: 500 11.5px var(--tm-font); fill: var(--tm-pencil); paint-order: stroke; stroke: var(--tm-paper); stroke-width: 6px; stroke-linejoin: round; opacity: 0; transition: opacity .15s ease; }
@@ -122,8 +122,8 @@ html[data-tm-focusing] .tm-wire-label:not(.is-focus) { opacity: 0; }
122
122
  .tm-legend { display: flex; flex-wrap: wrap; gap: 6px 22px; margin: 22px 0 0 132px; font-size: 13px; color: var(--tm-graphite); }
123
123
  .tm-legend span { display: inline-flex; align-items: center; gap: 8px; }
124
124
  .tm-legend i { display: inline-block; width: 22px; height: 0; border-top: 2px solid var(--tm-route); }
125
- .tm-legend i.is-wire { border-top: 1.5px solid var(--tm-rule-strong); }
126
- .tm-legend i.is-ext { border-top: 1.5px dashed var(--tm-rule-strong); }
125
+ .tm-legend i.is-wire { border-top: 1.5px solid var(--tm-wire, var(--tm-rule-strong)); }
126
+ .tm-legend i.is-ext { border-top: 1.5px dashed var(--tm-wire, var(--tm-rule-strong)); }
127
127
  .tm-legend span:has(> i.is-mark) { display: none; } /* older pages: the corner mark is gone */
128
128
 
129
129
  /* ---------- flow: a real sequence ---------- */
@@ -255,6 +255,7 @@ pre { font-family: var(--tm-code); font-size: 13px; line-height: 1.6; background
255
255
  /* ===================== diagrams (v0.5): small nodes in groups, laid out left to right ===================== */
256
256
  .tm-diagram {
257
257
  --dg-bg: var(--tm-paper); --dg-surface: var(--tm-wash); --dg-line: var(--tm-rule); --dg-line-strong: var(--tm-rule-strong);
258
+ --dg-wire: var(--tm-wire, var(--tm-rule-strong));
258
259
  --dg-muted: var(--tm-graphite); --dg-text: var(--tm-text); --dg-ink: var(--tm-ink); --dg-mark: var(--tm-mark);
259
260
  --dg-font: var(--tm-font); --dg-code: var(--tm-code);
260
261
  position: relative; margin: 20px 0 8px; font-family: var(--dg-font);
@@ -279,18 +280,26 @@ pre { font-family: var(--tm-code); font-size: 13px; line-height: 1.6; background
279
280
  .tm-diagram .tm-node.is-ext { background: var(--dg-bg); border-style: dashed; border-color: var(--dg-line-strong); }
280
281
  .tm-diagram .tm-node.is-ext .tm-dg-name { color: var(--dg-muted); }
281
282
  .tm-diagram .tm-detail { display: none; }
282
- .tm-dg-edge { fill: none; stroke: var(--dg-line-strong); stroke-width: 1.25; }
283
+ .tm-dg-edge { fill: none; stroke: var(--dg-wire); stroke-width: 1.25; }
283
284
  .tm-dg-edge.is-main { stroke: var(--dg-ink); stroke-width: 1.6; }
284
285
  .tm-dg-edge.is-ext { stroke-dasharray: 3 4; }
285
- .tm-dg-head { fill: var(--dg-line-strong); }
286
+ .tm-dg-head { fill: var(--dg-wire); }
286
287
  .tm-dg-head.is-main { fill: var(--dg-ink); }
287
288
  .tm-dg-edge.is-hot, .tm-dg-edge.is-flow { stroke: var(--dg-ink); stroke-width: 1.75; }
288
289
  .tm-dg-head.is-hot, .tm-dg-head.is-flow { fill: var(--dg-ink); }
289
290
  .tm-dg-label { position: absolute; z-index: 3; transform: translate(-50%, -50%); font: 400 11px/1.3 var(--dg-code); color: var(--dg-muted); background: var(--dg-bg); padding: 1px 4px; border-radius: 4px; white-space: nowrap; pointer-events: none; }
290
291
  .tm-dg-group ~ .tm-dg-label { background: var(--dg-bg); }
291
292
  .tm-dg-label.is-hot, .tm-dg-label.is-flow { color: var(--dg-ink); }
292
- /* at rest only the main path says its verbs; a hovered or selected box, a lit path or a flow shows the rest */
293
- .tm-dg-label:not(.is-main):not(.is-hot):not(.is-flow):not(.is-focus):not(.is-sel), .tm-dg-label.is-dup:not(.is-flow):not(.is-focus), .tm-dg-label.is-crowded:not(.is-hot):not(.is-flow):not(.is-focus):not(.is-sel) { visibility: hidden; }
293
+ /* at rest the main path says its verbs, and so does any other line whose label found a clean spot (is-rest);
294
+ a hovered or selected box, a lit path or a flow shows the rest, and then only its own lines speak */
295
+ .tm-dg-label:not(.is-main):not(.is-rest):not(.is-hot):not(.is-flow):not(.is-focus):not(.is-sel),
296
+ .tm-diagram[data-flow] .tm-dg-label.is-rest:not(.is-flow):not(.is-sel):not(.is-hot), html[data-tm-focusing] .tm-dg-label.is-rest:not(.is-focus):not(.is-sel):not(.is-hot),
297
+ html[data-tm-changes] .tm-dg-label.is-rest:not(.is-hot):not(.is-flow):not(.is-sel), .tm-dg-label.is-dup:not(.is-flow):not(.is-focus):not(.is-sel), .tm-dg-label.is-crowded:not(.is-hot):not(.is-flow):not(.is-focus):not(.is-sel) { visibility: hidden; }
298
+ /* own rule: a browser without :has() drops only this one */
299
+ .tm-diagram:has([data-tm-selected]) .tm-dg-label.is-rest:not(.is-sel):not(.is-hot) { visibility: hidden; }
300
+ /* one word said once for several edges carries a count at rest; a lit edge says only its own word */
301
+ .tm-dg-label[data-many]::after { content: attr(data-many); margin-left: .4em; }
302
+ .tm-dg-label.is-sel[data-many]::after, .tm-dg-label.is-flow[data-many]::after, .tm-dg-label.is-focus[data-many]::after { content: none; }
294
303
  .tm-dg-edge.is-sel { stroke: var(--dg-ink); stroke-width: 1.75; }
295
304
  .tm-dg-head.is-sel { fill: var(--dg-ink); }
296
305
  .tm-dg-label.is-sel { color: var(--dg-ink); }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "truemap-cli",
3
- "version": "0.5.2",
3
+ "version": "0.5.3",
4
4
  "description": "Agents explain your project with living HTML pages that stay true to the code. Click, ask, and decide right on the page.",
5
5
  "repository": {
6
6
  "type": "git",
package/src/changes.js CHANGED
@@ -14,7 +14,7 @@ import { copyFileSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
14
14
  import { tmpdir } from 'node:os';
15
15
  import { join } from 'node:path';
16
16
  import { FOLDER, gitExe } from './common.js';
17
- import { extractAnchors, listPages, parseAnchor } from './check.js';
17
+ import { anchorTags, attrOf, extractAnchors, listPages, parseAnchor } from './check.js';
18
18
 
19
19
  function git(root, args, env) {
20
20
  const exe = gitExe();
@@ -50,7 +50,9 @@ async function mainBase(root) {
50
50
  }
51
51
 
52
52
  export async function resolveBase(root, kind, snapshots = {}) {
53
- const want = kind && kind !== 'auto' ? kind : snapshots.plan ? 'plan' : snapshots.turn ? 'turn' : 'head';
53
+ // auto: the plan while it is being built and in the turn that closed it; after that, the turn
54
+ const closedEarlier = snapshots.plan && snapshots.planEnd?.slug === snapshots.plan.slug && snapshots.turn && snapshots.planEnd.at < snapshots.turn.at;
55
+ const want = kind && kind !== 'auto' ? kind : snapshots.plan && !closedEarlier ? 'plan' : snapshots.turn ? 'turn' : 'head';
54
56
  if (want === 'plan' && snapshots.plan) {
55
57
  const end = snapshots.planEnd?.slug === snapshots.plan.slug ? snapshots.planEnd : null;
56
58
  return { kind: 'plan', tree: snapshots.plan.tree, to: end?.tree, at: snapshots.plan.at, label: end ? 'What was done for the plan' : 'Since you approved the plan' };
@@ -98,18 +100,18 @@ export function attribute(root, files) {
98
100
  if (path) anchors.push({ page, src, path, own: true });
99
101
  }
100
102
  // data-also="server/db.ts server/hub.ts": more files a box owns (its migration, its wiring)
101
- for (const m of html.matchAll(/<[^>]*\sdata-src\s*=\s*["']([^"']+)["'][^>]*>/gi)) {
102
- const also = m[0].match(/\sdata-also\s*=\s*["']([^"']*)["']/i)?.[1];
103
- for (const p of (also || '').split(/[\s,]+/).filter(Boolean)) anchors.push({ page, src: m[1], path: p.replace(/^\.?\//, '') });
103
+ for (const { tag, src } of anchorTags(html)) {
104
+ const also = attrOf(tag, 'data-also');
105
+ for (const p of (also || '').split(/[\s,]+/).filter(Boolean)) anchors.push({ page, src, path: p.replace(/^\.?\//, '') });
104
106
  }
105
107
  }
106
108
  const names = new Map();
107
109
  for (const { page } of pages) {
108
110
  let html = '';
109
111
  try { html = readFileSync(join(root, FOLDER, page), 'utf8'); } catch { continue; }
110
- for (const m of html.matchAll(/<[^>]*\sdata-src\s*=\s*["']([^"']+)["'][^>]*>/gi)) {
111
- const nm = m[0].match(/\sdata-name\s*=\s*["']([^"']+)["']/i)?.[1];
112
- if (nm && !names.has(m[1])) names.set(m[1], nm);
112
+ for (const { tag, src } of anchorTags(html)) {
113
+ const nm = attrOf(tag, 'data-name');
114
+ if (nm && !names.has(src)) names.set(src, nm);
113
115
  }
114
116
  }
115
117
  const boxes = new Map(); // src -> { src, pages:Set, files:[] }
package/src/check.js CHANGED
@@ -10,7 +10,6 @@ import { createHash } from 'node:crypto';
10
10
  import { FOLDER, gitExe, verifiedPath } from './common.js';
11
11
 
12
12
  const META_RE = /<meta\s+name=["']truemap-verified["']\s+content=["']([^"']*)["']\s*\/?>/i;
13
- const ANCHOR_RE = /\bdata-src\s*=\s*(?:"([^"]*)"|'([^']*)')/gi;
14
13
  const TITLE_RE = /<title[^>]*>([\s\S]*?)<\/title>/i;
15
14
  const MAX_SCAN_BYTES = 4 * 1024 * 1024;
16
15
 
@@ -69,13 +68,35 @@ function decodeEntities(s) {
69
68
  return s.replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&#39;/g, "'");
70
69
  }
71
70
 
72
- export function extractAnchors(html) {
73
- const seen = new Set();
74
- for (const m of html.matchAll(ANCHOR_RE)) {
75
- const v = decodeEntities((m[1] ?? m[2] ?? '').trim());
76
- if (v) seen.add(v);
71
+ // Start tags of real elements only. Comments, raw text (script, style, textarea, title) and what is inside
72
+ // <pre> and <code> are text, and so is an escaped sample (&lt;div data-src=…&gt;): a draft that shows
73
+ // `data-src="src/server.js#start"` as an example must not be checked as an anchor.
74
+ const TAG_RE = /<[a-zA-Z][\w:-]*(?:[^>"']|"[^"]*"|'[^']*')*>/g;
75
+ const ATTR_RE = /\s([^\s"'>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
76
+ function elementTags(html) {
77
+ const text = html
78
+ .replace(/<!--[\s\S]*?(?:-->|$)/g, ' ')
79
+ .replace(/<(script|style|textarea|title|pre|code)\b((?:[^>"']|"[^"]*"|'[^']*')*)>[\s\S]*?<\/\1\s*>/gi, (_m, t, a) => `<${t}${a}>`);
80
+ return text.match(TAG_RE) || [];
81
+ }
82
+ export function attrOf(tag, name) {
83
+ const body = tag.replace(/^<[a-zA-Z][\w:-]*/, '');
84
+ for (const m of body.matchAll(ATTR_RE)) if (m[1].toLowerCase() === name) return decodeEntities(m[2] ?? m[3] ?? m[4] ?? '');
85
+ return null;
86
+ }
87
+
88
+ /** The start tags that carry a data-src, with that value: { tag, src }. */
89
+ export function anchorTags(html) {
90
+ const out = [];
91
+ for (const tag of elementTags(html)) {
92
+ const v = attrOf(tag, 'data-src');
93
+ if (v !== null && v.trim()) out.push({ tag, src: v.trim() });
77
94
  }
78
- return [...seen];
95
+ return out;
96
+ }
97
+
98
+ export function extractAnchors(html) {
99
+ return [...new Set(anchorTags(html).map((a) => a.src))];
79
100
  }
80
101
 
81
102
  export function parseAnchor(raw) {
@@ -283,6 +304,11 @@ export function checkLayout(html) {
283
304
  return notes.concat(lintDiagrams(html));
284
305
  }
285
306
 
307
+ // Most boxes one box may wire to. A map has 7-12 boxes; 5 targets is already half of a 10-box map and
308
+ // as many as a full group (5) holds. Past that the wires leave one side of the box together, their curves
309
+ // overlap into one bundle and their labels collide, so no single connection can be followed.
310
+ const MAX_FANOUT = 5;
311
+
286
312
  /** The rules of a v0.5 map (figure.tm-diagram), checked so a page that breaks them is told why. */
287
313
  export function lintDiagrams(html) {
288
314
  const notes = [];
@@ -300,6 +326,28 @@ export function lintDiagrams(html) {
300
326
  const label = sec[0].match(/data-label=["']([^"']+)/)?.[1] || 'a group';
301
327
  if (n > 5) notes.push(`${where}group "${label}" has ${n} boxes; keep a group to 5 or fewer (split it by responsibility) so it reads as one row.`);
302
328
  }
329
+ if (groups > 5) notes.push(`${where}${groups} groups; 3-5 read at a glance. Merge a small group into the neighbour with the same responsibility, or give a part its own page.`);
330
+ // Connections as the map draws them: data-to on a box, to another box on this map, once per pair.
331
+ const out = new Map(); const wired = new Set();
332
+ for (const t of nodes) {
333
+ const from = attr(t, 'id');
334
+ if (!from) continue;
335
+ const to = new Set((attr(t, 'data-to') || '').split(/[\s,]+/).filter(Boolean).map((s) => s.split(':')[0]).filter((x) => x !== from && ids.has(x)));
336
+ out.set(from, to);
337
+ if (to.size) wired.add(from);
338
+ for (const x of to) wired.add(x);
339
+ }
340
+ if (nodes.length > 1 && !wired.size) notes.push(`${where}no connections. Give each box data-to="id:verb" for what it calls or feeds.`);
341
+ else {
342
+ for (const t of nodes) {
343
+ const id = attr(t, 'id');
344
+ if (!id) continue;
345
+ const label = attr(t, 'data-name') || id;
346
+ if (!wired.has(id)) notes.push(`${where}box "${label}" has no connections, so it reads as clutter. Connect it (data-to on it or on what calls it), or fold it into a neighbour's .tm-detail.`);
347
+ const n = out.get(id)?.size || 0;
348
+ if (n > MAX_FANOUT) notes.push(`${where}box "${label}" has ${n} outgoing connections; past ${MAX_FANOUT} they merge into one bundle of lines. Keep the ones on the main paths and name the rest in its .tm-detail, or split the box by responsibility.`);
349
+ }
350
+ }
303
351
  const outside = body.replace(/<section\b[^>]*class=["'][^"']*\btm-group\b[\s\S]*?<\/section>/gi, '');
304
352
  const loose = (outside.match(/class=["'][^"']*\btm-node\b/gi) || []).length;
305
353
  if (groups && loose) notes.push(`${where}${loose} box(es) outside any group; every box belongs to one group.`);
@@ -312,7 +360,17 @@ export function lintDiagrams(html) {
312
360
  if (!attr(t, 'data-src') && !/\bis-ext\b/.test(attr(t, 'class') || '')) notes.push(`${where}box "${label}" has no data-src; anchor it to its code, or mark it is-ext if it is outside the code.`);
313
361
  }
314
362
  for (const m of body.matchAll(/<li\b[^>]*\sdata-path\s*=\s*["']([^"']*)["']/gi)) {
315
- for (const id of m[1].split(/[\s,]+/).filter(Boolean)) if (!ids.has(id)) notes.push(`${where}flow step "${id}" is not a box id on this map.`);
363
+ const path = m[1].split(/[\s,]+/).filter(Boolean);
364
+ for (const id of path) if (!ids.has(id)) notes.push(`${where}flow step "${id}" is not a box id on this map.`);
365
+ // A lit flow numbers the wire from each step to the next, in that direction only (diagram.js markFlow):
366
+ // a pair with no such wire shows no number and no line, and the flow reads as missing a step.
367
+ const name = body.slice(m.index + m[0].length).split(/<\/li>|<li\b/i)[0].replace(/^[^>]*>/, '').replace(/<[^>]+>/g, '').trim() || m[1];
368
+ path.forEach((a, i) => {
369
+ const b = path[i + 1];
370
+ if (!b || a === b || !ids.has(a) || !ids.has(b) || out.get(a)?.has(b)) return;
371
+ const back = out.get(b)?.has(a);
372
+ notes.push(`${where}flow "${name}": no wire from "${a}" to "${b}"${back ? ` (the wire goes from "${b}" to "${a}")` : ''}, so step ${i + 1} is not drawn. List the steps in the direction the wires point${back ? '' : `, or add data-to="${b}:…" on "${a}"`}.`);
373
+ });
316
374
  }
317
375
  });
318
376
  if (figs.length && /<style\b|\sstyle\s*=\s*["'][^"']*(?:color|background|font|border)/i.test(html)) notes.push('page sets its own colours or fonts; the look is fixed so every map reads the same. Remove <style> and style="…".');
package/src/cli.js CHANGED
@@ -374,7 +374,7 @@ async function cmdChanges(root, args, opts) {
374
374
  for (const st of r.plan.steps || []) {
375
375
  const quiet = [...st.files.filter((x) => !x.changed).map((x) => x.path), ...st.boxes.filter((x) => !x.changed).map((x) => x.name)];
376
376
  out(` - step ${st.n}${st.report ? ` (you reported: ${st.report.status})` : ''}: ${q(st.text)}${quiet.length ? ` # names ${quiet.map(q).join(', ')} with no changes` : ''}`);
377
- if (st.conflict) out(` conflict: ${q(st.conflict)} # the user sees this at the top of the Changes view`);
377
+ if (st.conflict) out(` conflict: ${q(st.conflict)} # the user sees this in the conversation when the plan is closed`);
378
378
  if (st.rewritten) out(` report_history: ${q(st.rewritten)}`);
379
379
  }
380
380
  }
@@ -405,7 +405,7 @@ async function cmdPlan(root, args, opts) {
405
405
  out(`status: ${r.body.status}`);
406
406
  out(`plan: ${q(r.body.plan)}`);
407
407
  for (const st of r.body.check?.steps || []) {
408
- if (st.conflict) out(`conflict: step ${st.n}: ${q(st.conflict)} # shown to the user in the conversation and the Changes view`);
408
+ if (st.conflict) out(`conflict: step ${st.n}: ${q(st.conflict)} # shown to the user in the conversation`);
409
409
  if (st.rewritten) out(`report_history: step ${st.n}: ${q(st.rewritten)}`);
410
410
  }
411
411
  const missing = (r.body.check?.planned || []).filter((p) => !p.changed);
@@ -461,7 +461,8 @@ function cmdDraft(root, args, opts) {
461
461
  mkdirSync(dir, { recursive: true });
462
462
  const nums = readdirSync(dir).map((x) => parseInt(x, 10)).filter(Number.isFinite);
463
463
  const n = (nums.length ? Math.max(...nums) : 0) + 1;
464
- const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 48) || 'draft';
464
+ // Letters and digits of any script, so a title in Japanese, Russian or Arabic still names its file.
465
+ const slug = [...name.normalize('NFC').toLowerCase().replace(/[^\p{L}\p{M}\p{N}]+/gu, '-').replace(/^-+|-+$/g, '')].slice(0, 48).join('').replace(/-+$/, '') || 'draft';
465
466
  const file = `drafts/${String(n).padStart(3, '0')}-${slug}.html`;
466
467
  const title = opts.title || name.replace(/^./, (c) => c.toUpperCase());
467
468
  const esc = (t) => String(t).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
@@ -480,7 +481,7 @@ function cmdDraft(root, args, opts) {
480
481
  </header>
481
482
  <!-- Show it in the form that makes it obvious: a real example traced step by step, a drawing, a timeline,
482
483
  options side by side, something to try, or the map component. Any HTML, inline SVG, <style>, <script>;
483
- colours through var(--tm-…). Words only as captions. -->
484
+ colours through var(--tm-…). Words only as captions. Write in the user's language and set <html lang> to match. -->
484
485
  <section class="tm-section">
485
486
  </section>
486
487
  </main></body>
@@ -608,7 +609,7 @@ usage:
608
609
  ${CMD} plan --file plan.json before a change that touches 3+ boxes or adds one: show the plan on the map for review
609
610
  ${CMD} plan --approve|--done the user said "go" in the terminal / the plan is built
610
611
  ${CMD} changes [--base turn|plan|head|main]
611
- what changed, by box; opens the Changes view for the user
612
+ what changed, by box; one card per turn in the conversation
612
613
  ${CMD} progress "<text>" show a short status line in the chat while you work
613
614
  ${CMD} stop stop the background server
614
615
 
package/src/outline.js CHANGED
@@ -12,11 +12,14 @@ const TEST = /(^|\/)(tests?|__tests__|spec|fixtures?|examples?|docs?)\//i;
12
12
  const BINARY = /\.(png|jpe?g|gif|webp|ico|svg|woff2?|ttf|otf|eot|pdf|zip|gz|tgz|jar|exe|dll|so|dylib|mp4|mp3|wav|lock)$/i;
13
13
 
14
14
  function listFiles(root) {
15
+ // Tracked files only: untracked scratch folders (.tmp-walk/, a stray server.ts) are not the project.
16
+ // A repo with nothing tracked yet falls through to the folder walk.
15
17
  try {
16
- const outText = execFileSync(gitExe(), ['ls-files', '-z', '--cached', '--others', '--exclude-standard'], {
18
+ const outText = execFileSync(gitExe(), ['ls-files', '-z', '--cached'], {
17
19
  cwd: root, encoding: 'utf8', maxBuffer: 256 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true,
18
20
  });
19
- return { gitRepo: true, files: outText.split('\0').filter(Boolean).filter((f) => !f.split('/').some((p) => SKIP.has(p))) };
21
+ const files = outText.split('\0').filter(Boolean).filter((f) => !f.split('/').some((p) => SKIP.has(p)));
22
+ if (files.length) return { gitRepo: true, files };
20
23
  } catch { /* not a git repo */ }
21
24
  const files = [];
22
25
  const walk = (dir, rel, depth) => {
@@ -55,7 +58,8 @@ export function outline(root) {
55
58
  if (parts.length <= 4 && ENTRY.test(f) && !TEST.test(f) && !BINARY.test(f)) entries.push(f);
56
59
  }
57
60
  const dirs = [...groups.values()]
58
- .sort((a, b) => (a.path === '.' ? -1 : b.path === '.' ? 1 : a.path.localeCompare(b.path)))
61
+ // the top level first, then the folders holding the most code, so the cap drops the small ones
62
+ .sort((a, b) => (a.path === '.' ? -1 : b.path === '.' ? 1 : (b.bytes - a.bytes) || a.path.localeCompare(b.path)))
59
63
  .slice(0, 60)
60
64
  .map((g) => ({
61
65
  path: g.path, files: g.files, lines: Math.round(g.bytes / 36),
package/src/server.js CHANGED
@@ -69,24 +69,60 @@ async function takeSnapshot(kind, extra = {}) {
69
69
  const changeCache = new Map(); // base -> { at, promise }
70
70
 
71
71
  // ---------- what changed in a turn comes to the user, in the conversation ----------
72
- let lastPostedChanges = snapshots.posted || '';
73
- async function postChanges(base = 'turn') {
74
- if (base === 'turn' && !snapshots.turn) return null;
75
- const r = await changes(root, base, snapshots).catch(() => null);
72
+ // One card per turn. `changes`, `plan --done` + `changes` and the end of the turn (listen) all want to post;
73
+ // the first posts the card, the later ones update that same card (same id, same place) when it differs.
74
+ // A turn is the time between the agent picking up a message and listening again; a user message or a
75
+ // finished listen starts a new card.
76
+ function cardThisTurn(turnAt) {
77
+ if (snapshots.closedTurn !== undefined && snapshots.closedTurn === turnAt) return null;
78
+ for (let i = history.length - 1; i >= 0; i--) {
79
+ const h = history[i];
80
+ if (h.role === 'user') return null;
81
+ if (h.kind === 'changes') return (h.turn || '') === turnAt ? h : null;
82
+ }
83
+ return null;
84
+ }
85
+ function updateEntry(entry) {
86
+ try {
87
+ const lines = readFileSync(historyPath(root), 'utf8').split('\n');
88
+ const i = lines.findLastIndex((l) => l.includes(`"id":"${entry.id}"`));
89
+ if (i !== -1) { lines[i] = JSON.stringify(entry); writePrivate(historyPath(root), lines.join('\n')); }
90
+ } catch { /* ignore */ }
91
+ broadcast({ type: 'chat-update', entry });
92
+ }
93
+ // `given`: the result `truemap changes` just reported, so the card says exactly what the terminal said.
94
+ async function postChanges(base = 'turn', given = null) {
95
+ const turnAt = snapshots.turn?.at || '';
96
+ const card = cardThisTurn(turnAt);
97
+ if (card && base === 'turn') base = card.changes?.base || base; // the end of the turn refreshes the card it has
98
+ if (!given && base === 'turn' && !snapshots.turn) return null;
99
+ // no key on the code alone: editing the map moves files between boxes, closing a plan changes what is not done
100
+ const r = given || await changesFor(base, true);
76
101
  if (!r || r.error || !r.files) return r;
77
- const key = `${r.base.kind}:${snapshots[r.base.kind]?.tree || ''}:${r.now}`;
78
- if (key === lastPostedChanges) return r;
79
- lastPostedChanges = key; snapshots.posted = key; saveSnapshots();
80
- const p = plan && snapshots.plan?.slug === plan.slug && r.base.kind === 'plan' ? planCheck(root, plan, r) : null;
102
+ const p = r.plan || null;
103
+ const summary = {
104
+ base: r.base.kind, label: r.base.label, files: r.files, add: r.add, del: r.del,
105
+ boxes: r.boxes.slice(0, 16).map((b) => ({ src: b.src, name: b.name, isNew: !!b.isNew, add: b.add, del: b.del, pages: b.pages, files: b.files.map((x) => x.path) })),
106
+ unmapped: r.unmapped.flatMap((g) => g.files).slice(0, 30).map((x) => ({ path: x.path, add: x.add, del: x.del })),
107
+ notDone: p ? p.planned.filter((x) => !x.changed).map((x) => x.name || x.box) : [],
108
+ };
109
+ const text = `Changed ${r.files} file${r.files > 1 ? 's' : ''}`;
110
+ // the same lines changed, whichever base measured them
111
+ const same = (c) => JSON.stringify([c.files, c.add, c.del, c.boxes.map((b) => [b.src, b.add, b.del]), c.unmapped.map((x) => [x.path, x.add, x.del])]);
112
+ const live = cardThisTurn(turnAt); // again: history may have moved while the diff ran
113
+ // a listen after the turn was closed (a timeout, a restart) measures from the same start: no repeat card
114
+ const last = live ? null : [...history].reverse().find((h) => h.kind === 'changes' && h.changes);
115
+ if (last && same(last.changes) === same(summary)) return r;
116
+ if (live) {
117
+ if (same(live.changes) !== same(summary) || String(live.changes.notDone) !== String(summary.notDone)) {
118
+ Object.assign(live, { text, changes: summary, updatedAt: new Date().toISOString() });
119
+ updateEntry(live);
120
+ }
121
+ return r;
122
+ }
81
123
  remember({
82
124
  role: 'agent', kind: 'changes', id: `c${Date.now().toString(36)}${(seq++).toString(36)}`, at: new Date().toISOString(), agent: agentName,
83
- text: `Changed ${r.files} file${r.files > 1 ? 's' : ''}`,
84
- changes: {
85
- base: r.base.kind, label: r.base.label, files: r.files, add: r.add, del: r.del,
86
- boxes: r.boxes.slice(0, 16).map((b) => ({ src: b.src, name: b.name, isNew: !!b.isNew, add: b.add, del: b.del, pages: b.pages, files: b.files.map((x) => x.path) })),
87
- unmapped: r.unmapped.flatMap((g) => g.files).slice(0, 30).map((x) => ({ path: x.path, add: x.add, del: x.del })),
88
- notDone: p ? p.planned.filter((x) => !x.changed).map((x) => x.name || x.box) : [],
89
- },
125
+ turn: turnAt, text, changes: summary,
90
126
  });
91
127
  return r;
92
128
  }
@@ -531,7 +567,9 @@ const server = createServer(async (req, res) => {
531
567
  if (p === '/api/agent/listen' && req.method === 'POST') {
532
568
  const b = await readBody(req);
533
569
  // the agent listens again: its turn is over, so what it changed goes to the user
534
- postChanges('turn'); // posts only when something changed since the turn began, and only once
570
+ // posts only when something changed since the turn began, or brings this turn's card up to date
571
+ const endedTurn = snapshots.turn?.at || '';
572
+ postChanges('turn').catch(() => null).finally(() => { snapshots.closedTurn = endedTurn; saveSnapshots(); });
535
573
  if (listener) finishListen({ status: 'replaced' });
536
574
  lastAgentActivity = Date.now();
537
575
  noteAgent(b.agent);
@@ -587,12 +625,12 @@ const server = createServer(async (req, res) => {
587
625
  return sendJson(res, 200, { ok: true, browsers: clients.size });
588
626
  }
589
627
  if (p === '/api/agent/changes' && req.method === 'POST') {
590
- // `truemap changes`: the summary for the agent, and the Changes view for the user.
628
+ // `truemap changes`: the summary for the agent, and this turn's changes card for the user.
591
629
  const b = await readBody(req);
592
630
  noteAgent(b.agent);
593
631
  const base = ['turn', 'plan', 'head', 'main'].includes(b.base) ? b.base : 'auto';
594
632
  const r = await changesFor(base, true);
595
- if (b.open !== false && !r.error && r.files) await postChanges(r.base.kind);
633
+ if (b.open !== false && !r.error && r.files) await postChanges(r.base.kind, r);
596
634
  return sendJson(res, 200, { ...r, browsers: clients.size });
597
635
  }
598
636
  if (p === '/api/agent/plan' && req.method === 'POST') {
@@ -617,8 +655,7 @@ const server = createServer(async (req, res) => {
617
655
  const conflicts = sts.filter((x) => x.conflict || x.rewritten);
618
656
  remember({ role: 'agent', id: `a${Date.now().toString(36)}${(seq++).toString(36)}`, at: new Date().toISOString(), agent: agentName, plan: plan.slug,
619
657
  text: [`**Plan closed: ${plan.title}.**${tally ? ` Steps: ${tally}.` : ''}`, ...rpt.map((x, i) => x && x.status !== 'done' ? `- Step ${i + 1} ${x.status.replace('_', ' ')}: ${x.note}` : null).filter(Boolean),
620
- ...(conflicts.length ? ['', '**Check before you trust this report:**', ...conflicts.map((x) => `- Step ${x.n}: ${[x.conflict, x.rewritten].filter(Boolean).join(' ')}`)] : []),
621
- '', 'Open the Changes tab to see each step beside its diff.'].join('\n') });
658
+ ...(conflicts.length ? ['', '**Check before you trust this report:**', ...conflicts.map((x) => `- Step ${x.n}: ${[x.conflict, x.rewritten].filter(Boolean).join(' ')}`)] : [])].join('\n') });
622
659
  }
623
660
  return sendJson(res, 200, { ok: true, plan: plan.slug, status: plan.status, check });
624
661
  }
package/src/ui/diagram.js CHANGED
@@ -102,7 +102,9 @@
102
102
  // The layered layout, computed top to bottom ("rows"); left to right is the same picture turned.
103
103
  // - Groups are bands of rows in the author's order: a group never shares a row with another, so groups
104
104
  // never overlap or interleave.
105
- // - Inside a group a box sits one row below the boxes that call it (longest path).
105
+ // - Inside a group a box sits one row below the boxes that call it (longest path). Top to bottom, a
106
+ // group that fits the width is one row; one that does not wraps into as few rows as fit, callers
107
+ // first, so a box is never above the boxes that call it.
106
108
  // - A connection that skips rows reserves a narrow slot in each row it crosses.
107
109
  // - Order within rows: barycenter sweeps, keeping the order with the fewest crossings.
108
110
  // - Positions: as close to the connected boxes as the ordering and spacing allow (block merging).
@@ -134,13 +136,15 @@
134
136
  const intra = E.filter((x) => gOf[x.a] === g && gOf[x.b] === g);
135
137
  // width of the row in its first order: only neighbours that call each other need room for a label
136
138
  const inOrder = [...members].sort((u, v) => local.get(u) - local.get(v) || u - v);
137
- let rowW = inOrder.reduce((n, i) => n + S[i].w, 0) + (members.length - 1) * NODESEP;
138
- for (let k = 1; k < inOrder.length; k++) {
139
- const pair = intra.filter((x) => (x.a === inOrder[k - 1] && x.b === inOrder[k]) || (x.b === inOrder[k - 1] && x.a === inOrder[k]));
140
- if (pair.length) rowW += Math.max(...pair.map((x) => (x.e.lw ? x.e.lw + 30 : 28))) - NODESEP;
141
- }
142
- const oneRow = !lr && rowW <= (room - gutter - 24) / 0.82;
143
- for (const i of members) { rank[i] = oneRow ? base : base + local.get(i); localRank[i] = local.get(i); top = Math.max(top, rank[i]); }
139
+ const sepAt = inOrder.map((i, k) => {
140
+ if (!k) return 0;
141
+ const pair = intra.filter((x) => (x.a === inOrder[k - 1] && x.b === i) || (x.b === inOrder[k - 1] && x.a === i));
142
+ return pair.length ? Math.max(...pair.map((x) => (x.e.lw ? x.e.lw + 30 : 28))) : NODESEP;
143
+ });
144
+ const fit = (room - gutter - 24) / 0.82;
145
+ const wrap = new Map();
146
+ if (!lr) { let row = 0; let w = 0; inOrder.forEach((i, k) => { if (k && w + sepAt[k] + S[i].w > fit) { row++; w = 0; } else w += sepAt[k]; w += S[i].w; wrap.set(i, row); }); }
147
+ for (const i of members) { rank[i] = base + (lr ? local.get(i) : wrap.get(i)); localRank[i] = local.get(i); top = Math.max(top, rank[i]); }
144
148
  bands.push({ g, from: base, to: top });
145
149
  base = top + 1;
146
150
  }
@@ -200,6 +204,38 @@
200
204
  }
201
205
  for (let r = 0; r < R; r++) rows[r] = best[r];
202
206
  number();
207
+ // A call inside a row between boxes that aren't neighbours is drawn as a loop under the row, across
208
+ // the wires leaving every box it passes. Finish the order with neighbour swaps that cut crossings and
209
+ // loop lengths together; callers stay left of callees, and on a tie the author's order stays.
210
+ const authorK = new Map(); for (const row of rows) [...row].sort((p, q) => p.order - q.order).forEach((it, k) => authorK.set(it, k));
211
+ const cost = () => {
212
+ let c = crossings();
213
+ for (const x of sameEdges) c += 2 * (Math.abs(item[x.a].k - item[x.b].k) - 1);
214
+ for (const row of rows) for (const it of row) if (!it.dummy) c += 0.001 * Math.abs(it.k - authorK.get(it));
215
+ return c;
216
+ };
217
+ const callsOk = (row) => sameEdges.every((x) => item[x.a].row !== row[0]?.row || item[x.a].k < item[x.b].k);
218
+ let cur = cost();
219
+ const renumber = (row) => row.forEach((it, k) => { it.k = k; });
220
+ for (let pass = 0; pass < 6; pass++) {
221
+ let better = false;
222
+ for (const row of rows) {
223
+ // take each box (or wire slot) out and put it back where the whole drawing costs least
224
+ for (const it of [...row]) {
225
+ const from = row.indexOf(it); let bestAt = from;
226
+ row.splice(from, 1);
227
+ for (let at = 0; at <= row.length; at++) {
228
+ if (at === from) continue;
229
+ row.splice(at, 0, it); renumber(row);
230
+ const c = callsOk(row) ? cost() : Infinity;
231
+ if (c < cur - 1e-9) { cur = c; bestAt = at; better = true; }
232
+ row.splice(at, 1);
233
+ }
234
+ row.splice(bestAt, 0, it); renumber(row);
235
+ }
236
+ }
237
+ if (!better) break;
238
+ }
203
239
  // 3. positions across the rows
204
240
  const pairGap = new Map();
205
241
  for (const x of sameEdges) { const k = [x.a, x.b].sort((u, v) => u - v).join('|'); pairGap.set(k, Math.max(pairGap.get(k) || 0, x.e.lw ? x.e.lw + 30 : 28)); }
@@ -223,12 +259,20 @@
223
259
  for (const b of blocks) b.items.forEach((k, j) => { row[k].x = b.pos + b.off[j]; });
224
260
  }
225
261
  for (const row of rows) { let x = 0; row.forEach((it, k) => { if (k) x += sep(row[k - 1], it); it.x = x + it.w / 2; x += it.w; }); const c = x / 2; for (const it of row) it.x -= c; }
262
+ // A box is pulled toward everything it connects to, in its own row too: a pair linked to the rest only
263
+ // by calls inside a row would otherwise keep its first place, past every wire slot at the row's end.
264
+ // A box with no connections at all sits under the middle of the drawing.
265
+ const beside = new Map();
266
+ for (const x of sameEdges) { link(beside, item[x.a], item[x.b]); link(beside, item[x.b], item[x.a]); }
267
+ const near = (p) => [...(up.get(p) || []), ...(down.get(p) || []), ...(beside.get(p) || [])];
268
+ const linked = rows.flat().filter((p) => near(p).length);
226
269
  for (let it = 0; it < 10; it++) {
227
270
  const seq = it % 2 === 0 ? [...rows.keys()] : [...rows.keys()].reverse();
271
+ const mid = linked.length ? (Math.min(...linked.map((p) => p.x - p.w / 2)) + Math.max(...linked.map((p) => p.x + p.w / 2))) / 2 : 0;
228
272
  for (const r of seq) {
229
273
  const want = rows[r].map((p) => {
230
- const ns = [...(up.get(p) || []), ...(down.get(p) || [])];
231
- return ns.length ? ns.reduce((s, q) => s + q.x, 0) / ns.length : p.x;
274
+ const ns = near(p);
275
+ return ns.length ? ns.reduce((s, q) => s + q.x, 0) / ns.length : mid;
232
276
  });
233
277
  settle(rows[r], want);
234
278
  }
@@ -272,10 +316,24 @@
272
316
  const step = Math.min(16, (it.w * 0.7) / Math.max(1, keys.length));
273
317
  return new Map(keys.map((k, i) => [k, it.x + (i - (keys.length - 1) / 2) * step]));
274
318
  };
275
- for (const [a, list] of out) {
276
- const it = item[a];
277
- const ports = portX(it, list, (x) => x.bundle, (k) => { const x = list.find((z) => z.bundle === k); return x.chain[1].x; });
278
- for (const x of list) x.exit = ports.get(x.bundle);
319
+ // A box's bottom edge carries its exits down and both ends of its loops under the row; each gets its own
320
+ // point there, ordered by where the line goes, so a loop in and a loop out never share a vertical line.
321
+ const bottom = new Map();
322
+ const atBottom = (i, key, other, set) => { if (!bottom.has(i)) bottom.set(i, new Map()); const B = bottom.get(i); if (!B.has(key)) B.set(key, { other, sets: [] }); B.get(key).sets.push(set); };
323
+ for (const [a, list] of out) for (const x of list) atBottom(a, `>${x.bundle}`, x.chain[1].x, (v) => { x.exit = v; });
324
+ for (const x of E) {
325
+ if (!x.same || adjacent(x)) continue;
326
+ x.below = {};
327
+ atBottom(x.a, `${x.e.name}:a`, item[x.b].x, (v) => { x.below.px = v; });
328
+ atBottom(x.b, `${x.e.name}:b`, item[x.a].x, (v) => { x.below.qx = v; });
329
+ }
330
+ for (const [i, B] of bottom) {
331
+ // exits in the middle by where they go; loops to the left and right, the farther one further out so
332
+ // they nest instead of crossing
333
+ const cx = item[i].x; const W = 1e6;
334
+ const rankOf = (k) => { const o = B.get(k).other; return k.startsWith('>') ? o : o < cx ? -W - o : W - o; };
335
+ const ports = portX(item[i], [...B.keys()], (k) => k, rankOf);
336
+ for (const [k, v] of B) for (const set of v.sets) set(ports.get(k));
279
337
  }
280
338
  for (const [b, list] of inc) {
281
339
  const it = item[b];
@@ -288,7 +346,7 @@
288
346
  for (const x of E) {
289
347
  const pts = [];
290
348
  if (x.same) {
291
- if (!adjacent(x)) { const a = item[x.a]; const b = item[x.b]; const dir = Math.sign(b.x - a.x); x.below = { px: a.x + dir * a.w / 4, qx: b.x - dir * b.w / 4 }; hops.push({ x, k: 0, row: a.row, px: x.below.px, qx: x.below.qx, key: `${x.e.name}:same` }); }
349
+ if (!adjacent(x)) hops.push({ x, k: 0, row: item[x.a].row, px: x.below.px, qx: x.below.qx, key: `${x.e.name}:same` });
292
350
  x.pts = pts; continue;
293
351
  }
294
352
  for (let k = 0; k + 1 < x.chain.length; k++) {
@@ -298,16 +356,52 @@
298
356
  }
299
357
  x.pts = pts;
300
358
  }
359
+ // Two lines never run down one vertical in a gap, or one reads as the other's continuation: a loop end
360
+ // or an entry that lands on another line slides along its box to a free spot.
361
+ const stems = [];
362
+ for (const h of hops) {
363
+ const x = h.x; const last = h.k + 1 === (x.same ? 1 : x.chain.length - 1);
364
+ stems.push({ h, end: 'px', key: x.same ? `${x.e.name}:a` : h.k === 0 ? `>${x.bundle}` : `${x.e.name}:${h.k}p`, box: x.same ? item[x.a] : null });
365
+ stems.push({ h, end: 'qx', key: `${x.e.name}:${h.k}q`, box: last ? item[x.b] : null });
366
+ }
367
+ const clash = (s, v) => stems.some((o) => o !== s && o.h.row === s.h.row && o.h.x !== s.h.x && o.key !== s.key && Math.abs(o.h[o.end] - v) < 5);
368
+ for (const s of stems) {
369
+ if (!s.box || !clash(s, s.h[s.end])) continue;
370
+ const v0 = s.h[s.end]; const lo = s.box.x - s.box.w / 2 + 6; const hi = s.box.x + s.box.w / 2 - 6;
371
+ let v;
372
+ for (let d = 6; v === undefined && d < s.box.w; d += 6) v = [v0 + d, v0 - d].find((c) => c > lo && c < hi && !clash(s, c));
373
+ if (v === undefined) continue;
374
+ s.h[s.end] = v;
375
+ if (s.h.x.same) s.h.x.below[s.end] = v; else s.h.x.entry = v;
376
+ }
301
377
  for (const h of hops) {
302
378
  if (Math.abs(h.px - h.qx) < 1) continue;
303
379
  if (!lanes.has(h.row)) lanes.set(h.row, new Map());
304
380
  const L = lanes.get(h.row);
381
+ if (!L.has(h.key)) L.set(h.key, { lo: Infinity, hi: -Infinity, tops: [], bottoms: [] });
305
382
  const cur = L.get(h.key);
306
- if (cur) { cur.lo = Math.min(cur.lo, h.px, h.qx); cur.hi = Math.max(cur.hi, h.px, h.qx); } else L.set(h.key, { lo: Math.min(h.px, h.qx), hi: Math.max(h.px, h.qx) });
383
+ cur.lo = Math.min(cur.lo, h.px, h.qx); cur.hi = Math.max(cur.hi, h.px, h.qx);
384
+ // a line comes into its lane from above at px and leaves downwards at qx; a loop goes back up at qx
385
+ cur.tops.push(h.px); (h.x.same ? cur.tops : cur.bottoms).push(h.qx);
307
386
  }
387
+ // In a gap, a lane whose line comes down from above through another lane's run has to sit above it, and
388
+ // one whose line goes on down through it has to sit below; order the lanes to break as few as possible.
389
+ const inside = (v, B) => v > B.lo + 1 && v < B.hi - 1;
390
+ const wrong = (A, B) => A.bottoms.filter((v) => inside(v, B)).length + B.tops.filter((v) => inside(v, A)).length; // A placed above B
391
+ const orderLanes = (list) => {
392
+ for (let pass = 0; pass < list.length; pass++) {
393
+ let moved = false;
394
+ for (let i = 0; i + 1 < list.length; i++) {
395
+ const A = list[i][1]; const B = list[i + 1][1];
396
+ if (wrong(B, A) < wrong(A, B)) { [list[i], list[i + 1]] = [list[i + 1], list[i]]; moved = true; }
397
+ }
398
+ if (!moved) break;
399
+ }
400
+ return list;
401
+ };
308
402
  const laneY = new Map();
309
403
  for (const [row, L] of lanes) {
310
- const g = gapAfter[row]; const list = [...L.entries()].sort((p, q) => p[1].lo - q[1].lo);
404
+ const g = gapAfter[row]; const list = orderLanes([...L.entries()].sort((p, q) => p[1].lo - q[1].lo));
311
405
  const span = g.bottom - g.top; const step = Math.min(11, Math.max(6, (span - 16) / Math.max(1, list.length)));
312
406
  list.forEach(([key], i) => laneY.set(`${row}|${key}`, g.top + span / 2 + (i - (list.length - 1) / 2) * step));
313
407
  }
@@ -349,7 +443,9 @@
349
443
  if (x.e.back) pts = pts.reverse();
350
444
  return [x.e.name, pts];
351
445
  }));
352
- return { width: lr ? H : W, height: lr ? W : H, pos, bands: bandBoxes, routes, dir, gutter: lr ? 0 : gutter };
446
+ // the gaps between rows and how many lanes run in each, so a label can stay out of a crowded one
447
+ const gaps = gapAfter.map((g, r) => g && { a: g.top, b: g.bottom, n: lanes.get(r)?.size || 0 }).filter(Boolean);
448
+ return { width: lr ? H : W, height: lr ? W : H, pos, bands: bandBoxes, routes, dir, gutter: lr ? 0 : gutter, gaps };
353
449
  }
354
450
 
355
451
  function layout(fig) {
@@ -378,6 +474,8 @@
378
474
  const asked = (fig.getAttribute('data-direction') || '').toUpperCase();
379
475
  let L = layered(m, edges, asked === 'TB' ? 'TB' : 'LR', labelW, room);
380
476
  if (!asked && L.width > room) L = layered(m, edges, 'TB', labelW, room);
477
+ // wire slots make a wrapped row wider than its boxes: wrap tighter until it fits at the smallest scale
478
+ for (let fitTo = room; L.dir === 'TB' && L.width * 0.7 > room - 16 && fitTo > 240;) { fitTo *= 0.85; L = layered(m, edges, 'TB', labelW, fitTo); }
381
479
  fig.dataset.laidOut = L.dir;
382
480
  if (L.dir === 'TB' && L.width < room) {
383
481
  const dx = (room - L.width) / 2;
@@ -448,17 +546,29 @@
448
546
  lab.style.left = `${best.l - l + 3}px`; lab.style.top = `${best.t - t + 2}px`;
449
547
  taken.push(best);
450
548
  }
451
- // Edge labels sit on their own edge, at the first spot along it that covers no box and no other label.
452
- // The same word on several edges from one box is said once, on the most important of them.
549
+ // Edge labels sit on their own edge, at the first spot along it that covers no box, no other label and,
550
+ // where it can, no other line. At rest a label shows on the main path, and on any other line where it
551
+ // found such a clean spot outside a gap crowded with three or more lanes; the rest wait for their line
552
+ // to be lit.
553
+ // The same word on several edges from one box is said once, on the most important of them ("creates ×3").
554
+ // Once a box is selected or a flow is lit, each lit edge says its own plain word instead: the repeats
555
+ // show, and the count hides (kit CSS). Repeats are placed last, so the map at rest is laid out the same.
453
556
  const seen = new Set();
454
557
  placed.sort((x, y) => (y.key - x.key));
455
558
  for (const pl of placed) { const k = `${pl.e.from}|${pl.e.label}`; pl.dup = seen.has(k); seen.add(k); }
456
559
  const bundleSize = new Map();
457
560
  for (const pl of placed) { const k = `${pl.e.from}|${pl.e.label}`; bundleSize.set(k, (bundleSize.get(k) || 0) + 1); }
458
- for (const { e, path, key, dup } of placed) {
561
+ // every line as straight runs, to keep labels off lines that aren't theirs (a shared trunk is one line)
562
+ const runs = [];
563
+ for (const e of edges) { const pts = L.routes.get(e.name) || []; for (let i = 0; i + 1 < pts.length; i++) runs.push({ e, a: pts[i], b: pts[i + 1] }); }
564
+ const lineHits = (r, e) => runs.filter((s) => !(s.e === e || (s.e.from === e.from && s.e.label === e.label))
565
+ && Math.min(s.a.x, s.b.x) < r.r - 1 && Math.max(s.a.x, s.b.x) > r.l + 1 && Math.min(s.a.y, s.b.y) < r.b - 1 && Math.max(s.a.y, s.b.y) > r.t + 1).length;
566
+ const lanesAt = (p) => { const v = L.dir === 'LR' ? p.x : p.y; return (L.gaps || []).find((g) => v > g.a && v < g.b)?.n || 0; };
567
+ for (const { e, path, key, dup } of [...placed.filter((pl) => !pl.dup), ...placed.filter((pl) => pl.dup)]) {
459
568
  const t = document.createElement('span'); t.className = `tm-dg-label${key ? ' is-main' : ''}${dup ? ' is-dup' : ''}`;
460
569
  const many = bundleSize.get(`${e.from}|${e.label}`) || 1;
461
- t.textContent = !dup && many > 1 ? `${e.label} ×${many}` : e.label;
570
+ t.textContent = e.label;
571
+ if (!dup && many > 1) t.dataset.many = `×${many}`;
462
572
  t.dataset.from = e.from; t.dataset.to = e.to;
463
573
  m.stage.appendChild(t);
464
574
  const w = t.offsetWidth; const h = t.offsetHeight; const L = path.getTotalLength();
@@ -466,19 +576,21 @@
466
576
  const trunk = bundleSize.get(`${e.from}|${e.label}`) > 1;
467
577
  // try every few pixels along the line, nearest the preferred spot first; take the first free one,
468
578
  // otherwise the least crowded; a label that would still cover a box only shows when its line is lit
469
- const pref = trunk ? 0.15 : 0.5;
579
+ const pref = trunk && !dup ? 0.15 : 0.5;
470
580
  const fr = [pref]; for (let d = 0.04; d < 0.96; d += 0.04) { if (pref + d < 0.97) fr.push(pref + d); if (pref - d > 0.03) fr.push(pref - d); }
471
- let bestCost = Infinity;
581
+ let bestCost = Infinity; let bestLines = Infinity; let clean = null;
472
582
  const overlap = (a, list) => list.reduce((n, o) => n + Math.max(0, Math.min(a.r, o.r) - Math.max(a.l, o.l)) * Math.max(0, Math.min(a.b, o.b) - Math.max(a.t, o.t)), 0);
473
583
  for (const f of fr) {
474
584
  const p = path.getPointAtLength(L * f);
475
585
  const r = { l: p.x - w / 2, r: p.x + w / 2, t: p.y - h / 2, b: p.y + h / 2 };
476
586
  const cost = overlap(r, boxes) * 4 + overlap(r, badges) * 4 + overlap(r, taken) * 2;
477
- if (cost < bestCost) { bestCost = cost; best = r; }
478
- if (!cost) break;
587
+ const lines = cost ? Infinity : lineHits(r, e);
588
+ if (cost < bestCost || (cost === bestCost && lines < bestLines)) { bestCost = cost; bestLines = lines; best = r; }
589
+ if (!cost && !lines) { clean = p; break; }
479
590
  }
480
591
  if (bestCost > 0) t.classList.add('is-crowded');
481
- if (!dup && !t.classList.contains('is-crowded')) taken.push(best);
592
+ else if (clean && !key && !dup && many === 1 && lanesAt(clean) < 3) t.classList.add('is-rest'); // a count ("creates ×3") waits for its lines to be lit
593
+ if (!t.classList.contains('is-crowded')) taken.push(best);
482
594
  t.style.left = `${(best.l + best.r) / 2}px`; t.style.top = `${(best.t + best.b) / 2}px`;
483
595
  }
484
596
  // main-path edges on top
package/src/ui/sdk.js CHANGED
@@ -76,8 +76,11 @@
76
76
  w.classList.toggle('is-focus', ids.has(from) && ids.has(to));
77
77
  w.classList.toggle('is-hot', !!hot && (from === hot || to === hot));
78
78
  }
79
+ const sel = selected?.id;
79
80
  for (const w of document.querySelectorAll('.tm-dg-edge, .tm-dg-head, .tm-dg-label')) {
80
81
  w.classList.toggle('is-focus', ids.has(w.dataset.from) && ids.has(w.dataset.to));
82
+ // a re-laid map (its space changed) keeps the selected box's lines lit
83
+ w.classList.toggle('is-sel', !!sel && (w.dataset.from === sel || w.dataset.to === sel));
81
84
  }
82
85
  // labels are placed afresh for what is now visible
83
86
  window.truemapWires?.labels?.({ hot: hot || null, focus: [...ids] });
@@ -377,6 +380,19 @@
377
380
  let left = u.r + 10; let top = u.t - h / 2;
378
381
  if (left + w > scrollX + vw - 8) { left = Math.max(scrollX + 8, u.r - w); top = u.t - h - 14; }
379
382
  if (top < scrollY + 4) top = u.b + 10;
383
+ // Never on top of a box, the badge above it ("Plan: edit") or a group's name: the first free spot beside
384
+ // the plan's boxes.
385
+ const doc = (r) => ({ l: r.left + scrollX, t: r.top + scrollY, r: r.right + scrollX, b: r.bottom + scrollY });
386
+ const walls = [...document.querySelectorAll('.tm-node, .tm-step, .tm-dg-glabel')].filter((el) => el.getBoundingClientRect().width).map((el) => { const r = doc(el.getBoundingClientRect()); return { l: r.l - 6, t: r.t - 18, r: r.r + 12, b: r.b + 6 }; });
387
+ // nor on a wire's label, including one that only shows when its box is selected
388
+ for (const el of document.querySelectorAll('.tm-dg-label')) { const b = el.getBoundingClientRect(); if (b.width) { const r = doc(b); walls.push({ l: r.l - 4, t: r.t - 4, r: r.r + 4, b: r.b + 4 }); } }
389
+ const free = ([x, y]) => x >= scrollX + 8 && x + w <= scrollX + vw - 8 && y >= 4 && !walls.some((o) => x < o.r && x + w > o.l && y < o.b && y + h > o.t);
390
+ const spots = [[left, top]];
391
+ for (const r of rs.map(doc)) {
392
+ const mid = (r.t + r.b) / 2 - h / 2;
393
+ spots.push([r.r + 16, mid], [r.l - 10 - w, mid], [r.r - w, r.t - h - 20], [r.r - w, r.b + 10]);
394
+ }
395
+ [left, top] = spots.find(free) || spots[0];
380
396
  box.style.left = `${left}px`; box.style.top = `${top}px`;
381
397
  box.onclick = (e) => {
382
398
  const act = e.target.closest('[data-pa]')?.dataset.pa; if (!act) return;
@@ -6,7 +6,7 @@
6
6
  const S = {
7
7
  placeholder: 'Ask about this page', placeholderNotes: 'Add a message (optional)',
8
8
  drawPrompt: 'Read this project and draw its blueprint as .truemap/index.html, then open it for me.',
9
- ok: 'Matches the code', changed: (n) => `Map may be out of date (${n})`, broken: (n) => `Map out of date (${n})`,
9
+ ok: 'Matches the code', changed: (n, what = 'Map') => `${what} may be out of date (${n})`, broken: (n, what = 'Map') => `${what} out of date (${n})`,
10
10
  fixPrompt: (p, c, b) => `Check ${p} against the code and update it: ${[b && `${b} anchor(s) no longer match`, c && `${c} anchor(s) whose code changed after the page was written`].filter(Boolean).join(', ')}.`,
11
11
  chose: 'Chose', fromPage: 'Sent by the page’s own script', waiting: 'Waiting for the agent', you: 'You',
12
12
  state: { listening: 'Listening', working: 'Working', idle: 'Stopped listening', stale: 'No reply yet', offline: 'Not listening', closed: 'Closed' },
@@ -229,7 +229,9 @@
229
229
  chip.hidden = !st;
230
230
  const { changed, broken } = r.counts;
231
231
  chip.dataset.state = st || 'ok';
232
- $('checkText').textContent = broken ? S.broken(broken) + (changed ? `, ${S.changed(changed)}` : '') : changed ? S.changed(changed) : S.ok;
232
+ // name what is stale: the map, a draft or another page
233
+ const what = state.page === 'index.html' ? 'Map' : state.page.startsWith('drafts/') ? 'Draft' : 'Page';
234
+ $('checkText').textContent = broken ? S.broken(broken, what) + (changed ? `, ${S.changed(changed, what).toLowerCase()}` : '') : changed ? S.changed(changed, what) : S.ok;
233
235
  chip.title = st ? 'Ask the agent to update this page' : `${S.ok}: ${r.counts.ok} boxes checked`;
234
236
  if (!st) $('checkText').textContent = '';
235
237
  chip.setAttribute('aria-label', st ? $('checkText').textContent : S.ok);
@@ -310,18 +312,30 @@
310
312
  const rows = c.boxes.map((b) => `<button type="button" class="cc-row" data-src="${esc(b.src)}" data-page="${esc(b.pages?.includes(state.page) ? state.page : (b.pages?.[0] || state.page))}"><b>${esc(b.name || b.src.split('#')[1] || b.src)}${b.isNew ? '<span class="cc-new">New</span>' : ''}</b>${d(b.add, b.del)}</button>`).join('');
311
313
  const loose = c.unmapped?.length ? `<details class="cc-loose"><summary>${c.unmapped.length} file${c.unmapped.length > 1 ? 's' : ''} not on the map</summary>${c.unmapped.map((x) => `<div><code>${esc(x.path)}</code>${d(x.add, x.del)}</div>`).join('')}<button type="button" class="text-btn" data-act="map-these">Ask the agent to map these</button></details>` : '';
312
314
  const notDone = c.notDone?.length ? `<p class="cc-warn">Planned, no changes: ${esc(c.notDone.join(', '))}</p>` : '';
313
- return `<div class="cc"><div class="cc-head"><b>Changed ${c.files} file${c.files > 1 ? 's' : ''}</b>${d(c.add, c.del)}</div>${rows ? `<div class="cc-rows">${rows}</div>` : ''}${notDone}${loose}<p class="cc-hint">Click a box to see its diff.</p></div>`;
315
+ return `<div class="cc"><div class="cc-head"><b>Changed ${c.files} file${c.files > 1 ? 's' : ''}</b>${d(c.add, c.del)}</div>${rows ? `<div class="cc-rows">${rows}</div>` : ''}${notDone}${loose}<p class="cc-hint">Click a box name above to see its diff.</p></div>`;
314
316
  }
315
317
  let latestChanges = null;
316
318
  function showChangeBadges() {
317
319
  toFrame({ type: 'changes', on: false, items: latestChanges ? latestChanges.boxes.filter((b) => !b.pages || b.pages.includes(state.page)).map((b) => ({ src: b.src, add: b.add, del: b.del, isNew: !!b.isNew })) : [] });
318
320
  }
321
+ // The server keeps one changes card per turn and updates it in place as the turn goes on.
322
+ function updateEntry(e) {
323
+ const i = state.history.findIndex((h) => h.id === e.id);
324
+ if (i === -1) { state.history.push(e); appendEntry(e, true, true); return; }
325
+ state.history[i] = e;
326
+ const el = msgsEl.querySelector(`.msg[data-id="${CSS.escape(e.id)}"]`);
327
+ if (!el || e.kind !== 'changes' || !e.changes) { renderAll(); return; }
328
+ el.innerHTML = changesCard(e.changes);
329
+ // the map's badges follow the newest card
330
+ const last = [...state.history].reverse().find((h) => h.kind === 'changes' && h.changes);
331
+ if (last === e) { latestChanges = e.changes; if (showingChanges()) loadChanges(); else showChangeBadges(); }
332
+ }
319
333
  function appendEntry(e, scroll = true, live = false) {
320
334
  msgsEl.querySelector('.intro')?.remove();
321
335
  if (e.role !== lastRole) { msgsEl.appendChild(whoLine(e.role, e.at, e.agent)); lastRole = e.role; }
322
336
  const el = document.createElement('div');
323
337
  if (e.kind === 'changes' && e.changes) {
324
- el.className = 'msg agent';
338
+ el.className = 'msg agent'; if (e.id) el.dataset.id = e.id;
325
339
  el.innerHTML = changesCard(e.changes);
326
340
  latestChanges = e.changes; showChangeBadges();
327
341
  msgsEl.appendChild(el); renderWorking(); if (scroll) scrollChat();
@@ -1002,6 +1016,9 @@
1002
1016
  } else if (d.type === 'chat') {
1003
1017
  state.history.push(d.entry); appendEntry(d.entry, true, true);
1004
1018
  if (d.entry.role === 'agent') state.lastAgentEvent = Date.now();
1019
+ } else if (d.type === 'chat-update') {
1020
+ updateEntry(d.entry);
1021
+ if (d.entry.role === 'agent') state.lastAgentEvent = Date.now();
1005
1022
  } else if (d.type === 'agent') {
1006
1023
  setAgent(d.agent);
1007
1024
  } else if (d.type === 'delivered') {