truemap-cli 0.3.0 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +31 -27
- package/kit/fonts/OFL-commit-mono.txt +90 -0
- package/kit/fonts/OFL-instrument-sans.txt +93 -0
- package/kit/fonts/commit-mono-latin-400-normal.woff2 +0 -0
- package/kit/fonts/instrument-sans-latin-400-normal.woff2 +0 -0
- package/kit/fonts/instrument-sans-latin-500-normal.woff2 +0 -0
- package/kit/fonts/instrument-sans-latin-600-normal.woff2 +0 -0
- package/kit/truemap.css +183 -62
- package/package.json +1 -1
- package/skills/truemap/SKILL.md +10 -5
- package/src/changes.js +164 -0
- package/src/check.js +102 -8
- package/src/cli.js +234 -18
- package/src/common.js +15 -1
- package/src/export.js +2 -2
- package/src/guide.md +150 -115
- package/src/plan.js +185 -0
- package/src/server.js +285 -30
- package/src/snippet.js +63 -0
- package/src/theme.js +46 -0
- package/src/ui/diagram.js +598 -0
- package/src/ui/sdk.js +402 -53
- package/src/ui/wires.js +114 -22
- package/src/ui/workspace.css +376 -157
- package/src/ui/workspace.html +29 -14
- package/src/ui/workspace.js +592 -76
package/src/check.js
CHANGED
|
@@ -6,7 +6,8 @@
|
|
|
6
6
|
import { execFileSync } from 'node:child_process';
|
|
7
7
|
import { existsSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';
|
|
8
8
|
import { join, relative, resolve, sep } from 'node:path';
|
|
9
|
-
import {
|
|
9
|
+
import { createHash } from 'node:crypto';
|
|
10
|
+
import { FOLDER, gitExe, verifiedPath } from './common.js';
|
|
10
11
|
|
|
11
12
|
const META_RE = /<meta\s+name=["']truemap-verified["']\s+content=["']([^"']*)["']\s*\/?>/i;
|
|
12
13
|
const ANCHOR_RE = /\bdata-src\s*=\s*(?:"([^"]*)"|'([^']*)')/gi;
|
|
@@ -51,7 +52,10 @@ export function listPages(root) {
|
|
|
51
52
|
};
|
|
52
53
|
walk(base);
|
|
53
54
|
out.sort((a, b) => (a === 'index.html' ? -1 : b === 'index.html' ? 1 : a.localeCompare(b)));
|
|
54
|
-
return out.map((page) =>
|
|
55
|
+
return out.map((page) => {
|
|
56
|
+
let at = 0; try { const st = statSync(join(base, page)); at = Math.round(st.birthtimeMs || st.mtimeMs); } catch { /* gone */ }
|
|
57
|
+
return { page, title: readTitle(join(base, page)) || page.replace(/\.html?$/i, ''), at };
|
|
58
|
+
});
|
|
55
59
|
}
|
|
56
60
|
|
|
57
61
|
function readTitle(file) {
|
|
@@ -102,7 +106,9 @@ export function createContext(root) {
|
|
|
102
106
|
if (entry[0] === 'R' || entry[0] === 'C') i++;
|
|
103
107
|
}
|
|
104
108
|
}
|
|
105
|
-
|
|
109
|
+
let records = {};
|
|
110
|
+
try { records = JSON.parse(readFileSync(verifiedPath(root), 'utf8')); } catch { records = {}; }
|
|
111
|
+
return { root, gitRepo, files, dirty, head, contents: new Map(), times: new Map(), records, recordsDirty: false, prints: new Map() };
|
|
106
112
|
}
|
|
107
113
|
|
|
108
114
|
function onDisk(root, p) { try { statSync(join(root, p)); return true; } catch { return false; } }
|
|
@@ -177,6 +183,31 @@ function changeTime(ctx, p) {
|
|
|
177
183
|
return t;
|
|
178
184
|
}
|
|
179
185
|
|
|
186
|
+
// What an anchor's code looks like now: a hash of the file, or of a folder's file list with sizes and times.
|
|
187
|
+
// Drift is judged per anchor against the fingerprint taken when the box was last known to match, so editing
|
|
188
|
+
// the page (to add one box) does not quietly clear drift on the others.
|
|
189
|
+
function fingerprint(ctx, p) {
|
|
190
|
+
const clean = p.replace(/\/+$/, '');
|
|
191
|
+
if (ctx.prints.has(clean)) return ctx.prints.get(clean);
|
|
192
|
+
const h = createHash('sha1');
|
|
193
|
+
const full = join(ctx.root, clean);
|
|
194
|
+
try {
|
|
195
|
+
const st = statSync(full);
|
|
196
|
+
if (!st.isDirectory()) h.update(st.size > MAX_SCAN_BYTES ? `${st.size}:${st.mtimeMs}` : readFileSync(full));
|
|
197
|
+
else {
|
|
198
|
+
const list = ctx.files ? [...ctx.files].filter((x) => x.startsWith(`${clean}/`)).sort() : [];
|
|
199
|
+
for (const x of list) { try { const t = statSync(join(ctx.root, x)); h.update(`${x}\0${t.size}\0${Math.floor(t.mtimeMs)}\n`); } catch { /* gone */ } }
|
|
200
|
+
}
|
|
201
|
+
} catch { h.update('missing'); }
|
|
202
|
+
const out = h.digest('hex').slice(0, 16);
|
|
203
|
+
ctx.prints.set(clean, out);
|
|
204
|
+
return out;
|
|
205
|
+
}
|
|
206
|
+
function saveRecords(ctx) {
|
|
207
|
+
if (!ctx.recordsDirty) return;
|
|
208
|
+
try { writeFileSync(verifiedPath(ctx.root), JSON.stringify(ctx.records)); ctx.recordsDirty = false; } catch { /* ignore */ }
|
|
209
|
+
}
|
|
210
|
+
|
|
180
211
|
function escapeRe(s) { return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); }
|
|
181
212
|
|
|
182
213
|
/** True/false, or null when the file is too large to scan (then we don't call it broken). */
|
|
@@ -215,15 +246,25 @@ export function checkPage(ctx, page) {
|
|
|
215
246
|
if (name && !isDir && hasWholeWord(ctx, path, name) === false) {
|
|
216
247
|
return { src, path, name, state: 'broken', reason: `"${name}" no longer appears in ${path}` };
|
|
217
248
|
}
|
|
249
|
+
const key = `${page}|${src}`;
|
|
250
|
+
const fp = fingerprint(ctx, path);
|
|
251
|
+
const rec = ctx.records[key];
|
|
252
|
+
const since = ctx.records[`@${key}`] || (pageTime ? new Date(pageTime * 1000).toISOString() : null);
|
|
253
|
+
if (rec !== undefined) {
|
|
254
|
+
return rec === fp ? { src, path, name, state: 'ok', reason: '' } : { src, path, name, state: 'changed', since, reason: `${path} changed since this box was last checked` };
|
|
255
|
+
}
|
|
256
|
+
// No fingerprint yet: fall back to times (code newer than the page), then remember the code as it is.
|
|
218
257
|
const t = changeTime(ctx, path.replace(/\/+$/, ''));
|
|
219
258
|
if (t !== null && pageTime && t > pageTime) {
|
|
220
|
-
return { src, path, name, state: 'changed', reason: `${path} changed after this page was last updated` };
|
|
259
|
+
return { src, path, name, state: 'changed', since, reason: `${path} changed after this page was last updated` };
|
|
221
260
|
}
|
|
261
|
+
ctx.records[key] = fp; ctx.records[`@${key}`] = new Date().toISOString(); ctx.recordsDirty = true;
|
|
222
262
|
return { src, path, name, state: 'ok', reason: '' };
|
|
223
263
|
});
|
|
224
264
|
const counts = { ok: 0, changed: 0, broken: 0 };
|
|
225
265
|
for (const a of anchors) counts[a.state]++;
|
|
226
|
-
|
|
266
|
+
const wireCount = [...html.matchAll(/\sdata-to\s*=\s*["']([^"']*)["']/gi)].reduce((n, m) => n + m[1].split(/[\s,]+/).filter(Boolean).length, 0);
|
|
267
|
+
return { page, anchors, counts, wires: checkWires(html), wireCount, layout: checkLayout(html) };
|
|
227
268
|
}
|
|
228
269
|
|
|
229
270
|
/** Maps that are too big to read at a glance (the guide: at most 12 boxes per map, 4 per layer). */
|
|
@@ -233,12 +274,48 @@ export function checkLayout(html) {
|
|
|
233
274
|
const maps = html.split(/class=["'][^"']*\btm-(?:map|blueprint)(?![-\w])/).slice(1);
|
|
234
275
|
maps.forEach((body, i) => {
|
|
235
276
|
const total = (body.match(NODE) || []).length;
|
|
236
|
-
if (total >
|
|
277
|
+
if (total > 16) notes.push(`map ${i + 1} has ${total} boxes; 16 is the most a map can carry, move the detail to a module page`);
|
|
237
278
|
body.split(/class=["'][^"']*\btm-layer(?![-\w])/).slice(1).forEach((layer, j) => {
|
|
238
279
|
const n = (layer.match(NODE) || []).length;
|
|
239
280
|
if (n > 4) notes.push(`map ${i + 1}, layer ${j + 1} has ${n} boxes; keep it to 4`);
|
|
240
281
|
});
|
|
241
282
|
});
|
|
283
|
+
return notes.concat(lintDiagrams(html));
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** The rules of a v0.5 map (figure.tm-diagram), checked so a page that breaks them is told why. */
|
|
287
|
+
export function lintDiagrams(html) {
|
|
288
|
+
const notes = [];
|
|
289
|
+
const attr = (tag, name) => { const m = tag.match(new RegExp(`\\s${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`, 'i')); return m ? decodeEntities(m[1] ?? m[2] ?? '') : null; };
|
|
290
|
+
const figs = html.split(/<figure\b[^>]*class=["'][^"']*\btm-diagram\b[^"']*["'][^>]*>/i).slice(1).map((b) => b.split(/<\/figure>/i)[0]);
|
|
291
|
+
figs.forEach((body, i) => {
|
|
292
|
+
const where = figs.length > 1 ? `map ${i + 1}: ` : 'map: ';
|
|
293
|
+
const nodes = [...body.matchAll(/<(?:div|a)\b[^>]*class=["'][^"']*\btm-node\b[^"']*["'][^>]*>/gi)].map((m) => m[0]);
|
|
294
|
+
const ids = new Set(nodes.map((t) => attr(t, 'id')).filter(Boolean));
|
|
295
|
+
if (nodes.length > 16) notes.push(`${where}${nodes.length} boxes; 16 is the most a map can carry. Merge minor neighbours or give a part its own page.`);
|
|
296
|
+
const groups = (body.match(/<section\b[^>]*class=["'][^"']*\btm-group\b/gi) || []).length;
|
|
297
|
+
if (!groups && nodes.length > 4) notes.push(`${where}no groups. Put the boxes in <section class="tm-group" data-label="…"> by responsibility.`);
|
|
298
|
+
for (const sec of body.matchAll(/<section\b[^>]*class=["'][^"']*\btm-group\b[^>]*>([\s\S]*?)<\/section>/gi)) {
|
|
299
|
+
const n = (sec[1].match(/class=["'][^"']*\btm-node\b/gi) || []).length;
|
|
300
|
+
const label = sec[0].match(/data-label=["']([^"']+)/)?.[1] || 'a group';
|
|
301
|
+
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
|
+
}
|
|
303
|
+
const outside = body.replace(/<section\b[^>]*class=["'][^"']*\btm-group\b[\s\S]*?<\/section>/gi, '');
|
|
304
|
+
const loose = (outside.match(/class=["'][^"']*\btm-node\b/gi) || []).length;
|
|
305
|
+
if (groups && loose) notes.push(`${where}${loose} box(es) outside any group; every box belongs to one group.`);
|
|
306
|
+
for (const t of nodes) {
|
|
307
|
+
const id = attr(t, 'id'); const name = attr(t, 'data-name'); const tag = attr(t, 'data-tag'); const label = name || id || '(a box)';
|
|
308
|
+
if (!id) notes.push(`${where}a box without an id ("${label}"); connections and flows need ids.`);
|
|
309
|
+
if (!name) notes.push(`${where}box "${id}" has no data-name.`);
|
|
310
|
+
else if (name.split(/\s+/).length > 4 || name.length > 28) notes.push(`${where}box name "${name}" is long; use 1-3 words from the code and put the rest in .tm-detail.`);
|
|
311
|
+
if (tag && (tag.split(/\s+/).length > 4 || tag.length > 32)) notes.push(`${where}tag "${tag}" on "${label}" is long; one short word or path fragment.`);
|
|
312
|
+
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
|
+
}
|
|
314
|
+
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.`);
|
|
316
|
+
}
|
|
317
|
+
});
|
|
318
|
+
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="…".');
|
|
242
319
|
return notes;
|
|
243
320
|
}
|
|
244
321
|
|
|
@@ -260,20 +337,37 @@ export function checkWires(html) {
|
|
|
260
337
|
export function checkAll(root, pages) {
|
|
261
338
|
const ctx = createContext(root);
|
|
262
339
|
const list = pages ?? listPages(root).map((p) => p.page);
|
|
263
|
-
|
|
340
|
+
const results = list.map((p) => checkPage(ctx, p));
|
|
341
|
+
saveRecords(ctx);
|
|
342
|
+
return { gitRepo: ctx.gitRepo, results };
|
|
264
343
|
}
|
|
265
344
|
|
|
266
345
|
/** Stamps the page as reviewed now, which clears its "changed" marks. */
|
|
267
|
-
export function markOk(root, page) {
|
|
346
|
+
export function markOk(root, page, boxes) {
|
|
268
347
|
const rel = pageInFolder(root, page);
|
|
269
348
|
if (!rel) return false;
|
|
270
349
|
const file = join(root, FOLDER, rel);
|
|
271
350
|
if (!existsSync(file)) return false;
|
|
272
351
|
let html = readFileSync(file, 'utf8');
|
|
273
352
|
const tag = `<meta name="truemap-verified" content="${new Date().toISOString()}">`;
|
|
353
|
+
if (boxes?.length) { // one box: its fingerprint only
|
|
354
|
+
const ctx = createContext(root);
|
|
355
|
+
const only = new Set(boxes.flatMap((b) => { const t = html.match(new RegExp(`<[^>]*\\sid=["']${escapeRe(b)}["'][^>]*>`))?.[0]; return [b, t?.match(/data-src=["']([^"']+)/)?.[1]].filter(Boolean); }));
|
|
356
|
+
const anchors = extractAnchors(html);
|
|
357
|
+
const unknown = boxes.filter((b) => !anchors.includes(b) && !anchors.some((a) => only.has(a) && html.includes(`id="${b}"`)));
|
|
358
|
+
if (unknown.length) throw new Error(`no box with an anchor named ${unknown.join(', ')} on ${rel} (use a box id or its data-src)`);
|
|
359
|
+
for (const src of extractAnchors(html)) { if (!only.has(src)) continue; const { path } = parseAnchor(src); if (path) { ctx.records[`${rel}|${src}`] = fingerprint(ctx, path); ctx.records[`@${rel}|${src}`] = new Date().toISOString(); } }
|
|
360
|
+
ctx.recordsDirty = true; saveRecords(ctx);
|
|
361
|
+
return true;
|
|
362
|
+
}
|
|
274
363
|
if (META_RE.test(html)) html = html.replace(META_RE, tag);
|
|
275
364
|
else if (/<head[^>]*>/i.test(html)) html = html.replace(/<head[^>]*>/i, (m) => `${m}\n${tag}`);
|
|
276
365
|
else html = `${tag}\n${html}`;
|
|
277
366
|
writeFileSync(file, html);
|
|
367
|
+
// every box on the page matches its code as it is now
|
|
368
|
+
const ctx = createContext(root);
|
|
369
|
+
const only = boxes?.length ? new Set(boxes.flatMap((b) => { const tag = html.match(new RegExp(`<[^>]*\\sid=["']${escapeRe(b)}["'][^>]*>`))?.[0]; return [b, tag?.match(/data-src=["']([^"']+)/)?.[1]].filter(Boolean); })) : null;
|
|
370
|
+
for (const src of extractAnchors(html)) { if (only && !only.has(src)) continue; const { path } = parseAnchor(src); if (path) { ctx.records[`${rel}|${src}`] = fingerprint(ctx, path); ctx.records[`@${rel}|${src}`] = new Date().toISOString(); } }
|
|
371
|
+
ctx.recordsDirty = true; saveRecords(ctx);
|
|
278
372
|
return true;
|
|
279
373
|
}
|
package/src/cli.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
// truemap CLI. Output is plain YAML-ish text written for agents: what happened + next_step.
|
|
2
2
|
import { spawn } from 'node:child_process';
|
|
3
|
-
import { closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, statSync } from 'node:fs';
|
|
3
|
+
import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readdirSync, rmSync, statSync } from 'node:fs';
|
|
4
4
|
import { request as httpRequest } from 'node:http';
|
|
5
5
|
import { isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
6
6
|
import {
|
|
7
|
-
FOLDER, IS_WIN, PKG_DIR, VERSION, detectAgent, findRoot, folderPath, logUsage, readJson,
|
|
7
|
+
FOLDER, IS_WIN, PKG_DIR, VERSION, buildId, detectAgent, findRoot, folderPath, logUsage, readJson,
|
|
8
8
|
samePath, serverLockPath, serverStatePath,
|
|
9
9
|
} from './common.js';
|
|
10
10
|
import { checkAll, listPages, markOk, pageInFolder } from './check.js';
|
|
@@ -58,9 +58,10 @@ async function liveState(root) {
|
|
|
58
58
|
|
|
59
59
|
async function ensureServer(root) {
|
|
60
60
|
let state = await liveState(root);
|
|
61
|
-
if (state && state.version !== VERSION) {
|
|
62
|
-
|
|
63
|
-
await
|
|
61
|
+
if (state && (state.version !== VERSION || (state.build && state.build !== buildId()) || !state.build)) {
|
|
62
|
+
// Older code: restart on the same address; the open tab reconnects and reloads itself.
|
|
63
|
+
try { await call(state, 'POST', '/api/agent/shutdown', { restart: true }, { timeoutMs: 1500 }); } catch { /* ignore */ }
|
|
64
|
+
for (let i = 0; i < 30; i++) { await sleep(100); try { process.kill(state.pid, 0); } catch { break; } }
|
|
64
65
|
state = null;
|
|
65
66
|
}
|
|
66
67
|
if (state) return state;
|
|
@@ -141,13 +142,13 @@ function agentLoopHint() {
|
|
|
141
142
|
|
|
142
143
|
function printCheck(result, indent = '') {
|
|
143
144
|
const bad = result.anchors.filter((a) => a.state !== 'ok');
|
|
144
|
-
out(`${indent}check: ${result.counts.ok} ok, ${result.counts.changed} changed, ${result.counts.broken} broken`);
|
|
145
|
+
out(`${indent}check: ${result.counts.ok} ok, ${result.counts.changed} changed, ${result.counts.broken} broken${result.wireCount ? `; wires: ${result.wireCount - (result.wires || []).length} of ${result.wireCount} drawn` : ''}`);
|
|
145
146
|
for (const a of bad) out(`${indent} - ${a.state}: ${q(a.src)} # ${a.reason}`);
|
|
146
147
|
for (const w of result.wires || []) out(`${indent} - wire not drawn: ${q(w.from)} -> ${q(w.to)} # ${w.reason}`);
|
|
147
148
|
for (const l of result.layout || []) out(`${indent} - layout: ${l}`);
|
|
148
149
|
}
|
|
149
150
|
|
|
150
|
-
const SETUP_NOTE = `
|
|
151
|
+
const SETUP_NOTE = `This project has a map in \`${FOLDER}/\` (index.html), checked against the code with truemap. Before a change that touches 3+ boxes on the map or adds one, show the plan first: \`${CMD} plan --file plan.json\`, and wait for approval. After editing code, run \`${CMD} changes\` so the user can review what changed, by box. Before explaining architecture or a flow, update the page that covers it and run \`${CMD} <page>\`. Run \`${CMD} guide\` for the details. Always also give a 1-3 line answer in the terminal.`;
|
|
151
152
|
|
|
152
153
|
// ---------- commands ----------
|
|
153
154
|
async function cmdOpen(root, args, opts = {}) {
|
|
@@ -185,7 +186,7 @@ async function cmdOpen(root, args, opts = {}) {
|
|
|
185
186
|
block('setup_note', `Add this note to CLAUDE.md and AGENTS.md (create the section if missing) so future sessions use ${FOLDER}/:\n\n${SETUP_NOTE}`);
|
|
186
187
|
}
|
|
187
188
|
const steps = [];
|
|
188
|
-
if (!page) steps.push(`No pages yet. Run \`${CMD} outline\` for a fast map of the repo and \`${CMD} guide\` for the
|
|
189
|
+
if (!page) steps.push(`No pages yet. Run \`${CMD} outline\` for a fast map of the repo and \`${CMD} guide\` for the format, write ${FOLDER}/index.html (one map, 7-12 boxes in groups), then run \`${CMD} index.html\`. Show a first map within a few minutes; go deeper only when the user asks.`);
|
|
189
190
|
else {
|
|
190
191
|
const r = checkAll(root, [page]).results[0];
|
|
191
192
|
if (r.counts.broken) steps.push('Fix the broken anchors first: update the page (or its data-src) to match the code.');
|
|
@@ -246,7 +247,7 @@ async function doListen(root, opts) {
|
|
|
246
247
|
r = await call(state, 'POST', '/api/agent/listen', { timeoutMs, agent: detectAgent() });
|
|
247
248
|
} catch {
|
|
248
249
|
out('status: interrupted');
|
|
249
|
-
block('next_step',
|
|
250
|
+
block('next_step', 'The truemap server stopped (the user closed it, or `truemap stop` ran). Continue in the terminal. Do not reopen the page unless the user asks.');
|
|
250
251
|
return;
|
|
251
252
|
}
|
|
252
253
|
const b = r.body || {};
|
|
@@ -255,11 +256,38 @@ async function doListen(root, opts) {
|
|
|
255
256
|
formatMessages(b.messages);
|
|
256
257
|
const decided = b.messages.filter((m) => m.kind === 'answer' && m.from === 'user');
|
|
257
258
|
if (decided.length) block('decision_note', 'The user made a decision on the page. Act on it, and record it on the relevant page (what was chosen and why) so it stays with the project.');
|
|
259
|
+
const bg = detectAgent() === 'claude-code' ? ' with run_in_background' : '';
|
|
260
|
+
if (b.messages.some((m) => m.kind === 'approval')) {
|
|
261
|
+
block('next_step', [
|
|
262
|
+
'The user APPROVED your plan. Build it now; changes are measured from this moment.',
|
|
263
|
+
`While you build, post short status lines with \`${CMD} progress "…"\`; no reply is needed to start.`,
|
|
264
|
+
`When done: put new boxes on the page for real (with data-src), run \`${CMD} plan --done\` and \`${CMD} changes\`, then \`${CMD} reply "<what you built, and anything you did not>" --listen\`${bg}.`,
|
|
265
|
+
].join('\n'));
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
if (b.messages.some((m) => m.kind === 'plan_rejected')) {
|
|
269
|
+
block('next_step', `The user REJECTED your plan. Do not build it. Ask in one short reply what they want instead (\`${CMD} reply "…" --listen\`${bg}).`);
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
if (b.plan_waiting) block('plan_note', `Your plan "${b.plan_waiting}" is waiting for approval. If the user approves it in this message (approve, OK, go, yes, 同意, 可以, 开始), run \`${CMD} plan --approve\` first, then build. If they reject it, drop it.`);
|
|
273
|
+
if (b.messages.some((m) => m.kind === 'plan_changes')) {
|
|
274
|
+
block('next_step', [
|
|
275
|
+
'The user asked for changes to your plan. Do not build yet.',
|
|
276
|
+
`1) Answer the comments in one short \`${CMD} reply "…"\` (without --listen).`,
|
|
277
|
+
`2) Write the revised plan (same title) and run \`${CMD} plan --file <plan.json>\`; it shows in the conversation by itself, with what changed.`,
|
|
278
|
+
`3) Then \`${CMD} listen\`${bg} for the approval. Only one listen runs at a time; a new one replaces the old.`,
|
|
279
|
+
].join('\n'));
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
258
282
|
block('next_step', [
|
|
259
|
-
|
|
283
|
+
b.messages.every((m) => m.kind === 'answer')
|
|
284
|
+
? 'The user answered your question. Act on the choice now, and record the decision (what and why) on the relevant page.'
|
|
285
|
+
: 'Answer the user. Comments and selections carry a data-src: read that code before answering. Answer every numbered comment.',
|
|
260
286
|
'If the answer changes the page (or the code it describes), update the page; the browser reloads by itself.',
|
|
261
287
|
`Then run \`${CMD} reply "<answer>" --listen\`${detectAgent() === 'claude-code' ? ' with run_in_background' : ''}. Keep the reply short and concrete; use - lists and **bold** sparingly.`,
|
|
262
288
|
].join('\n'));
|
|
289
|
+
} else if (b.status === 'no_tab') {
|
|
290
|
+
block('next_step', `No truemap tab is open, so nobody can answer on the page. Open it with \`${CMD} <page>\` (the url it prints works too), then listen again; or continue in the terminal.`);
|
|
263
291
|
} else if (b.status === 'browser_closed') {
|
|
264
292
|
block('next_step', 'The user closed the truemap tab. Stop listening and continue in the terminal. Do not reopen the browser unless the user asks or something important needs their eyes.');
|
|
265
293
|
} else if (b.status === 'ended') {
|
|
@@ -283,12 +311,181 @@ async function cmdReply(root, args, opts) {
|
|
|
283
311
|
block('next_step', `truemap is not running. Give the answer in the terminal, or run \`${CMD}\` to reopen the page.`);
|
|
284
312
|
return;
|
|
285
313
|
}
|
|
286
|
-
const r = await call(state, 'POST', '/api/agent/reply', { text, keepWorking: !!opts.working, willListen: !!opts.listen, agent: detectAgent() });
|
|
314
|
+
const r = await call(state, 'POST', '/api/agent/reply', { text, keepWorking: !!opts.working, willListen: !!opts.listen, agent: detectAgent(), focus: splitList(opts.focus), ...(opts.ask ? { ask: opts.ask } : {}) });
|
|
287
315
|
if (r.status !== 200) throw new Error(`reply was rejected: ${r.body?.error || r.status}`);
|
|
288
|
-
out(
|
|
316
|
+
out(`${opts.ask ? 'asked' : 'reply'}: ${r.body?.browsers ? `shown in ${r.body.browsers} tab(s)` : 'saved (no tab open right now; the user sees it next time)'}`);
|
|
317
|
+
if (opts.listen && !r.body?.browsers) {
|
|
318
|
+
out('status: no_tab');
|
|
319
|
+
block('next_step', opts.ask
|
|
320
|
+
? `Nobody has the page open, so the question waits there. Ask the same question in the terminal, or open the page (\`${CMD} <page>\`) and run \`${CMD} listen\`: the answer arrives through listen.`
|
|
321
|
+
: `Nobody has the page open; your reply waits there. Continue in the terminal, or open the page (\`${CMD} <page>\`) and run \`${CMD} listen\`.`);
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
289
324
|
if (opts.listen) await doListen(root, opts);
|
|
290
325
|
}
|
|
291
326
|
|
|
327
|
+
const splitList = (v) => (v ? String(v).split(',').map((s) => s.trim()).filter(Boolean) : []);
|
|
328
|
+
|
|
329
|
+
async function cmdShow(root, args, opts) {
|
|
330
|
+
const state = await liveState(root);
|
|
331
|
+
if (!state) { out('status: no_server'); block('next_step', `truemap is not running. Run \`${CMD} <page>\` first.`); return; }
|
|
332
|
+
const page = args[0] ? resolvePage(root, args[0]) : '';
|
|
333
|
+
const r = await call(state, 'POST', '/api/agent/show', { page, focus: splitList(opts.focus), note: opts.note || '', clear: !!opts.clear, agent: detectAgent() });
|
|
334
|
+
out(`status: ${opts.clear ? 'cleared' : 'shown'}${r.body?.browsers ? '' : ' # no tab is open; nobody saw it'}`);
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
async function cmdAsk(root, args, opts) {
|
|
338
|
+
const question = args.join(' ').trim();
|
|
339
|
+
const options = (opts.option || []).map((o) => { const [label, ...why] = String(o).split('|'); return { label: label.trim(), why: why.join('|').trim() }; }).filter((o) => o.label);
|
|
340
|
+
if (!question || options.length < 2) throw new Error('ask needs a question and at least two --option "Label | why"');
|
|
341
|
+
opts.ask = { question, options };
|
|
342
|
+
opts.listen = true;
|
|
343
|
+
await cmdReply(root, [question], opts);
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
async function cmdChanges(root, args, opts) {
|
|
347
|
+
const state = (await liveState(root)) || await ensureServer(root);
|
|
348
|
+
const base = opts.base || 'auto';
|
|
349
|
+
const r = (await call(state, 'POST', '/api/agent/changes', { base, open: !opts.noOpen, agent: detectAgent() })).body || {};
|
|
350
|
+
if (r.error) { out('status: error'); out(`error: ${q(r.error)}`); return; }
|
|
351
|
+
out(`base: ${q(r.base.label)}`);
|
|
352
|
+
out(`files_changed: ${r.files} # +${r.add} -${r.del}`);
|
|
353
|
+
if (r.boxes.length) {
|
|
354
|
+
out('boxes: # boxes whose files changed (attribution is by file)');
|
|
355
|
+
for (const b of r.boxes) out(` - ${q(b.src)} +${b.add} -${b.del} files: ${b.files.map((f) => q(f.path)).join(', ')}`);
|
|
356
|
+
}
|
|
357
|
+
if (r.unmapped.length) {
|
|
358
|
+
out('not_on_the_map:');
|
|
359
|
+
for (const g of r.unmapped) out(` - ${q(g.folder)} ${g.files.map((f) => q(f.path) + (f.near ? ` (next to ${f.near.map(q).join(', ')}: if it belongs to that box, add it to its data-also)` : '')).join(', ')}`);
|
|
360
|
+
}
|
|
361
|
+
if (r.plan) {
|
|
362
|
+
const missing = r.plan.planned.filter((p) => !p.changed);
|
|
363
|
+
out(`plan: ${q(r.plan.title)} # ${r.plan.planned.length - missing.length} of ${r.plan.planned.length} planned boxes have changes (that is not proof they are done)`);
|
|
364
|
+
for (const p of r.plan.planned.filter((x) => x.changed)) out(` - planned, has changes: ${q(p.name || p.box)} files: ${p.files.map(q).join(', ')} # planned: ${q(p.what || '')}`);
|
|
365
|
+
for (const p of missing) out(` - planned, no changes: ${q(p.name || p.box)}${p.src ? '' : ' # no data-src on the page yet'} # planned: ${q(p.what || '')}`);
|
|
366
|
+
for (const u of r.plan.unplanned) out(` - changed but not in the plan: ${q(u)}`);
|
|
367
|
+
for (const st of r.plan.steps || []) {
|
|
368
|
+
const quiet = [...st.files.filter((x) => !x.changed).map((x) => x.path), ...st.boxes.filter((x) => !x.changed).map((x) => x.name)];
|
|
369
|
+
out(` - step ${st.n}${st.report ? ` (you reported: ${st.report.status})` : ''}: ${q(st.text)}${quiet.length ? ` # names ${quiet.map(q).join(', ')} with no changes` : ''}`);
|
|
370
|
+
if (st.conflict) out(` conflict: ${q(st.conflict)} # the user sees this at the top of the Changes view`);
|
|
371
|
+
if (st.rewritten) out(` report_history: ${q(st.rewritten)}`);
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
out(`browser: ${r.browsers ? 'shown to the user as a card in the conversation; changed boxes carry their lines on the map' : `no tab is open; run \`${CMD}\` to open the map`}`);
|
|
375
|
+
const steps = [];
|
|
376
|
+
if (r.plan && r.plan.status !== 'done') steps.push(`When the plan is built, run \`${CMD} plan --done\`. If some steps are not built, say so in your reply (or add --step "3=not_built:why" so it shows beside the facts).`);
|
|
377
|
+
if (r.plan?.steps?.some((x) => x.conflict)) steps.push('Some steps you reported done name files with no changes: fix the work or correct your report (the user sees both, and the report history).');
|
|
378
|
+
if (r.files) steps.push('Tell the user in 1-3 lines what you changed and where, by box. They see it as a card in the conversation and on the map; a box opens its diff.');
|
|
379
|
+
if (r.boxes.length) steps.push(`Keep the map true: for each box you changed, fix its data-name, tag and detail if they no longer fit, then confirm it with \`${CMD} check --ok index.html --box <id>\` (otherwise the user sees "Map may be out of date").`);
|
|
380
|
+
if (r.unmapped.length) steps.push('Files that are not on the map: if they matter (a new module, a new route), add a box for them to the page.');
|
|
381
|
+
steps.push(agentLoopHint());
|
|
382
|
+
block('next_step', steps.join('\n'));
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
async function cmdPlan(root, args, opts) {
|
|
386
|
+
if (opts.approve || opts.done) {
|
|
387
|
+
const state = await liveState(root);
|
|
388
|
+
if (!state) { out('status: no_server'); return; }
|
|
389
|
+
const r = await call(state, 'POST', '/api/agent/plan', { status: opts.approve ? 'approved' : 'done', steps: opts.step || [], agent: detectAgent() });
|
|
390
|
+
if (r.status === 400 && r.body?.missing) {
|
|
391
|
+
out('status: report_needed');
|
|
392
|
+
out('steps: # say what happened to every step; the user sees your report beside the facts');
|
|
393
|
+
r.body.steps.forEach((st, i) => out(` ${i + 1}. ${q(st)}${r.body.missing.includes(i + 1) ? ' # not reported' : ''}`));
|
|
394
|
+
block('next_step', `Run \`${CMD} plan --done\` again with one --step per step: --step "1=done" --step "2=partly:the UI field is missing" --step "3=not_built:hub.ts does not start the watchdog yet". Statuses: done, partly, not_built, dropped (a note after a colon is required for all but done). Check each step against your diff first; be exact.`);
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
397
|
+
if (r.status !== 200) throw new Error(r.body?.error || `plan update failed (${r.status})`);
|
|
398
|
+
out(`status: ${r.body.status}`);
|
|
399
|
+
out(`plan: ${q(r.body.plan)}`);
|
|
400
|
+
for (const st of r.body.check?.steps || []) {
|
|
401
|
+
if (st.conflict) out(`conflict: step ${st.n}: ${q(st.conflict)} # shown to the user in the conversation and the Changes view`);
|
|
402
|
+
if (st.rewritten) out(`report_history: step ${st.n}: ${q(st.rewritten)}`);
|
|
403
|
+
}
|
|
404
|
+
const missing = (r.body.check?.planned || []).filter((p) => !p.changed);
|
|
405
|
+
if (missing.length) {
|
|
406
|
+
out('warning: some planned boxes have no changes in their files # tell the user which parts of the plan are not built');
|
|
407
|
+
for (const p of missing) out(` - ${q(p.name || p.box)} # ${q(p.what || '')}`);
|
|
408
|
+
}
|
|
409
|
+
block('next_step', opts.approve
|
|
410
|
+
? `The plan is approved; changes are measured from now. Build it. When you are done, put the new boxes on the page for real (with data-src), run \`${CMD} plan --done\`, then \`${CMD} changes\` so the user can review what you did.`
|
|
411
|
+
: `The plan is closed. Run \`${CMD} changes\` to show the user what changed.`);
|
|
412
|
+
return;
|
|
413
|
+
}
|
|
414
|
+
if (!opts.file) throw new Error(`plan needs --file plan.json (or --file - to read stdin); see \`${CMD} guide\` for the format`);
|
|
415
|
+
let raw;
|
|
416
|
+
try { raw = JSON.parse(opts.file === '-' ? readFileSync(0, 'utf8') : readFileSync(resolve(opts.file), 'utf8')); } catch (e) { throw new Error(`could not read the plan: ${e.message}`); }
|
|
417
|
+
ensureFolder(root);
|
|
418
|
+
const state = await ensureServer(root);
|
|
419
|
+
const r = await call(state, 'POST', '/api/agent/plan', { plan: raw, agent: detectAgent() });
|
|
420
|
+
if (r.status !== 200) throw new Error(`plan rejected: ${r.body?.error || r.status}`);
|
|
421
|
+
const url = `http://127.0.0.1:${state.port}/?t=${state.token}#page=${encodeURIComponent(r.body.page)}`;
|
|
422
|
+
if (!r.body.browsers && !process.env.TRUEMAP_NO_OPEN && !opts.noOpen) openBrowser(url);
|
|
423
|
+
let drawable = true;
|
|
424
|
+
try { drawable = /class=["'][^"']*\btm-diagram\b/.test(readFileSync(join(folderPath(root), r.body.page), 'utf8')); } catch { /* the server already checked the page */ }
|
|
425
|
+
if (!drawable) {
|
|
426
|
+
out('status: plan_not_drawn');
|
|
427
|
+
out(`page: ${q(r.body.page)} # an older .tm-map page: the plan shows in the conversation as text, not on the map`);
|
|
428
|
+
block('next_step', [
|
|
429
|
+
`Convert ${r.body.page} to the current map first: rewrite its <div class="tm-map"> as <figure class="tm-diagram">: each .tm-layer becomes a <section class="tm-group" data-label="…">, each box keeps its id, data-src and data-to and gets data-name / data-tag (see \`${CMD} guide\`, THE MAP). Run \`${CMD} check ${r.body.page}\`.`,
|
|
430
|
+
`Then run \`${CMD} plan --file <plan.json>\` again. Until then the user can only approve from the text.`,
|
|
431
|
+
].join('\n'));
|
|
432
|
+
return;
|
|
433
|
+
}
|
|
434
|
+
out('status: plan_shown');
|
|
435
|
+
for (const w of r.body.warnings || []) out(`warning: ${w}`);
|
|
436
|
+
if ((r.body.warnings || []).length) out('# fix the plan and run plan --file again: entries that name nothing are not drawn');
|
|
437
|
+
out(`plan: ${q(r.body.slug)} # ${FOLDER}/plans/${r.body.slug}.json, revision ${r.body.revision}`);
|
|
438
|
+
out(`page: ${q(r.body.page)}`);
|
|
439
|
+
out(`url: ${url}`);
|
|
440
|
+
block('next_step', [
|
|
441
|
+
'Tell the user in the terminal, in 1-3 lines, what the plan does and that they can review it on the map (or just say "go" here).',
|
|
442
|
+
`Do not start building yet. Wait for the review: ${agentLoopHint()}`,
|
|
443
|
+
`If the user says "go" in the terminal instead, run \`${CMD} plan --approve\` and start.`,
|
|
444
|
+
].join('\n'));
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
// A draft: a free-form page that explains one thing, numbered so the drafts read as a record.
|
|
448
|
+
function cmdDraft(root, args, opts) {
|
|
449
|
+
const hasMap = existsSync(join(root, FOLDER, 'index.html'));
|
|
450
|
+
const name = args.join(' ').trim();
|
|
451
|
+
if (!name) throw new Error('draft needs a name: truemap draft "how a message is routed"');
|
|
452
|
+
ensureFolder(root);
|
|
453
|
+
const dir = join(folderPath(root), 'drafts');
|
|
454
|
+
mkdirSync(dir, { recursive: true });
|
|
455
|
+
const nums = readdirSync(dir).map((x) => parseInt(x, 10)).filter(Number.isFinite);
|
|
456
|
+
const n = (nums.length ? Math.max(...nums) : 0) + 1;
|
|
457
|
+
const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 48) || 'draft';
|
|
458
|
+
const file = `drafts/${String(n).padStart(3, '0')}-${slug}.html`;
|
|
459
|
+
const title = opts.title || name.replace(/^./, (c) => c.toUpperCase());
|
|
460
|
+
const esc = (t) => String(t).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
|
461
|
+
writeFileSync(join(folderPath(root), file), `<!doctype html>
|
|
462
|
+
<html lang="en">
|
|
463
|
+
<head>
|
|
464
|
+
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
|
465
|
+
<title>${esc(title)}</title>
|
|
466
|
+
<link rel="stylesheet" href="../assets/truemap.css">
|
|
467
|
+
</head>
|
|
468
|
+
<body><main class="tm-page">
|
|
469
|
+
<header class="tm-header">
|
|
470
|
+
<nav class="tm-crumb">${hasMap ? '<a href="../index.html">Map</a> / ' : ''}Draft ${n}</nav>
|
|
471
|
+
<h1 class="tm-title">${esc(title)}</h1>
|
|
472
|
+
<p class="tm-lede">One or two sentences: what this draft explains or proposes.</p>
|
|
473
|
+
</header>
|
|
474
|
+
<section class="tm-section">
|
|
475
|
+
<h2>…</h2>
|
|
476
|
+
<p>…</p>
|
|
477
|
+
</section>
|
|
478
|
+
</main></body>
|
|
479
|
+
</html>
|
|
480
|
+
`);
|
|
481
|
+
out('status: draft_created');
|
|
482
|
+
out(`draft: ${q(file)} # .truemap/${file}`);
|
|
483
|
+
block('next_step', [
|
|
484
|
+
`Write the draft: replace the placeholder sections in .truemap/${file}. Free form: any mix of short text, a <figure class="tm-diagram"> (data-plan="new" draws a proposed box dashed), steps, a comparison table, a small interactive bit, or an <iframe> of the running dev server.${hasMap ? ' Link boxes on the map as <a href="../index.html#runs">Runs</a>.' : ' No map is needed for this.'}`,
|
|
485
|
+
`Then show it: \`${CMD} ${file}\` (the user's tab switches to it and it is added to their drafts), and answer in one or two lines with \`${CMD} reply "…" --listen\` pointing to it.`,
|
|
486
|
+
].join('\n'));
|
|
487
|
+
}
|
|
488
|
+
|
|
292
489
|
async function cmdProgress(root, args) {
|
|
293
490
|
const state = await liveState(root);
|
|
294
491
|
if (!state) return out('status: no_server');
|
|
@@ -299,8 +496,8 @@ async function cmdProgress(root, args) {
|
|
|
299
496
|
async function cmdCheck(root, args, opts) {
|
|
300
497
|
if (opts.ok) {
|
|
301
498
|
const page = resolvePage(root, opts.ok);
|
|
302
|
-
if (!markOk(root, page)) throw new Error(`page not found: ${FOLDER}/${page}`);
|
|
303
|
-
out(`status: marked ${q(page)} as
|
|
499
|
+
if (!markOk(root, page, opts.box)) throw new Error(`page not found: ${FOLDER}/${page}`);
|
|
500
|
+
out(opts.box?.length ? `status: marked ${opts.box.map(q).join(', ')} on ${q(page)} as matching the code # other boxes keep their marks` : `status: marked every box on ${q(page)} as matching the code`);
|
|
304
501
|
const state = await liveState(root);
|
|
305
502
|
if (state) await call(state, 'POST', '/api/check', {}).catch(() => {});
|
|
306
503
|
return;
|
|
@@ -320,7 +517,7 @@ async function cmdCheck(root, args, opts) {
|
|
|
320
517
|
if (changed) steps.push(`Changed anchors: review the code. Update the page if needed, otherwise run \`${CMD} check --ok <page>\`.`);
|
|
321
518
|
if (wires) steps.push('Some map wires point at ids that are not on the page, so they are not drawn. Fix the data-to values (ids separated by spaces).');
|
|
322
519
|
const layout = results.reduce((n, r) => n + (r.layout || []).length, 0);
|
|
323
|
-
if (layout) steps.push('
|
|
520
|
+
if (layout) steps.push('Map notes: fix each one; they are what keeps a map readable at a glance (see `' + CMD + ' guide`, THE MAP).');
|
|
324
521
|
if (!broken && !changed && !wires && !layout) steps.push('All pages match the code.');
|
|
325
522
|
block('next_step', steps.join('\n'));
|
|
326
523
|
}
|
|
@@ -352,7 +549,7 @@ function cmdOutline(root) {
|
|
|
352
549
|
out('tree: # folder, files, approx lines, biggest files');
|
|
353
550
|
for (const d of o.dirs) out(` - ${q(d.path)} files=${d.files} lines=${d.lines} ${d.top.join(', ')}`);
|
|
354
551
|
if (o.entries.length) out(`likely_entry_points: ${o.entries.map(q).join(', ')}`);
|
|
355
|
-
block('next_step', `Read the manifests and entry points (not every file), then write ${FOLDER}/index.html
|
|
552
|
+
block('next_step', `Read the manifests and entry points (not every file), then write ${FOLDER}/index.html with one <figure class="tm-diagram">: 3-5 groups by responsibility in the order a request travels, 7-12 small boxes (data-name, data-tag, data-src), data-to connections with a verb, 1-3 flows. Run \`${CMD} guide\` for the format if you have not.`);
|
|
356
553
|
}
|
|
357
554
|
|
|
358
555
|
function cmdGuide() {
|
|
@@ -364,7 +561,6 @@ function help() {
|
|
|
364
561
|
|
|
365
562
|
usage:
|
|
366
563
|
${CMD} [page] open a page from ${FOLDER}/ (default: index.html) in the user's browser
|
|
367
|
-
${CMD} <page> --annotate open it with comment mode on (when you want the user's review)
|
|
368
564
|
${CMD} listen [--timeout s] wait for the user's next message from the page chat
|
|
369
565
|
${CMD} reply "<text>" [--listen] [--file path|-]
|
|
370
566
|
show your answer in the page chat (--listen: then wait for the next message)
|
|
@@ -373,6 +569,16 @@ usage:
|
|
|
373
569
|
${CMD} outline a compact map of the repo (folders, sizes, entry points) for a fast first blueprint
|
|
374
570
|
${CMD} guide how to write pages: folder rules, data-src, page kit, decisions
|
|
375
571
|
${CMD} export <page> [--out f] write the page as one self-contained HTML file to share
|
|
572
|
+
${CMD} show [page] --focus id,id [--note "…"]
|
|
573
|
+
point at the map while you explain: light up boxes (ids or data-src), add a note
|
|
574
|
+
${CMD} reply "…" --focus id,id answer and light up the boxes the answer is about
|
|
575
|
+
${CMD} ask "<question>" --option "A | why" --option "B | why"
|
|
576
|
+
ask the user to choose, only when you are blocked on a real trade-off
|
|
577
|
+
${CMD} draft "<name>" a new numbered draft page that explains one thing (then open it with truemap <file>)
|
|
578
|
+
${CMD} plan --file plan.json before a change that touches 3+ boxes or adds one: show the plan on the map for review
|
|
579
|
+
${CMD} plan --approve|--done the user said "go" in the terminal / the plan is built
|
|
580
|
+
${CMD} changes [--base turn|plan|head|main]
|
|
581
|
+
what changed, by box; opens the Changes view for the user
|
|
376
582
|
${CMD} progress "<text>" show a short status line in the chat while you work
|
|
377
583
|
${CMD} stop stop the background server
|
|
378
584
|
|
|
@@ -395,6 +601,16 @@ function parseArgs(argv) {
|
|
|
395
601
|
else if (a === '--file') opts.file = argv[++i];
|
|
396
602
|
else if (a === '--ok') opts.ok = argv[++i];
|
|
397
603
|
else if (a === '--out') opts.out = argv[++i];
|
|
604
|
+
else if (a === '--focus') opts.focus = argv[++i];
|
|
605
|
+
else if (a === '--note') opts.note = argv[++i];
|
|
606
|
+
else if (a === '--clear') opts.clear = true;
|
|
607
|
+
else if (a === '--base') opts.base = argv[++i];
|
|
608
|
+
else if (a === '--approve') opts.approve = true;
|
|
609
|
+
else if (a === '--done') opts.done = true;
|
|
610
|
+
else if (a === '--step') (opts.step ||= []).push(argv[++i]);
|
|
611
|
+
else if (a === '--title') opts.title = argv[++i];
|
|
612
|
+
else if (a === '--box') (opts.box ||= []).push(argv[++i]);
|
|
613
|
+
else if (a === '--option') (opts.option ||= []).push(argv[++i]);
|
|
398
614
|
else if (a === '--help' || a === '-h') opts.help = true;
|
|
399
615
|
else if (a === '--version' || a === '-v') opts.version = true;
|
|
400
616
|
else args.push(a);
|
|
@@ -405,7 +621,7 @@ function parseArgs(argv) {
|
|
|
405
621
|
export async function main(argv) {
|
|
406
622
|
const { args, opts } = parseArgs(argv);
|
|
407
623
|
if (opts.version) return out(VERSION);
|
|
408
|
-
const commands = { listen: cmdListen, reply: cmdReply, check: cmdCheck, stop: cmdStop, guide: cmdGuide, progress: cmdProgress, outline: cmdOutline, export: cmdExport, help };
|
|
624
|
+
const commands = { listen: cmdListen, reply: cmdReply, check: cmdCheck, stop: cmdStop, guide: cmdGuide, progress: cmdProgress, outline: cmdOutline, export: cmdExport, show: cmdShow, ask: cmdAsk, changes: cmdChanges, plan: cmdPlan, draft: cmdDraft, help };
|
|
409
625
|
const name = args[0] && commands[args[0]] ? args.shift() : null;
|
|
410
626
|
if (opts.help || name === 'help') return help();
|
|
411
627
|
const root = findRoot();
|
package/src/common.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Shared helpers: repo root, state files, version, safe executable lookup.
|
|
2
2
|
import { execFileSync } from 'node:child_process';
|
|
3
3
|
import { createHash } from 'node:crypto';
|
|
4
|
-
import { appendFileSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';
|
|
5
5
|
import { homedir } from 'node:os';
|
|
6
6
|
import { delimiter, dirname, isAbsolute, join, resolve } from 'node:path';
|
|
7
7
|
import { fileURLToPath } from 'node:url';
|
|
@@ -73,9 +73,23 @@ export function rootKey(root) {
|
|
|
73
73
|
return createHash('sha1').update(CASE_INSENSITIVE_FS ? r.toLowerCase() : r).digest('hex').slice(0, 16);
|
|
74
74
|
}
|
|
75
75
|
|
|
76
|
+
export function serversDir() { return stateSubdir('servers'); }
|
|
77
|
+
/** The code a server runs: the version plus the newest edit to truemap's own files (catches local builds). */
|
|
78
|
+
export function buildId() {
|
|
79
|
+
let newest = 0;
|
|
80
|
+
for (const dir of ['src', 'src/ui', 'kit']) {
|
|
81
|
+
let names = []; try { names = readdirSync(join(PKG_DIR, dir)); } catch { /* not there */ }
|
|
82
|
+
for (const n of names) { try { const st = statSync(join(PKG_DIR, dir, n)); if (st.isFile()) newest = Math.max(newest, st.mtimeMs); } catch { /* gone */ } }
|
|
83
|
+
}
|
|
84
|
+
return `${VERSION}+${Math.round(newest)}`;
|
|
85
|
+
}
|
|
86
|
+
/** A project keeps the same ports and token across restarts, so an open tab and a bookmark keep working. */
|
|
87
|
+
export function addrPath(root) { return join(stateSubdir('addr'), `${rootKey(root)}.json`); }
|
|
76
88
|
export function serverStatePath(root) { return join(stateSubdir('servers'), `${rootKey(root)}.json`); }
|
|
77
89
|
export function serverLockPath(root) { return join(stateSubdir('servers'), `${rootKey(root)}.lock`); }
|
|
78
90
|
export function historyPath(root) { return join(stateSubdir('history'), `${rootKey(root)}.jsonl`); }
|
|
91
|
+
export function verifiedPath(root) { return join(stateSubdir('verified'), `${rootKey(root)}.json`); }
|
|
92
|
+
export function snapshotsPath(root) { return join(stateSubdir('snapshots'), `${rootKey(root)}.json`); }
|
|
79
93
|
|
|
80
94
|
export function readJson(file) {
|
|
81
95
|
try { return JSON.parse(readFileSync(file, 'utf8')); } catch { return null; }
|
package/src/export.js
CHANGED
|
@@ -53,8 +53,8 @@ export function exportPage(root, page) {
|
|
|
53
53
|
return f ? `${a}data:${type};base64,${readFileSync(f).toString('base64')}${b}` : m;
|
|
54
54
|
});
|
|
55
55
|
|
|
56
|
-
const wires =
|
|
57
|
-
const boot = `<script>\n${wires}\n(() => { const d = () => window.truemapWires.draw(); if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', d); else d(); addEventListener('resize', d); document.fonts && document.fonts.ready.then(d); })();\n</script>`;
|
|
56
|
+
const wires = [join(UI_DIR, 'wires.js'), join(UI_DIR, 'diagram.js')].map((f) => readFileSync(f, 'utf8')).join('\n;\n');
|
|
57
|
+
const boot = `<script>\n${wires}\n(() => { const d = () => { window.truemapDiagram.draw(); window.truemapWires.draw(); window.truemapWires.mark && window.truemapWires.mark(); }; window.truemapWires.interact(); window.truemapDiagram.interact(); if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', d); else d(); addEventListener('resize', d); document.fonts && document.fonts.ready.then(d); })();\n</script>`;
|
|
58
58
|
const stamp = `<!-- Exported by truemap ${VERSION} from ${FOLDER}/${page} on ${new Date().toISOString().slice(0, 10)}. Links to other pages need the .truemap folder. -->`;
|
|
59
59
|
const note = `<p style="max-width:960px;margin:0 auto;padding:0 48px 40px;font:13px/1.5 var(--tm-font);color:var(--tm-pencil)">Exported from <code>${FOLDER}/${page}</code> with truemap. Links to other pages work inside the project's ${FOLDER} folder.</p>`;
|
|
60
60
|
html = /<\/body>/i.test(html) ? html.replace(/<\/body>(?![\s\S]*<\/body>)/i, () => `${note}\n${boot}\n</body>`) : html + note + boot;
|