truemap-cli 0.5.1 → 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.
@@ -0,0 +1,93 @@
1
+ // Can people read it? The colour tokens a project ends up with (kit + .truemap/assets/theme.css), light and
2
+ // dark, and the pairs that must stay readable.
3
+
4
+ const NAMED = {
5
+ black: '#000000', white: '#ffffff', gray: '#808080', grey: '#808080', silver: '#c0c0c0', lightgray: '#d3d3d3',
6
+ lightgrey: '#d3d3d3', darkgray: '#a9a9a9', darkgrey: '#a9a9a9', dimgray: '#696969', dimgrey: '#696969',
7
+ gainsboro: '#dcdcdc', whitesmoke: '#f5f5f5', snow: '#fffafa', ivory: '#fffff0', beige: '#f5f5dc', linen: '#faf0e6',
8
+ red: '#ff0000', darkred: '#8b0000', maroon: '#800000', crimson: '#dc143c', tomato: '#ff6347', coral: '#ff7f50',
9
+ orange: '#ffa500', darkorange: '#ff8c00', gold: '#ffd700', yellow: '#ffff00', khaki: '#f0e68c',
10
+ green: '#008000', darkgreen: '#006400', lime: '#00ff00', olive: '#808000', teal: '#008080', seagreen: '#2e8b57',
11
+ blue: '#0000ff', navy: '#000080', darkblue: '#00008b', royalblue: '#4169e1', steelblue: '#4682b4',
12
+ skyblue: '#87ceeb', lightblue: '#add8e6', dodgerblue: '#1e90ff', cyan: '#00ffff', aqua: '#00ffff',
13
+ purple: '#800080', indigo: '#4b0082', violet: '#ee82ee', magenta: '#ff00ff', fuchsia: '#ff00ff', pink: '#ffc0cb',
14
+ brown: '#a52a2a', chocolate: '#d2691e', tan: '#d2b48c', slategray: '#708090', slategrey: '#708090',
15
+ };
16
+ /** [r, g, b] 0-255 for hex, rgb(), hsl() and named colours; null when it can't be read. */
17
+ function hex(c) {
18
+ let v = String(c ?? '').trim().toLowerCase();
19
+ if (NAMED[v]) v = NAMED[v];
20
+ const m = v.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/);
21
+ if (m) {
22
+ const h = m[1].length <= 4 ? [...m[1].slice(0, 3)].map((x) => x + x).join('') : m[1].slice(0, 6);
23
+ return [0, 2, 4].map((i) => parseInt(h.slice(i, i + 2), 16));
24
+ }
25
+ const num = (x, max) => (x.endsWith('%') ? (parseFloat(x) / 100) * max : parseFloat(x));
26
+ const r = v.match(/^rgba?\(\s*([\d.]+%?)[\s,]+([\d.]+%?)[\s,]+([\d.]+%?)/);
27
+ if (r) return [r[1], r[2], r[3]].map((x) => Math.round(Math.min(255, num(x, 255))));
28
+ const h = v.match(/^hsla?\(\s*([\d.]+)(?:deg)?[\s,]+([\d.]+)%[\s,]+([\d.]+)%/);
29
+ if (h) {
30
+ const H = (+h[1] % 360) / 360; const S = +h[2] / 100; const L = +h[3] / 100;
31
+ const q = L < 0.5 ? L * (1 + S) : L + S - L * S; const p = 2 * L - q;
32
+ const t = (x) => { x = (x + 1) % 1; return x < 1 / 6 ? p + (q - p) * 6 * x : x < 1 / 2 ? q : x < 2 / 3 ? p + (q - p) * (2 / 3 - x) * 6 : p; };
33
+ return [t(H + 1 / 3), t(H), t(H - 1 / 3)].map((x) => Math.round(x * 255));
34
+ }
35
+ return null;
36
+ }
37
+ const lum = (rgb) => {
38
+ const [r, g, b] = rgb.map((v) => { v /= 255; return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4; });
39
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;
40
+ };
41
+ export function ratio(a, b) {
42
+ const x = hex(a); const y = hex(b);
43
+ if (!x || !y) return null;
44
+ const [hi, lo] = [lum(x), lum(y)].sort((p, q) => q - p);
45
+ return (hi + 0.05) / (lo + 0.05);
46
+ }
47
+
48
+ /** The --tm-* values in effect, for light and for dark (later rules win, dark builds on light). */
49
+ export function tokens(css) {
50
+ const light = {}; const dark = {};
51
+ const take = (body, into) => { for (const m of body.matchAll(/(--tm-[\w-]+)\s*:\s*([^;}]+)/g)) into[m[1]] = m[2].trim(); };
52
+ const plain = css.replace(/\/\*[\s\S]*?\*\//g, '');
53
+ const re = /@media\s*\(\s*prefers-color-scheme\s*:\s*dark\s*\)\s*\{/g;
54
+ let at = 0; let m;
55
+ while ((m = re.exec(plain))) {
56
+ for (const r of plain.slice(at, m.index).matchAll(/:root[^{]*\{([^}]*)\}/g)) take(r[1], light);
57
+ let depth = 1; let i = re.lastIndex;
58
+ for (; i < plain.length && depth; i++) { if (plain[i] === '{') depth++; else if (plain[i] === '}') depth--; }
59
+ for (const r of plain.slice(re.lastIndex, i).matchAll(/:root[^{]*\{([^}]*)\}/g)) take(r[1], dark);
60
+ at = i; re.lastIndex = i;
61
+ }
62
+ for (const r of plain.slice(at).matchAll(/:root[^{]*\{([^}]*)\}/g)) take(r[1], light);
63
+ return { light, dark: { ...light, ...dark } };
64
+ }
65
+
66
+ const PAIRS = [
67
+ ['--tm-text', '--tm-paper', 4.5, 'body text on the page'],
68
+ ['--tm-ink', '--tm-sheet', 4.5, 'box titles'],
69
+ ['--tm-ink', '--tm-mark', 4.5, 'text on the highlighter'],
70
+ ['--tm-text', '--tm-wash', 4.5, 'text on quiet fills'],
71
+ ['--tm-ink', '--tm-chrome', 4.5, 'the workspace bar'],
72
+ ['--tm-graphite', '--tm-paper', 4.5, 'secondary text'],
73
+ ['--tm-pencil', '--tm-paper', 2.5, 'hints'],
74
+ ['--tm-accent-text', '--tm-accent', 4.5, 'text on the primary button'],
75
+ ['--tm-changed', '--tm-paper', 3, '"changed" marks'],
76
+ ['--tm-broken', '--tm-paper', 3, '"broken" marks'],
77
+ ['--tm-fine', '--tm-paper', 3, '"fine" and "new" marks'],
78
+ ['--tm-rule-strong', '--tm-paper', 1.3, 'box borders'],
79
+ ];
80
+
81
+ /** Pairs that are too faint to read, as plain notes. */
82
+ export function contrastNotes(css) {
83
+ const t = tokens(css); const notes = [];
84
+ for (const [mode, vals] of [['light', t.light], ['dark', t.dark]]) {
85
+ const val = (k) => { let v = vals[k]; for (let n = 0; n < 4 && /^var\(/.test(v || ''); n++) v = vals[(v.match(/var\(\s*(--tm-[\w-]+)/) || [])[1]]; return v; };
86
+ for (const [fg, bg, min, what] of PAIRS) {
87
+ const r = ratio(val(fg), val(bg));
88
+ if (r == null) { notes.push(`${mode}: ${what}: can't read ${hex(val(fg)) ? bg + ' ' + val(bg) : fg + ' ' + val(fg)}; use hex, rgb() or hsl() so it can be checked`); continue; }
89
+ if (r < min) notes.push(`${mode}: ${what} (${fg} ${val(fg)} on ${bg} ${val(bg)}) contrast ${r.toFixed(1)}:1, needs ${min}:1`);
90
+ }
91
+ }
92
+ return notes;
93
+ }
package/src/export.js CHANGED
@@ -21,14 +21,19 @@ export function insideFile(dir, rel) {
21
21
  } catch { return null; }
22
22
  }
23
23
 
24
- /** The page kit as served: a repo's own assets/truemap.css wins; assets/theme.css is appended. */
24
+ /** The project's theme (.truemap/assets/theme.css), or nothing. */
25
+ export function themeCss(root) {
26
+ const theme = insideFile(join(root, FOLDER), 'assets/theme.css');
27
+ return theme ? `\n/* .truemap/assets/theme.css */\n${readFileSync(theme, 'utf8')}` : '';
28
+ }
29
+ /** Colours and fonts in effect: truemap's tokens, then the project's theme. The workspace uses these too. */
30
+ export function tokensCss(root) {
31
+ return readFileSync(join(KIT_DIR, 'tokens.css'), 'utf8') + themeCss(root);
32
+ }
33
+ /** The page kit as served: tokens, components, theme. A repo's own assets/truemap.css (older setups) replaces the first two. */
25
34
  export function kitCss(root) {
26
- const folder = join(root, FOLDER);
27
- const own = insideFile(folder, 'assets/truemap.css');
28
- let css = readFileSync(own || join(KIT_DIR, 'truemap.css'), 'utf8');
29
- const theme = insideFile(folder, 'assets/theme.css');
30
- if (theme) css += `\n/* .truemap/assets/theme.css */\n${readFileSync(theme, 'utf8')}`;
31
- return css;
35
+ const own = insideFile(join(root, FOLDER), 'assets/truemap.css');
36
+ return (own ? readFileSync(own, 'utf8') : readFileSync(join(KIT_DIR, 'tokens.css'), 'utf8') + '\n' + readFileSync(join(KIT_DIR, 'truemap.css'), 'utf8')) + themeCss(root);
32
37
  }
33
38
 
34
39
  export function exportPage(root, page) {
package/src/guide.md CHANGED
@@ -19,8 +19,9 @@ FOLDER RULES
19
19
  (payments.html, auth-flow.html). index.html is the blueprint; link module pages from it and back.
20
20
  - Write pages in the user's language.
21
21
  - Link the kit and nothing else: <link rel="stylesheet" href="assets/truemap.css"> (from a subfolder
22
- ../assets/truemap.css). No frameworks, no CDNs, no web fonts, no build step, no inline colours.
23
- The look is fixed on purpose so every map reads the same; .truemap/assets/theme.css may set --tm-accent only.
22
+ ../assets/truemap.css). No frameworks, no CDNs, no web fonts, no build step. Colours only through the kit's
23
+ tokens (var(--tm-ink), var(--tm-accent), …) so the user's light, dark and theme apply.
24
+ The components are fixed; colours and fonts belong to the user (see THE USER'S LOOK).
24
25
 
25
26
  ANCHORS (this is what keeps pages true)
26
27
  - Put data-src="path#name" on every box that stands for real code. path = file or folder relative to the repo
@@ -145,19 +146,43 @@ SHOW WHAT YOU CHANGED (after you edited code)
145
146
  `{{CMD}} check --ok index.html --box <id>`. "Map may be out of date" should only appear for code the map
146
147
  hasn't caught up with, not after every turn of yours.
147
148
 
149
+ THE USER'S LOOK (colours and fonts)
150
+ - When the user asks for other colours or fonts ("warmer", "blue accent", "like our brand", "bigger code font"),
151
+ write .truemap/assets/theme.css: override --tm-* tokens in :root for light and again inside
152
+ @media (prefers-color-scheme: dark) { :root { ... } } for dark. `{{CMD}} theme` lists where the tokens are.
153
+ - It restyles every page, every draft and the workspace around them at once; open tabs update by themselves.
154
+ - Colours and fonts only: never restyle components (boxes, wires, badges). Keep --tm-changed, --tm-broken and
155
+ --tm-fine easy to tell apart; they mean status. Fonts: only ones installed on the machine (no web fonts).
156
+ - Then run `{{CMD}} theme`: it checks contrast in light and dark. If something is hard to read, fix it or tell the
157
+ user which colour and let them decide.
158
+
148
159
  DRAFTS (the everyday way to explain)
149
- - When the user asks how something works, says they don't understand, or you have an idea or a design to show,
150
- draw a draft instead of a long chat answer:
160
+ - When the user asks you to explain something, make a draft and open it:
151
161
  {{CMD}} draft "how a message is routed" creates .truemap/drafts/NNN-how-a-message-is-routed.html
152
162
  Write it, then `{{CMD}} drafts/NNN-….html`: the user's tab switches to it at once and it joins their numbered
153
163
  drafts (the record of what you explained). Keep the chat reply to one or two lines pointing to it.
154
- - A draft is free form, a whole scrolling page if needed: short text, a <figure class="tm-diagram"> (data-plan="new"
155
- draws a proposed box dashed), numbered steps, a comparison table, a decision with its trade-offs, a small
156
- interactive bit, even an <iframe> of the running dev server. Pick what makes this one thing clear.
164
+ - Show it, don't write it. First ask: what would make this obvious at a glance? Then build exactly that, in any
165
+ form HTML can take. The form follows the thing, for example:
166
+ a function one real input traced to its output, with the actual values at each step
167
+ a data structure drawn (inline SVG or plain HTML boxes) with a real example in it
168
+ something over time a timeline or sequence: one lane per actor, what happens when
169
+ a choice the options side by side, what each one costs
170
+ a bug what happens next to what should, at the point where they split
171
+ logic with knobs something to try: an input or a step button running the same logic
172
+ architecture the map component, <figure class="tm-diagram">
173
+ Nothing is required: no fixed sections, no diagram for its own sake. If a picture would not help, the code
174
+ itself with a few notes beside it can be the whole draft.
175
+ - Words are captions and the one line of "why". A draft that is mostly paragraphs should be a picture or a chat
176
+ answer instead.
177
+ - Any HTML, inline <svg>, <style> and <script> are fine; nothing loaded from the network. Colours only through
178
+ these tokens (there are no others):
179
+ --tm-paper (page) --tm-sheet (cards, boxes) --tm-wash (quiet fills) --tm-rule, --tm-rule-strong (lines)
180
+ --tm-ink (titles, emphasis) --tm-text (body) --tm-graphite (secondary) --tm-pencil (hints)
181
+ --tm-accent, --tm-accent-text (the primary action) --tm-mark (highlighter)
182
+ --tm-changed, --tm-broken, --tm-fine (+ -wash) (status only) --tm-font, --tm-code (fonts)
157
183
  - Link boxes on the map from a draft as <a href="../index.html#runs">Runs</a>: the map opens with that box lit.
158
184
  - Drafts are kept; don't delete them. A draft worth keeping for good can move to .truemap/ as a page.
159
- - A request to explain gets a draft, even for a single point: one function can be a short page with its inputs,
160
- what it does step by step, and its edge cases. Short factual questions still get a short chat answer.
185
+ - Short factual questions (which file, which flag, yes or no) still get a short chat answer.
161
186
 
162
187
  POINTING AT THE MAP
163
188
  - While you explain, light up what you are talking about:
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
@@ -1,6 +1,7 @@
1
1
  // The local truemap server: one per repo, started on demand by the CLI, invisible to the user.
2
2
  // Serves the workspace UI, the .truemap pages (with the SDK injected), a chat queue between
3
3
  // the browser and the agent's CLI (listen/reply), and live updates over Server-Sent Events.
4
+ import { spawn } from 'node:child_process';
4
5
  import { createServer, request as httpRequest } from 'node:http';
5
6
  import { randomBytes } from 'node:crypto';
6
7
  import { existsSync, lstatSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, watch } from 'node:fs';
@@ -10,7 +11,7 @@ import { FOLDER, PKG_DIR, VERSION, addrPath, appendPrivate, buildId, stateHome,
10
11
  import { changes, fileDiff, snapshotTree } from './changes.js';
11
12
  import { cleanPlan, currentPlan, parseReport, planCheck, planMessage, planWarnings, readPlan, savePlan, srcOfBox, stepCheck } from './plan.js';
12
13
  import { checkAll, listPages } from './check.js';
13
- import { exportPage, kitCss } from './export.js';
14
+ import { exportPage, kitCss, tokensCss } from './export.js';
14
15
  import { snippet } from './snippet.js';
15
16
 
16
17
  const root = resolve(process.argv[2] || process.cwd());
@@ -68,24 +69,60 @@ async function takeSnapshot(kind, extra = {}) {
68
69
  const changeCache = new Map(); // base -> { at, promise }
69
70
 
70
71
  // ---------- what changed in a turn comes to the user, in the conversation ----------
71
- let lastPostedChanges = snapshots.posted || '';
72
- async function postChanges(base = 'turn') {
73
- if (base === 'turn' && !snapshots.turn) return null;
74
- 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);
75
101
  if (!r || r.error || !r.files) return r;
76
- const key = `${r.base.kind}:${snapshots[r.base.kind]?.tree || ''}:${r.now}`;
77
- if (key === lastPostedChanges) return r;
78
- lastPostedChanges = key; snapshots.posted = key; saveSnapshots();
79
- 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
+ }
80
123
  remember({
81
124
  role: 'agent', kind: 'changes', id: `c${Date.now().toString(36)}${(seq++).toString(36)}`, at: new Date().toISOString(), agent: agentName,
82
- text: `Changed ${r.files} file${r.files > 1 ? 's' : ''}`,
83
- changes: {
84
- base: r.base.kind, label: r.base.label, files: r.files, add: r.add, del: r.del,
85
- 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) })),
86
- unmapped: r.unmapped.flatMap((g) => g.files).slice(0, 30).map((x) => ({ path: x.path, add: x.add, del: x.del })),
87
- notDone: p ? p.planned.filter((x) => !x.changed).map((x) => x.name || x.box) : [],
88
- },
125
+ turn: turnAt, text, changes: summary,
89
126
  });
90
127
  return r;
91
128
  }
@@ -369,6 +406,10 @@ function serveKit(res) {
369
406
  }
370
407
 
371
408
  function serveUi(res, name) {
409
+ if (name === 'tokens.css') {
410
+ res.writeHead(200, { 'Content-Type': 'text/css; charset=utf-8', 'Cache-Control': 'no-store' });
411
+ return res.end(themeable(tokensCss(root)));
412
+ }
372
413
  const file = safeFile(UI_DIR, name);
373
414
  if (!file) return sendText(res, 404, 'not found');
374
415
  const type = MIME[extname(file).toLowerCase()] || 'application/octet-stream';
@@ -526,7 +567,9 @@ const server = createServer(async (req, res) => {
526
567
  if (p === '/api/agent/listen' && req.method === 'POST') {
527
568
  const b = await readBody(req);
528
569
  // the agent listens again: its turn is over, so what it changed goes to the user
529
- 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(); });
530
573
  if (listener) finishListen({ status: 'replaced' });
531
574
  lastAgentActivity = Date.now();
532
575
  noteAgent(b.agent);
@@ -582,12 +625,12 @@ const server = createServer(async (req, res) => {
582
625
  return sendJson(res, 200, { ok: true, browsers: clients.size });
583
626
  }
584
627
  if (p === '/api/agent/changes' && req.method === 'POST') {
585
- // `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.
586
629
  const b = await readBody(req);
587
630
  noteAgent(b.agent);
588
631
  const base = ['turn', 'plan', 'head', 'main'].includes(b.base) ? b.base : 'auto';
589
632
  const r = await changesFor(base, true);
590
- 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);
591
634
  return sendJson(res, 200, { ...r, browsers: clients.size });
592
635
  }
593
636
  if (p === '/api/agent/plan' && req.method === 'POST') {
@@ -612,8 +655,7 @@ const server = createServer(async (req, res) => {
612
655
  const conflicts = sts.filter((x) => x.conflict || x.rewritten);
613
656
  remember({ role: 'agent', id: `a${Date.now().toString(36)}${(seq++).toString(36)}`, at: new Date().toISOString(), agent: agentName, plan: plan.slug,
614
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),
615
- ...(conflicts.length ? ['', '**Check before you trust this report:**', ...conflicts.map((x) => `- Step ${x.n}: ${[x.conflict, x.rewritten].filter(Boolean).join(' ')}`)] : []),
616
- '', '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') });
617
659
  }
618
660
  return sendJson(res, 200, { ok: true, plan: plan.slug, status: plan.status, check });
619
661
  }
@@ -656,8 +698,7 @@ const content = createServer((req, res) => {
656
698
  const p = new URL(req.url, `http://127.0.0.1:${contentPort}`).pathname;
657
699
  try {
658
700
  if (p === '/__truemap/sdk.js') {
659
- const themeSrc = readFileSync(new URL('./theme.js', import.meta.url), 'utf8').replace(/^export /m, '');
660
- const js = `const tmThemeable = (() => {\n${themeSrc}\nreturn themeable;\n})();\n` + [join(UI_DIR, 'wires.js'), join(UI_DIR, 'diagram.js')].map((f) => readFileSync(f, 'utf8')).join('\n;\n')
701
+ const js = [join(UI_DIR, 'wires.js'), join(UI_DIR, 'diagram.js')].map((f) => readFileSync(f, 'utf8')).join('\n;\n')
661
702
  + '\n' + readFileSync(join(UI_DIR, 'sdk.js'), 'utf8').replace('__TRUEMAP_PARENT__', `http://127.0.0.1:${port}`);
662
703
  res.writeHead(200, { 'Content-Type': 'text/javascript; charset=utf-8', 'Cache-Control': 'no-store' });
663
704
  return res.end(js);
@@ -704,5 +745,22 @@ setInterval(() => {
704
745
  if (!listener && (agentState === 'working' || agentState === 'idle') && Date.now() - lastAgentActivity > 20 * 60 * 1000) setAgentState('offline');
705
746
  }, 60_000).unref();
706
747
 
748
+ // truemap's own files can change under a running server (an upgrade in place, a local build). New files
749
+ // served by old code break pages, so the server hands over to a fresh one on the same address at once;
750
+ // open tabs reconnect and reload, and a waiting listen returns 'timeout' so the agent simply listens again.
751
+ let handingOver = false;
752
+ setInterval(() => {
753
+ if (handingOver || buildId() === BUILD) return;
754
+ handingOver = true;
755
+ finishListen({ status: 'timeout' });
756
+ broadcast({ type: 'closing', restart: true });
757
+ try { const st = JSON.parse(readFileSync(statePath, 'utf8')); if (st.pid === process.pid) rmSync(statePath, { force: true }); } catch { /* ignore */ }
758
+ for (const srv of [server, content]) { srv.close(); srv.closeAllConnections?.(); }
759
+ setTimeout(() => {
760
+ spawn(process.execPath, [join(PKG_DIR, 'src', 'server.js'), root], { detached: true, stdio: 'ignore', windowsHide: true, cwd: root }).unref();
761
+ process.exit(0);
762
+ }, 300);
763
+ }, 2000).unref();
764
+
707
765
  process.on('SIGTERM', shutdown);
708
766
  process.on('SIGINT', shutdown);
package/src/theme.js CHANGED
@@ -1,7 +1,6 @@
1
1
  // Dark mode follows the system unless the user picks one. The stylesheets keep plain
2
2
  // `@media (prefers-color-scheme: dark)` blocks; this turns each into rules that also answer to a choice:
3
3
  // <html data-theme="dark"> always dark <html data-theme="light"> always light
4
- // For a shadow root, the host carries the choice as a class instead (tm-dark / tm-light).
5
4
 
6
5
  function blocks(css) {
7
6
  // top-level `@media (prefers-color-scheme: dark) { ... }` blocks, with their positions
@@ -23,24 +22,26 @@ function scopeRules(body, pick) {
23
22
  }
24
23
 
25
24
  /** CSS for a document: dark when chosen, or when the system is dark and light was not chosen. */
26
- export function themeable(css, { host = false } = {}) {
25
+ export function themeable(css) {
27
26
  const found = blocks(css);
28
27
  if (!found.length) return css;
29
- const on = host ? ':host(.tm-dark)' : ':root[data-theme="dark"]';
30
- const notOff = host ? ':host(:not(.tm-light))' : ':root:not([data-theme="light"])';
31
28
  const scope = (prefix) => (sel) => {
32
29
  if (!sel) return '';
33
- if (!host && sel.startsWith(':root')) return prefix + sel.slice(5);
34
- if (!host && /^html\b/.test(sel)) return prefix.replace(':root', 'html') + sel.slice(4);
30
+ if (sel.startsWith(':root')) return prefix + sel.slice(5);
31
+ if (/^html\b/.test(sel)) return prefix.replace(':root', 'html') + sel.slice(4);
35
32
  return `${prefix} ${sel}`;
36
33
  };
37
34
  let out = ''; let at = 0; const forced = [];
38
35
  for (const b of found) {
39
36
  const body = css.slice(b.bodyStart, b.end - 1);
40
- out += css.slice(at, b.bodyStart) + scopeRules(body, scope(notOff)) + '}';
41
- forced.push(scopeRules(body, scope(on)));
37
+ out += css.slice(at, b.bodyStart) + scopeRules(body, scope(':root:not([data-theme="light"])')) + '}';
38
+ forced.push(scopeRules(body, scope(':root[data-theme="dark"]')));
42
39
  at = b.end;
43
40
  }
44
- const scheme = host ? '' : ':root[data-theme="light"] { color-scheme: light; }\n:root[data-theme="dark"] { color-scheme: dark; }\n';
45
- return `${out}${css.slice(at)}\n/* the user's choice */\n${scheme}${forced.join('\n')}\n`;
41
+ return `${out}${css.slice(at)}
42
+ /* the user's choice */
43
+ :root[data-theme="light"] { color-scheme: light; }
44
+ :root[data-theme="dark"] { color-scheme: dark; }
45
+ ${forced.join('\n')}
46
+ `;
46
47
  }