truemap-cli 0.3.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +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 +179 -62
- package/package.json +1 -1
- package/skills/truemap/SKILL.md +9 -5
- package/src/changes.js +155 -0
- package/src/check.js +98 -7
- package/src/cli.js +178 -13
- package/src/common.js +3 -0
- package/src/export.js +2 -2
- package/src/guide.md +128 -115
- package/src/plan.js +185 -0
- package/src/server.js +188 -11
- package/src/snippet.js +63 -0
- package/src/ui/diagram.js +598 -0
- package/src/ui/sdk.js +271 -39
- package/src/ui/wires.js +114 -22
- package/src/ui/workspace.css +337 -157
- package/src/ui/workspace.html +27 -14
- package/src/ui/workspace.js +503 -57
package/src/server.js
CHANGED
|
@@ -1,13 +1,16 @@
|
|
|
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 { createServer } from 'node:http';
|
|
4
|
+
import { createServer, request as httpRequest } from 'node:http';
|
|
5
5
|
import { randomBytes } from 'node:crypto';
|
|
6
|
-
import { existsSync, lstatSync, readFileSync, realpathSync, rmSync, statSync, watch } from 'node:fs';
|
|
7
|
-
import { extname, join, resolve, sep } from 'node:path';
|
|
8
|
-
import { FOLDER, PKG_DIR, VERSION, appendPrivate, historyPath, serverStatePath, writePrivate } from './common.js';
|
|
6
|
+
import { existsSync, lstatSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, watch } from 'node:fs';
|
|
7
|
+
import { basename, extname, join, resolve, sep } from 'node:path';
|
|
8
|
+
import { FOLDER, PKG_DIR, VERSION, appendPrivate, historyPath, serverStatePath, serversDir, snapshotsPath, writePrivate } from './common.js';
|
|
9
|
+
import { changes, fileDiff, snapshotTree } from './changes.js';
|
|
10
|
+
import { cleanPlan, currentPlan, parseReport, planCheck, planMessage, planWarnings, readPlan, savePlan, srcOfBox, stepCheck } from './plan.js';
|
|
9
11
|
import { checkAll, listPages } from './check.js';
|
|
10
12
|
import { exportPage, kitCss } from './export.js';
|
|
13
|
+
import { snippet } from './snippet.js';
|
|
11
14
|
|
|
12
15
|
const root = resolve(process.argv[2] || process.cwd());
|
|
13
16
|
const folder = join(root, FOLDER);
|
|
@@ -37,6 +40,10 @@ let agentSince = 0; // when the current state began
|
|
|
37
40
|
let endRequested = false; // the user pressed End conversation while the agent wasn't listening
|
|
38
41
|
let annotateWish; // set by `truemap <page> --annotate` before a tab is open
|
|
39
42
|
let lastAgentActivity = 0;
|
|
43
|
+
let lastSeenAt = Date.now(); // when a person last had this project open
|
|
44
|
+
let lastReplyAt = 0; // when the agent last wrote in the chat
|
|
45
|
+
let everConnected = false; // a tab has been open since this server started
|
|
46
|
+
const asking = () => { const a = [...history].reverse().find((h) => h.role === 'agent'); return !!(a?.ask && !history.some((h) => h.kind === 'answer' && h.at > a.at)); };
|
|
40
47
|
let currentPage = null;
|
|
41
48
|
let closeTimer = null;
|
|
42
49
|
let idleTimer = null;
|
|
@@ -44,6 +51,49 @@ let seq = 0;
|
|
|
44
51
|
let lastCheck = { gitRepo: false, results: [] };
|
|
45
52
|
const history = loadHistory();
|
|
46
53
|
|
|
54
|
+
// ---------- change review: where "what changed" is measured from ----------
|
|
55
|
+
const snapshots = (() => { try { return JSON.parse(readFileSync(snapshotsPath(root), 'utf8')); } catch { return {}; } })();
|
|
56
|
+
function saveSnapshots() { try { writePrivate(snapshotsPath(root), JSON.stringify(snapshots)); } catch { /* ignore */ } }
|
|
57
|
+
async function takeSnapshot(kind, extra = {}) {
|
|
58
|
+
const tree = await snapshotTree(root).catch(() => null);
|
|
59
|
+
if (!tree) return null;
|
|
60
|
+
snapshots[kind] = { tree, at: new Date().toISOString(), ...extra };
|
|
61
|
+
saveSnapshots(); changeCache.clear();
|
|
62
|
+
broadcast({ type: 'changes-base', kind });
|
|
63
|
+
return snapshots[kind];
|
|
64
|
+
}
|
|
65
|
+
const changeCache = new Map(); // base -> { at, promise }
|
|
66
|
+
|
|
67
|
+
// ---------- plans ----------
|
|
68
|
+
let plan = (() => { try { return currentPlan(root); } catch { return null; } })();
|
|
69
|
+
function setPlan(p) {
|
|
70
|
+
plan = p;
|
|
71
|
+
if (p) { try { savePlan(root, p); } catch { /* ignore */ } }
|
|
72
|
+
broadcast({ type: 'plan', plan: p && p.status !== 'done' ? p : null });
|
|
73
|
+
}
|
|
74
|
+
async function approvePlan(by) {
|
|
75
|
+
if (!plan || plan.status === 'done') return false;
|
|
76
|
+
setPlan({ ...plan, status: 'approved', approvedAt: new Date().toISOString() });
|
|
77
|
+
await takeSnapshot('plan', { slug: plan.slug });
|
|
78
|
+
if (by === 'user') {
|
|
79
|
+
const msg = { id: `m${Date.now().toString(36)}${(seq++).toString(36)}`, at: new Date().toISOString(), kind: 'approval', from: 'user', page: plan.page, text: `Approved the plan: ${plan.title}`, context: [], plan: plan.slug };
|
|
80
|
+
queue.push(msg); remember({ role: 'user', ...msg }); deliverQueue();
|
|
81
|
+
}
|
|
82
|
+
return true;
|
|
83
|
+
}
|
|
84
|
+
function changesFor(base, fresh = false) {
|
|
85
|
+
const hit = changeCache.get(base);
|
|
86
|
+
if (!fresh && hit && Date.now() - hit.at < 3000) return hit.promise;
|
|
87
|
+
const promise = changes(root, base, snapshots).then((r) => {
|
|
88
|
+
// measured from the plan's approval: say how the work compares with the plan
|
|
89
|
+
const p = plan && snapshots.plan?.slug === plan.slug ? plan : snapshots.plan?.slug ? readPlan(root, snapshots.plan.slug) : null;
|
|
90
|
+
if (!r.error && r.base?.kind === 'plan' && p) { r.plan = planCheck(root, p, r); r.plan.steps = stepCheck(root, p, r); r.plan.status = p.status; }
|
|
91
|
+
return r;
|
|
92
|
+
}).catch((e) => ({ error: String(e?.message || e) }));
|
|
93
|
+
changeCache.set(base, { at: Date.now(), promise });
|
|
94
|
+
return promise;
|
|
95
|
+
}
|
|
96
|
+
|
|
47
97
|
function loadHistory() {
|
|
48
98
|
try {
|
|
49
99
|
return readFileSync(historyPath(root), 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l)).slice(-200);
|
|
@@ -103,6 +153,7 @@ function deliverQueue() {
|
|
|
103
153
|
if (listener && (listener.res.destroyed || listener.res.writableEnded)) { clearTimeout(listener.timer); listener = null; setAgentState('idle'); }
|
|
104
154
|
if (!listener || queue.length === 0) return;
|
|
105
155
|
const messages = queue.splice(0, queue.length);
|
|
156
|
+
takeSnapshot('turn');
|
|
106
157
|
setAgentState('working');
|
|
107
158
|
lastAgentActivity = Date.now();
|
|
108
159
|
broadcast({ type: 'delivered', ids: messages.map((m) => m.id) });
|
|
@@ -114,7 +165,7 @@ function scheduleCloseCheck() {
|
|
|
114
165
|
if (!listener || clients.size > 0) return;
|
|
115
166
|
closeTimer = setTimeout(() => {
|
|
116
167
|
if (listener && clients.size === 0 && queue.length === 0) {
|
|
117
|
-
finishListen({ status: 'browser_closed' });
|
|
168
|
+
finishListen({ status: everConnected ? 'browser_closed' : 'no_tab' });
|
|
118
169
|
setAgentState('idle');
|
|
119
170
|
}
|
|
120
171
|
}, CLOSE_GRACE_MS);
|
|
@@ -144,6 +195,7 @@ function startWatching() {
|
|
|
144
195
|
watchTimer = setTimeout(() => {
|
|
145
196
|
const files = [...changedPages];
|
|
146
197
|
changedPages.clear();
|
|
198
|
+
changeCache.clear();
|
|
147
199
|
broadcast({ type: 'pages', pages: safePages() });
|
|
148
200
|
broadcast({ type: 'changed', files });
|
|
149
201
|
scheduleChecks();
|
|
@@ -159,6 +211,35 @@ function safePages() {
|
|
|
159
211
|
try { return listPages(root); } catch { return []; }
|
|
160
212
|
}
|
|
161
213
|
|
|
214
|
+
const cleanFocus = (f) => (Array.isArray(f) ? f : []).map((x) => String(x).trim().slice(0, 300)).filter(Boolean).slice(0, 20);
|
|
215
|
+
|
|
216
|
+
// ---------- every truemap project running on this machine (one server each) ----------
|
|
217
|
+
function peek(state) {
|
|
218
|
+
return new Promise((ok) => {
|
|
219
|
+
const r = httpRequest({ host: '127.0.0.1', port: state.port, path: '/api/agent/status', method: 'GET', headers: { 'X-Truemap-Token': state.token } }, (res) => {
|
|
220
|
+
const chunks = []; res.on('data', (c) => chunks.push(c));
|
|
221
|
+
res.on('end', () => { try { ok(JSON.parse(Buffer.concat(chunks).toString('utf8'))); } catch { ok(null); } });
|
|
222
|
+
});
|
|
223
|
+
r.setTimeout(800, () => r.destroy()); r.on('error', () => ok(null)); r.end();
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
async function projects() {
|
|
227
|
+
let files = [];
|
|
228
|
+
try { files = readdirSync(serversDir()).filter((x) => x.endsWith('.json')); } catch { return []; }
|
|
229
|
+
const list = await Promise.all(files.map(async (name) => {
|
|
230
|
+
let st; try { st = JSON.parse(readFileSync(join(serversDir(), name), 'utf8')); } catch { return null; }
|
|
231
|
+
if (!st?.port || !st.token) return null;
|
|
232
|
+
const self = st.pid === process.pid;
|
|
233
|
+
const s = self ? { root, name: basename(root), agent: agentState, agentName, plan: plan && plan.status !== 'done' ? { title: plan.title, status: plan.status } : null, unread: false, asking: false, clients: clients.size } : await peek(st);
|
|
234
|
+
if (!s?.root) return null;
|
|
235
|
+
return { self, name: s.name || basename(s.root), root: s.root, agent: s.agent, agentName: s.agentName || '', plan: s.plan || null, unread: !!s.unread, asking: !!s.asking, url: `http://127.0.0.1:${st.port}/?t=${encodeURIComponent(st.token)}` };
|
|
236
|
+
}));
|
|
237
|
+
// one entry per project, even when two state files (old path spellings) point at the same server
|
|
238
|
+
const seen = new Set();
|
|
239
|
+
return list.filter(Boolean).sort((a, b) => (b.self - a.self) || a.name.localeCompare(b.name))
|
|
240
|
+
.filter((x) => { const k = String(x.root).toLowerCase().replace(/[\\/]+$/, ''); if (seen.has(k)) return false; seen.add(k); return true; });
|
|
241
|
+
}
|
|
242
|
+
|
|
162
243
|
// ---------- http helpers ----------
|
|
163
244
|
function sendJson(res, status, body) {
|
|
164
245
|
res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' });
|
|
@@ -288,13 +369,13 @@ const server = createServer(async (req, res) => {
|
|
|
288
369
|
res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-store', Connection: 'keep-alive' });
|
|
289
370
|
res.write(`data: ${JSON.stringify({
|
|
290
371
|
type: 'hello', version: VERSION, root, cmd: CMD, agent: agentInfo(), pages: safePages(), check: lastCheck,
|
|
291
|
-
history, current: currentPage, pending: queue.map((m) => m.id), ...(annotateWish !== undefined ? { annotate: annotateWish } : {}),
|
|
372
|
+
history, current: currentPage, pending: queue.map((m) => m.id), plan: plan && plan.status !== 'done' ? plan : null, ...(annotateWish !== undefined ? { annotate: annotateWish } : {}),
|
|
292
373
|
})}\n\n`);
|
|
293
374
|
annotateWish = undefined;
|
|
294
|
-
clients.add(res);
|
|
375
|
+
clients.add(res); everConnected = true;
|
|
295
376
|
clearTimeout(closeTimer);
|
|
296
377
|
const ping = setInterval(() => res.write(': ping\n\n'), 20_000);
|
|
297
|
-
req.on('close', () => { clearInterval(ping); clients.delete(res); scheduleCloseCheck(); touchIdle(); });
|
|
378
|
+
req.on('close', () => { clearInterval(ping); clients.delete(res); lastSeenAt = Date.now(); scheduleCloseCheck(); touchIdle(); });
|
|
298
379
|
return;
|
|
299
380
|
}
|
|
300
381
|
if (p === '/api/send' && req.method === 'POST') {
|
|
@@ -321,6 +402,7 @@ const server = createServer(async (req, res) => {
|
|
|
321
402
|
context,
|
|
322
403
|
...(answer ? { answer } : {}),
|
|
323
404
|
};
|
|
405
|
+
if (b.plan === 'request' && plan && plan.status !== 'done') { msg.kind = 'plan_changes'; msg.plan = plan.slug; setPlan({ ...plan, status: 'revise' }); }
|
|
324
406
|
queue.push(msg);
|
|
325
407
|
endRequested = false; // a new message means the conversation goes on
|
|
326
408
|
remember({ role: 'user', ...msg });
|
|
@@ -342,6 +424,32 @@ const server = createServer(async (req, res) => {
|
|
|
342
424
|
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'Content-Disposition': `attachment; filename="${name.replace(/[^\w.-]/g, '_')}-truemap.html"` });
|
|
343
425
|
return res.end(html);
|
|
344
426
|
}
|
|
427
|
+
if (p === '/api/snippet' && req.method === 'GET') {
|
|
428
|
+
try { return sendJson(res, 200, snippet(root, url.searchParams.get('src') || '')); } catch (e) { return sendJson(res, 200, { error: String(e.message || e) }); }
|
|
429
|
+
}
|
|
430
|
+
if (p === '/api/changes' && req.method === 'GET') {
|
|
431
|
+
return sendJson(res, 200, await changesFor(url.searchParams.get('base') || 'auto'));
|
|
432
|
+
}
|
|
433
|
+
if (p === '/api/diff' && req.method === 'GET') {
|
|
434
|
+
return sendJson(res, 200, await fileDiff(root, url.searchParams.get('base') || 'auto', snapshots, String(url.searchParams.get('path') || '')));
|
|
435
|
+
}
|
|
436
|
+
if (p === '/api/plan' && req.method === 'POST') {
|
|
437
|
+
const b = await readBody(req);
|
|
438
|
+
if (b.action === 'approve') return sendJson(res, 200, { ok: await approvePlan('user') });
|
|
439
|
+
return sendJson(res, 400, { error: 'unknown action' });
|
|
440
|
+
}
|
|
441
|
+
if (p === '/api/drift' && req.method === 'GET') {
|
|
442
|
+
const path = String(url.searchParams.get('path') || '').replace(/\\/g, '/');
|
|
443
|
+
const since = String(url.searchParams.get('since') || '');
|
|
444
|
+
if (!path || path.includes('..')) return sendJson(res, 400, { error: 'bad path' });
|
|
445
|
+
const { execFileSync } = await import('node:child_process');
|
|
446
|
+
const g = (args) => { try { return execFileSync('git', args, { cwd: root, encoding: 'utf8', maxBuffer: 16 * 1024 * 1024, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] }); } catch { return null; } };
|
|
447
|
+
const commit = (since && g(['rev-list', '-1', `--before=${since}`, 'HEAD'])?.trim()) || 'HEAD';
|
|
448
|
+
const text = g(['diff', '--no-color', '-U3', commit, '--', path]);
|
|
449
|
+
if (text === null) return sendJson(res, 200, { error: 'git diff failed' });
|
|
450
|
+
return sendJson(res, 200, { path, from: commit.slice(0, 8), text: text.length > 200_000 ? `${text.slice(0, 200_000)}\n… (cut)` : text });
|
|
451
|
+
}
|
|
452
|
+
if (p === '/api/projects' && req.method === 'GET') return sendJson(res, 200, { projects: await projects() });
|
|
345
453
|
if (p === '/api/end' && req.method === 'POST') {
|
|
346
454
|
// The user is done talking on the page: free the agent to go back to the terminal.
|
|
347
455
|
if (listener) finishListen({ status: 'ended' }); else if (agentState === 'working' || agentState === 'listening') endRequested = true;
|
|
@@ -351,7 +459,11 @@ const server = createServer(async (req, res) => {
|
|
|
351
459
|
|
|
352
460
|
// ----- agent (CLI) side -----
|
|
353
461
|
if (p === '/api/agent/status' && req.method === 'GET') {
|
|
354
|
-
return sendJson(res, 200, {
|
|
462
|
+
return sendJson(res, 200, {
|
|
463
|
+
version: VERSION, pid: process.pid, root, name: basename(root), clients: clients.size, agent: agentState, agentName, queued: queue.length, current: currentPage,
|
|
464
|
+
plan: plan && plan.status !== 'done' ? { title: plan.title, status: plan.status } : null,
|
|
465
|
+
unread: !clients.size && lastReplyAt > lastSeenAt, asking: asking(),
|
|
466
|
+
});
|
|
355
467
|
}
|
|
356
468
|
if (p === '/api/agent/listen' && req.method === 'POST') {
|
|
357
469
|
const b = await readBody(req);
|
|
@@ -377,7 +489,12 @@ const server = createServer(async (req, res) => {
|
|
|
377
489
|
if (!text.trim()) return sendJson(res, 400, { error: 'empty reply' });
|
|
378
490
|
lastAgentActivity = Date.now();
|
|
379
491
|
noteAgent(b.agent);
|
|
380
|
-
|
|
492
|
+
const focus = cleanFocus(b.focus);
|
|
493
|
+
const ask = b.ask && typeof b.ask === 'object' && Array.isArray(b.ask.options) && b.ask.options.length >= 2
|
|
494
|
+
? { question: String(b.ask.question ?? '').slice(0, 500), options: b.ask.options.slice(0, 6).map((o) => ({ label: String(o.label ?? '').slice(0, 200), why: String(o.why ?? '').slice(0, 400) })) }
|
|
495
|
+
: null;
|
|
496
|
+
remember({ role: 'agent', id: `a${Date.now().toString(36)}${(seq++).toString(36)}`, at: new Date().toISOString(), agent: agentName, text, ...(focus.length ? { focus } : {}), ...(ask ? { ask } : {}) });
|
|
497
|
+
lastReplyAt = Date.now(); if (clients.size) lastSeenAt = lastReplyAt;
|
|
381
498
|
if (!listener) setAgentState(b.keepWorking || b.willListen ? 'working' : 'idle');
|
|
382
499
|
return sendJson(res, 200, { ok: true, browsers: clients.size });
|
|
383
500
|
}
|
|
@@ -390,6 +507,65 @@ const server = createServer(async (req, res) => {
|
|
|
390
507
|
scheduleChecks();
|
|
391
508
|
return sendJson(res, 200, { ok: true, browsers: clients.size });
|
|
392
509
|
}
|
|
510
|
+
if (p === '/api/agent/show' && req.method === 'POST') {
|
|
511
|
+
// The agent points at the map: light up boxes (by id or data-src), optionally with a note.
|
|
512
|
+
const b = await readBody(req);
|
|
513
|
+
lastAgentActivity = Date.now();
|
|
514
|
+
noteAgent(b.agent);
|
|
515
|
+
broadcast({ type: 'show', page: typeof b.page === 'string' ? b.page : '', focus: cleanFocus(b.focus), note: String(b.note ?? '').slice(0, 2000), clear: !!b.clear, agent: agentName });
|
|
516
|
+
return sendJson(res, 200, { ok: true, browsers: clients.size });
|
|
517
|
+
}
|
|
518
|
+
if (p === '/api/agent/changes' && req.method === 'POST') {
|
|
519
|
+
// `truemap changes`: the summary for the agent, and the Changes view for the user.
|
|
520
|
+
const b = await readBody(req);
|
|
521
|
+
noteAgent(b.agent);
|
|
522
|
+
const base = ['turn', 'plan', 'head', 'main'].includes(b.base) ? b.base : 'auto';
|
|
523
|
+
const r = await changesFor(base, true);
|
|
524
|
+
if (b.open !== false) broadcast({ type: 'view', view: 'changes', base });
|
|
525
|
+
return sendJson(res, 200, { ...r, browsers: clients.size });
|
|
526
|
+
}
|
|
527
|
+
if (p === '/api/agent/plan' && req.method === 'POST') {
|
|
528
|
+
const b = await readBody(req);
|
|
529
|
+
noteAgent(b.agent);
|
|
530
|
+
lastAgentActivity = Date.now();
|
|
531
|
+
if (b.status) {
|
|
532
|
+
if (!plan) return sendJson(res, 404, { error: 'no plan in play' });
|
|
533
|
+
if (b.status === 'approved') await approvePlan('agent');
|
|
534
|
+
let check = null;
|
|
535
|
+
if (b.status === 'done') {
|
|
536
|
+
// closing a plan takes the agent's account of every step
|
|
537
|
+
let rep2;
|
|
538
|
+
try { rep2 = parseReport(plan, Array.isArray(b.steps) ? b.steps : []); } catch (e) { return sendJson(res, 400, { error: String(e.message || e) }); }
|
|
539
|
+
// the account of steps is optional; when given, every report is kept
|
|
540
|
+
if (rep2.report.some(Boolean)) plan = { ...plan, report: rep2.report, reports: [...(plan.reports || []), { at: new Date().toISOString(), report: rep2.report }] };
|
|
541
|
+
if (snapshots.plan?.slug === plan.slug) { await takeSnapshot('planEnd', { slug: plan.slug }); const r = await changesFor('plan', true); check = r.plan || null; }
|
|
542
|
+
setPlan({ ...plan, status: 'done', doneAt: new Date().toISOString() });
|
|
543
|
+
const sts = check?.steps || [];
|
|
544
|
+
const rpt = plan.report || [];
|
|
545
|
+
const tally = ['done', 'partly', 'not_built', 'dropped'].map((k) => [k, rpt.filter((x) => x?.status === k).length]).filter(([, n]) => n).map(([k, n]) => `${n} ${k.replace('_', ' ')}`).join(', ');
|
|
546
|
+
const conflicts = sts.filter((x) => x.conflict || x.rewritten);
|
|
547
|
+
remember({ role: 'agent', id: `a${Date.now().toString(36)}${(seq++).toString(36)}`, at: new Date().toISOString(), agent: agentName, plan: plan.slug,
|
|
548
|
+
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),
|
|
549
|
+
...(conflicts.length ? ['', '**Check before you trust this report:**', ...conflicts.map((x) => `- Step ${x.n}: ${[x.conflict, x.rewritten].filter(Boolean).join(' ')}`)] : []),
|
|
550
|
+
'', 'Open the Changes tab to see each step beside its diff.'].join('\n') });
|
|
551
|
+
}
|
|
552
|
+
return sendJson(res, 200, { ok: true, plan: plan.slug, status: plan.status, check });
|
|
553
|
+
}
|
|
554
|
+
let p2;
|
|
555
|
+
try { p2 = cleanPlan(b.plan); } catch (e) { return sendJson(res, 400, { error: String(e.message || e) }); }
|
|
556
|
+
const prev = readPlan(root, p2.slug);
|
|
557
|
+
p2.revision = prev && prev.status !== 'done' ? (prev.revision || 1) + 1 : 1;
|
|
558
|
+
p2.status = 'review'; p2.at = new Date().toISOString();
|
|
559
|
+
if (prev && prev.status !== 'done') {
|
|
560
|
+
const was = new Map(prev.touch.map((t) => [t.box, t.what]));
|
|
561
|
+
const wasAdd = new Map(prev.add.map((a) => [a.id, JSON.stringify(a)]));
|
|
562
|
+
p2.revised = [...p2.touch.filter((t) => was.get(t.box) !== t.what).map((t) => t.box), ...p2.add.filter((a) => wasAdd.get(a.id) !== JSON.stringify(a)).map((a) => a.id)];
|
|
563
|
+
}
|
|
564
|
+
setPlan(p2);
|
|
565
|
+
remember({ role: 'agent', id: `a${Date.now().toString(36)}${(seq++).toString(36)}`, at: p2.at, agent: agentName, text: planMessage(p2, p2.revision > 1 ? prev : null, (box) => srcOfBox(root, p2.page, box, 'data-name') || box), plan: p2.slug });
|
|
566
|
+
broadcast({ type: 'navigate', page: p2.page, pages: safePages() });
|
|
567
|
+
return sendJson(res, 200, { ok: true, slug: p2.slug, revision: p2.revision, page: p2.page, browsers: clients.size, warnings: planWarnings(root, p2) });
|
|
568
|
+
}
|
|
393
569
|
if (p === '/api/agent/progress' && req.method === 'POST') {
|
|
394
570
|
const b = await readBody(req);
|
|
395
571
|
broadcast({ type: 'progress', text: String(b.text ?? '').slice(0, 300) });
|
|
@@ -413,7 +589,8 @@ const content = createServer((req, res) => {
|
|
|
413
589
|
const p = new URL(req.url, `http://127.0.0.1:${contentPort}`).pathname;
|
|
414
590
|
try {
|
|
415
591
|
if (p === '/__truemap/sdk.js') {
|
|
416
|
-
const js =
|
|
592
|
+
const js = [join(UI_DIR, 'wires.js'), join(UI_DIR, 'diagram.js')].map((f) => readFileSync(f, 'utf8')).join('\n;\n')
|
|
593
|
+
+ '\n' + readFileSync(join(UI_DIR, 'sdk.js'), 'utf8').replace('__TRUEMAP_PARENT__', `http://127.0.0.1:${port}`);
|
|
417
594
|
res.writeHead(200, { 'Content-Type': 'text/javascript; charset=utf-8', 'Cache-Control': 'no-store' });
|
|
418
595
|
return res.end(js);
|
|
419
596
|
}
|
package/src/snippet.js
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// The real code behind a box: a few lines around `name` in `path`, read from the repo.
|
|
2
|
+
// Only files git tracks (or, without git, files inside the repo that aren't hidden) are served, so a
|
|
3
|
+
// page can never pull out .env or anything ignored.
|
|
4
|
+
import { execFileSync } from 'node:child_process';
|
|
5
|
+
import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs';
|
|
6
|
+
import { join, resolve, sep } from 'node:path';
|
|
7
|
+
import { gitExe } from './common.js';
|
|
8
|
+
import { parseAnchor } from './check.js';
|
|
9
|
+
|
|
10
|
+
const MAX_BYTES = 2 * 1024 * 1024;
|
|
11
|
+
|
|
12
|
+
function git(root, args) {
|
|
13
|
+
try {
|
|
14
|
+
return execFileSync(gitExe(), args, { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true, maxBuffer: 8 * 1024 * 1024 });
|
|
15
|
+
} catch { return null; }
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function snippet(root, src, around = 10) {
|
|
19
|
+
const { path, name } = parseAnchor(String(src || ''));
|
|
20
|
+
if (!path || path.endsWith('/')) return { path, kind: 'folder' };
|
|
21
|
+
const full = resolve(root, '.' + sep + path.replace(/\//g, sep));
|
|
22
|
+
if (!full.startsWith(resolve(root) + sep) || !existsSync(full)) return { path, error: 'not found' };
|
|
23
|
+
try { if (!realpathSync(full).startsWith(realpathSync(root) + sep)) return { path, error: 'outside the repo' }; } catch { return { path, error: 'not found' }; }
|
|
24
|
+
const tracked = git(root, ['ls-files', '--error-unmatch', '--', path]);
|
|
25
|
+
if (tracked === null) {
|
|
26
|
+
if (git(root, ['rev-parse', '--is-inside-work-tree']) !== null) return { path, error: 'not tracked by git' };
|
|
27
|
+
if (path.split('/').some((p) => p.startsWith('.'))) return { path, error: 'hidden file' };
|
|
28
|
+
}
|
|
29
|
+
const st = statSync(full);
|
|
30
|
+
if (st.isDirectory()) return { path, kind: 'folder' };
|
|
31
|
+
if (st.size > MAX_BYTES) return { path, error: 'file too large to show' };
|
|
32
|
+
const text = readFileSync(join(full), 'utf8');
|
|
33
|
+
if (text.includes('\0')) return { path, error: 'binary file' };
|
|
34
|
+
const lines = text.split(/\r?\n/);
|
|
35
|
+
let line = 0;
|
|
36
|
+
if (name) {
|
|
37
|
+
const esc = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
38
|
+
const re = new RegExp(`(?<![\\p{L}\\p{N}_$])${esc}(?![\\p{L}\\p{N}_$])`, 'u');
|
|
39
|
+
// Prefer the line that defines the name over lines that merely use it:
|
|
40
|
+
// 1. a keyword right before it (function x, class X, def x, const x = …), or x: / x = a function,
|
|
41
|
+
// or a method header at the start of a line (async x(…) {) that is not a call (this.x(…))
|
|
42
|
+
// 2. any line with a defining keyword 3. the first mention
|
|
43
|
+
const strong = [
|
|
44
|
+
new RegExp(`\\b(function\\*?|class|def|fn|func|interface|type|struct|enum|trait|impl|module|const|let|var|val)\\s+${esc}(?![\\p{L}\\p{N}_$])`, 'u'),
|
|
45
|
+
new RegExp(`(?<![.\\p{L}\\p{N}_$])${esc}\\s*[:=]\\s*(async\\s*)?(function|\\(|[\\p{L}_$][\\p{L}\\p{N}_$]*\\s*=>)`, 'u'),
|
|
46
|
+
// a method header: name(…) { or name(…): Type { on one line, or name( with the parameters continuing below
|
|
47
|
+
new RegExp(`^\\s*((public|private|protected|static|async|override|readonly|get|set)\\s+)*${esc}\\s*(<[^>]*>)?\\s*\\((.*\\)\\s*(:[^=]*?)?\\s*\\{\\s*$|[^)]*$)`, 'u'),
|
|
48
|
+
];
|
|
49
|
+
const weak = /\b(function|class|def|fn|func|const|let|var|type|interface|export|struct|enum|router\.\w+|app\.\w+)\b/;
|
|
50
|
+
const hits = lines.map((l, i) => (re.test(l) ? i : -1)).filter((i) => i >= 0);
|
|
51
|
+
if (!hits.length) return { path, name, missing: true, total: lines.length };
|
|
52
|
+
line = hits.find((i) => strong.some((s) => s.test(lines[i]))) ?? hits.find((i) => weak.test(lines[i])) ?? hits[0] ?? 0;
|
|
53
|
+
}
|
|
54
|
+
const start = Math.max(0, line - 3);
|
|
55
|
+
const end = Math.min(lines.length, start + around * 2 + 1);
|
|
56
|
+
const dirty = (git(root, ['status', '--porcelain', '--', path]) || '').trim();
|
|
57
|
+
const changed = dirty ? 'uncommitted changes' : git(root, ['log', '-1', '--format=%cr', '--', path]);
|
|
58
|
+
return {
|
|
59
|
+
path, name, line: line + 1, start: start + 1, total: lines.length,
|
|
60
|
+
lines: lines.slice(start, end).map((l) => (l.length > 220 ? `${l.slice(0, 220)}…` : l)),
|
|
61
|
+
lastChange: changed ? changed.trim() : '',
|
|
62
|
+
};
|
|
63
|
+
}
|