@point-seven-studio/jq-deck 0.0.0-stage → 0.3.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.
@@ -0,0 +1,1944 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli.ts
4
+ import { spawn } from "child_process";
5
+ import { createServer } from "http";
6
+ import path6 from "path";
7
+
8
+ // ../agents/dist/index.mjs
9
+ import { execFile as execFile2 } from "child_process";
10
+ import { existsSync } from "fs";
11
+ import { open, readdir, stat } from "fs/promises";
12
+ import os2 from "os";
13
+ import path from "path";
14
+ import { promisify as promisify2 } from "util";
15
+ import { execFile } from "child_process";
16
+ import { promisify } from "util";
17
+ import os from "os";
18
+ var META_RECORD_TYPES = /* @__PURE__ */ new Set([
19
+ "last-prompt",
20
+ "pr-link",
21
+ "queue-operation",
22
+ "mode",
23
+ "ai-title",
24
+ "attachment",
25
+ "result",
26
+ "summary"
27
+ ]);
28
+ var LIVE_WITHIN_S = 15 * 60;
29
+ var IDLE_WITHIN_S = 2 * 60 * 60;
30
+ var QUESTION_MAX_CHARS = 400;
31
+ var REDACTIONS = [
32
+ // Connection strings carrying user:password@host (the real finding on this machine).
33
+ { name: "db-url", re: /\b(postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|amqp):\/\/[^\s:@/]+:[^\s:@/]+@/gi },
34
+ // Real 3-segment JWTs only — header.payload.signature.
35
+ { name: "jwt", re: /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{20,}\b/g },
36
+ { name: "stripe-key", re: /\b(sk|rk)_(live|test)_[A-Za-z0-9]{20,}\b/g },
37
+ { name: "openai-key", re: /\bsk-(?:proj-)?[A-Za-z0-9_-]{32,}\b/g },
38
+ { name: "gh-token", re: /\bgh[pousr]_[A-Za-z0-9]{30,}\b/g },
39
+ { name: "aws-akid", re: /\bAKIA[0-9A-Z]{16}\b/g },
40
+ { name: "supabase-key", re: /\bsb_(?:publishable|secret)_[A-Za-z0-9_-]{20,}\b/g },
41
+ {
42
+ name: "slack-token",
43
+ re: /\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g
44
+ },
45
+ // KEY=… / TOKEN=… / SECRET=… / PASSWORD=… assignments with a realistic value.
46
+ { name: "env-assign", re: /\b([A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL)S?)\s*[=:]\s*["']?[^\s"']{12,}/g }
47
+ ];
48
+ function redactSecrets(text) {
49
+ let out = text;
50
+ let redacted = false;
51
+ for (const { name, re } of REDACTIONS) {
52
+ out = out.replace(re, (match) => {
53
+ redacted = true;
54
+ if (name === "env-assign") {
55
+ const varName = match.split(/[=:]/)[0].trim();
56
+ return `${varName}=[redacted]`;
57
+ }
58
+ return `[redacted:${name}]`;
59
+ });
60
+ }
61
+ return { text: out, redacted };
62
+ }
63
+ function messageText(rec) {
64
+ const content = rec.message?.content;
65
+ if (typeof content === "string") return content;
66
+ if (Array.isArray(content)) {
67
+ return content.filter(
68
+ (b) => !!b && typeof b === "object" && b.type === "text" && typeof b.text === "string"
69
+ ).map((b) => b.text).join("\n");
70
+ }
71
+ return "";
72
+ }
73
+ function endsWithQuestion(text) {
74
+ const tail = text.trimEnd().split("\n").filter((l) => l.trim()).slice(-3).join(" ");
75
+ if (/\?\s*$/.test(text.trimEnd())) return true;
76
+ return /\?/.test(tail);
77
+ }
78
+ function lastSubstantive(records) {
79
+ for (let i = records.length - 1; i >= 0; i--) {
80
+ const r = records[i];
81
+ if (!r?.type) continue;
82
+ if (META_RECORD_TYPES.has(r.type)) continue;
83
+ if (r.type === "assistant" || r.type === "user") return r;
84
+ }
85
+ return null;
86
+ }
87
+ function lastAssistant(records) {
88
+ for (let i = records.length - 1; i >= 0; i--) {
89
+ if (records[i]?.type === "assistant") return records[i];
90
+ }
91
+ return null;
92
+ }
93
+ function lastActivityAt(records) {
94
+ for (let i = records.length - 1; i >= 0; i--) {
95
+ const r = records[i];
96
+ if (!r?.timestamp || r.type && META_RECORD_TYPES.has(r.type)) continue;
97
+ return r.timestamp;
98
+ }
99
+ return null;
100
+ }
101
+ function deriveState(alive, lastActivityIso, now) {
102
+ if (!alive) return "dead";
103
+ if (!lastActivityIso) return "stale";
104
+ const ageS = Math.max(0, (now - Date.parse(lastActivityIso)) / 1e3);
105
+ if (ageS <= LIVE_WITHIN_S) return "live";
106
+ if (ageS <= IDLE_WITHIN_S) return "idle";
107
+ return "stale";
108
+ }
109
+ function deriveWaiting(rec, alive) {
110
+ if (!alive || !rec || rec.type !== "assistant") return false;
111
+ return rec.message?.stop_reason === "end_turn";
112
+ }
113
+ function deriveAttention(state, waiting) {
114
+ if (!waiting) return "none";
115
+ if (state === "live" || state === "idle") return "needs-you";
116
+ if (state === "stale") return "abandoned";
117
+ return "none";
118
+ }
119
+ function isTreeAllowed(workingTree, allowlist) {
120
+ if (!workingTree) return false;
121
+ return allowlist.some((t) => t && (workingTree === t || workingTree.startsWith(t.replace(/\/+$/, "") + "/")));
122
+ }
123
+ function buildStatusRow(opts) {
124
+ const { machine, records, sessionIdFallback, alive, pid, allowlist, now, workingTreeOverride } = opts;
125
+ const withCwd = [...records].reverse().find((r) => r?.cwd);
126
+ const workingTree = workingTreeOverride || withCwd?.cwd || "";
127
+ if (!workingTree) return null;
128
+ const sessionId = [...records].reverse().find((r) => r?.sessionId)?.sessionId || sessionIdFallback;
129
+ if (!sessionId) return null;
130
+ const branch = [...records].reverse().find((r) => r?.gitBranch)?.gitBranch || null;
131
+ const substantive = lastSubstantive(records);
132
+ const assistant = lastAssistant(records);
133
+ const activity = lastActivityAt(records);
134
+ const state = deriveState(alive, activity, now);
135
+ const waiting = deriveWaiting(substantive, alive);
136
+ const rawText = assistant ? messageText(assistant) : "";
137
+ const allowed = isTreeAllowed(workingTree, allowlist);
138
+ let blocked_question = null;
139
+ let question_redacted = false;
140
+ if (allowed && waiting && rawText.trim()) {
141
+ const { text, redacted } = redactSecrets(rawText.trim());
142
+ question_redacted = redacted;
143
+ blocked_question = text.length > QUESTION_MAX_CHARS ? text.slice(0, QUESTION_MAX_CHARS).trimEnd() + "\u2026" : text;
144
+ }
145
+ return {
146
+ machine,
147
+ product: workingTree.split("/").filter(Boolean).pop() || workingTree,
148
+ working_tree: workingTree,
149
+ branch,
150
+ session_id: sessionId,
151
+ pid,
152
+ state,
153
+ last_activity_at: activity,
154
+ waiting,
155
+ stop_reason: substantive?.type === "assistant" ? substantive.message?.stop_reason ?? null : null,
156
+ ends_with_question: rawText ? endsWithQuestion(rawText) : false,
157
+ blocked_question,
158
+ question_redacted,
159
+ question_allowed: allowed
160
+ };
161
+ }
162
+ function parsePs(stdout) {
163
+ const out = /* @__PURE__ */ new Map();
164
+ for (const line of stdout.split("\n")) {
165
+ const m = line.trim().match(/^(\d+)\s+([\d.]+)\s+(\d+)$/);
166
+ if (!m) continue;
167
+ out.set(Number(m[1]), { cpuPct: Number(m[2]), rssMb: Number(m[3]) / 1024 });
168
+ }
169
+ return out;
170
+ }
171
+ function parseNettop(stdout) {
172
+ const out = /* @__PURE__ */ new Map();
173
+ for (const line of stdout.split("\n")) {
174
+ const f = line.trim().split(/\s+/);
175
+ if (f.length < 4) continue;
176
+ const name = f[1];
177
+ if (!name || !name.includes(".")) continue;
178
+ const pid = Number(name.slice(name.lastIndexOf(".") + 1));
179
+ const bytesIn = Number(f[2]);
180
+ const bytesOut = Number(f[3]);
181
+ if (!Number.isInteger(pid) || pid <= 0) continue;
182
+ if (!Number.isFinite(bytesIn) || !Number.isFinite(bytesOut)) continue;
183
+ out.set(pid, { bytesIn, bytesOut });
184
+ }
185
+ return out;
186
+ }
187
+ function rateBps(prev, cur, seconds) {
188
+ if (prev == null || !Number.isFinite(prev) || seconds <= 0) return null;
189
+ if (cur < prev) return null;
190
+ return Math.round((cur - prev) / seconds);
191
+ }
192
+ function parseVmStat(stdout, memTotalBytes) {
193
+ const pageSize = Number(stdout.match(/page size of (\d+) bytes/)?.[1] || 0);
194
+ if (!pageSize || !memTotalBytes) return 0;
195
+ const pages = (label) => Number(stdout.match(new RegExp(`${label}:\\s+(\\d+)`))?.[1] || 0);
196
+ const used = (pages("Pages wired down") + pages("Pages active") + pages("Pages occupied by compressor")) * pageSize;
197
+ return Math.min(100, Math.round(used / memTotalBytes * 1e3) / 10);
198
+ }
199
+ function parseLoadAvg(stdout) {
200
+ return Number(stdout.replace(/[{}]/g, "").trim().split(/\s+/)[0] || 0);
201
+ }
202
+ function parseSwapUsedMb(stdout) {
203
+ const m = stdout.match(/used\s*=\s*([\d.]+)([MG])/);
204
+ if (!m) return 0;
205
+ const v = Number(m[1]);
206
+ return Math.round(m[2] === "G" ? v * 1024 : v);
207
+ }
208
+ function parseIostat(stdout) {
209
+ const rows = stdout.split("\n").map((l) => l.trim()).filter((l) => /^[\d.\s]+$/.test(l) && l.length > 0);
210
+ const last = rows[rows.length - 1];
211
+ if (!last) return null;
212
+ const f = last.split(/\s+/).map(Number);
213
+ let mbs = 0;
214
+ for (let i = 2; i < f.length; i += 3) if (Number.isFinite(f[i])) mbs += f[i];
215
+ if (!Number.isFinite(mbs)) return null;
216
+ return { readMbs: Math.round(mbs * 100) / 100, writeMbs: Math.round(mbs * 100) / 100 };
217
+ }
218
+ var THRESHOLDS = {
219
+ /** load per core above which the machine is genuinely contended */
220
+ loadPerCore: 1.5,
221
+ /** % of RAM in wired+active+compressed */
222
+ memUsedPct: 90,
223
+ /**
224
+ * Swap in use, MB. Paired with memUsedPct because on its own it is a WEAK
225
+ * signal, and this machine proves it: measured 23.9 GB of swap used on 16 GB
226
+ * of RAM while memory sat at 67% and the machine was responsive. macOS
227
+ * swapusage is close to cumulative — it reflects what has been paged out at
228
+ * some point, not what is being paged now — so a high figure alone says
229
+ * little about current pressure.
230
+ *
231
+ * The RIGHT current-pressure signal is the swapin/swapout RATE, which needs
232
+ * two vm_stat samples the way byte counters need two nettop samples. Until
233
+ * that exists, this stays conservative and deliberately under-reports: a
234
+ * false 'memory-bound' on a healthy machine would teach people to ignore the
235
+ * chip, which is the failure this whole feature is trying to avoid.
236
+ */
237
+ swapUsedMb: 1024,
238
+ /*
239
+ * NO DISK THRESHOLD — deliberately removed after it produced a wrong verdict
240
+ * against real data.
241
+ *
242
+ * First live sample on prod (2026-08-20) read disk 118 MB/s alongside
243
+ * 376ms ±378 to the API. It returned 'disk'. That is backwards: 376ms of
244
+ * latency with more jitter than latency is the thing costing that session
245
+ * time, while 118 MB/s on an NVMe drive that does multiple GB/s is a disk
246
+ * that is busy, not one that is saturated.
247
+ *
248
+ * The deeper problem is that throughput is the wrong measure entirely.
249
+ * Saturation is utilisation or queue wait — %util and await on Linux — and
250
+ * macOS iostat reports neither. There is no honest disk verdict to be had
251
+ * from the numbers available, so disk_read_mbs / disk_write_mbs are still
252
+ * sampled and still displayed for context, and they no longer vote.
253
+ *
254
+ * This is the rule that keeps the board trustworthy: a signal that cannot
255
+ * justify its verdict is reported, not ruled on.
256
+ */
257
+ /** TLS connect jitter, ms — variance hurts an agentic loop more than latency */
258
+ jitterMs: 60,
259
+ /** TLS connect time, ms */
260
+ rttMs: 400
261
+ };
262
+ function deriveBottleneck(host) {
263
+ if (!host.cpuCount) return { kind: "unknown", reason: null };
264
+ if (host.swapUsedMb > THRESHOLDS.swapUsedMb && host.memUsedPct > THRESHOLDS.memUsedPct) {
265
+ return {
266
+ kind: "memory",
267
+ reason: `${host.memUsedPct}% RAM in use, ${host.swapUsedMb}MB swapped`
268
+ };
269
+ }
270
+ const perCore = host.load1 / host.cpuCount;
271
+ if (perCore > THRESHOLDS.loadPerCore) {
272
+ return {
273
+ kind: "cpu",
274
+ reason: `load ${host.load1.toFixed(2)} across ${host.cpuCount} cores (${perCore.toFixed(1)}x)`
275
+ };
276
+ }
277
+ if (host.jitterMs != null && host.jitterMs > THRESHOLDS.jitterMs) {
278
+ return { kind: "network", reason: `${host.rttMs}ms \xB1${host.jitterMs} to the API` };
279
+ }
280
+ if (host.rttMs != null && host.rttMs > THRESHOLDS.rttMs) {
281
+ return { kind: "network", reason: `${host.rttMs}ms to the API` };
282
+ }
283
+ return { kind: "none", reason: null };
284
+ }
285
+ var execFileAsync = promisify(execFile);
286
+ var PROBE_URL = "https://api.anthropic.com/";
287
+ async function run(cmd, args2, timeoutMs = 8e3) {
288
+ try {
289
+ const { stdout } = await execFileAsync(cmd, args2, { timeout: timeoutMs, maxBuffer: 8 * 1024 * 1024 });
290
+ return stdout;
291
+ } catch {
292
+ return "";
293
+ }
294
+ }
295
+ async function probeLatency() {
296
+ const samples = [];
297
+ for (let i = 0; i < 3; i++) {
298
+ const out = await run(
299
+ "curl",
300
+ ["-sS", "-o", "/dev/null", "-w", "%{time_connect}", "--max-time", "3", PROBE_URL],
301
+ 5e3
302
+ );
303
+ const t = Number(out);
304
+ if (Number.isFinite(t) && t > 0) samples.push(t * 1e3);
305
+ }
306
+ if (samples.length === 0) return { rttMs: null, jitterMs: null };
307
+ const mean = samples.reduce((a, b) => a + b, 0) / samples.length;
308
+ const variance = samples.length > 1 ? samples.reduce((a, b) => a + (b - mean) ** 2, 0) / (samples.length - 1) : 0;
309
+ return { rttMs: Math.round(mean), jitterMs: Math.round(Math.sqrt(variance)) };
310
+ }
311
+ async function sampleHost(probe = false) {
312
+ const [vmstat, swap, load, iostat, latency] = await Promise.all([
313
+ run("vm_stat", []),
314
+ run("sysctl", ["-n", "vm.swapusage"]),
315
+ run("sysctl", ["-n", "vm.loadavg"]),
316
+ // Two samples a second apart: the first row iostat prints is a since-boot
317
+ // average that never moves, so a single-shot call reads as a flat line.
318
+ run("iostat", ["-d", "-w", "1", "-c", "2"], 6e3),
319
+ probe ? probeLatency() : Promise.resolve({ rttMs: null, jitterMs: null })
320
+ ]);
321
+ const disk = parseIostat(iostat);
322
+ return {
323
+ cpuCount: os.cpus()?.length || 0,
324
+ load1: parseLoadAvg(load) || os.loadavg()[0] || 0,
325
+ memUsedPct: parseVmStat(vmstat, os.totalmem()),
326
+ swapUsedMb: parseSwapUsedMb(swap),
327
+ diskReadMbs: disk?.readMbs ?? null,
328
+ diskWriteMbs: disk?.writeMbs ?? null,
329
+ rttMs: latency.rttMs,
330
+ jitterMs: latency.jitterMs
331
+ };
332
+ }
333
+ async function sampleProcs(pids) {
334
+ if (pids.length === 0) return { procs: /* @__PURE__ */ new Map(), net: /* @__PURE__ */ new Map() };
335
+ const [ps, nettop] = await Promise.all([
336
+ run("ps", ["-o", "pid=,pcpu=,rss=", "-p", pids.join(",")]),
337
+ run("nettop", ["-P", "-x", "-l", "1"], 1e4)
338
+ ]);
339
+ const all2 = parseNettop(nettop);
340
+ const net = /* @__PURE__ */ new Map();
341
+ for (const pid of pids) {
342
+ const s = all2.get(pid);
343
+ if (s) net.set(pid, s);
344
+ }
345
+ return { procs: parsePs(ps), net };
346
+ }
347
+ var execFileAsync2 = promisify2(execFile2);
348
+ function defaultProjectsDir() {
349
+ return path.join(process.env.CLAUDE_CONFIG_DIR || path.join(os2.homedir(), ".claude"), "projects");
350
+ }
351
+ var TAIL_RECORDS = 60;
352
+ async function findTranscripts(dir, out = []) {
353
+ let entries;
354
+ try {
355
+ entries = await readdir(dir, { withFileTypes: true });
356
+ } catch {
357
+ return out;
358
+ }
359
+ for (const e of entries) {
360
+ const full = path.join(dir, e.name);
361
+ if (e.isDirectory()) await findTranscripts(full, out);
362
+ else if (e.isFile() && e.name.endsWith(".jsonl")) out.push(full);
363
+ }
364
+ return out;
365
+ }
366
+ var rootCache = /* @__PURE__ */ new Map();
367
+ async function repoRoot(dir) {
368
+ if (!dir) return dir;
369
+ const cached = rootCache.get(dir);
370
+ if (cached) return cached;
371
+ let cur = dir;
372
+ for (let i = 0; i < 12; i++) {
373
+ try {
374
+ await stat(path.join(cur, ".git"));
375
+ break;
376
+ } catch {
377
+ const parent = path.dirname(cur);
378
+ if (parent === cur) {
379
+ cur = dir;
380
+ break;
381
+ }
382
+ cur = parent;
383
+ }
384
+ }
385
+ rootCache.set(dir, cur);
386
+ return cur;
387
+ }
388
+ async function tailRecords(file, n = TAIL_RECORDS) {
389
+ const fh = await open(file, "r");
390
+ try {
391
+ const { size } = await fh.stat();
392
+ const chunk = 128 * 1024;
393
+ let pos = size;
394
+ let buf = Buffer.alloc(0);
395
+ while (pos > 0 && buf.toString("utf8").split("\n").length <= n + 1) {
396
+ const start = Math.max(0, pos - chunk);
397
+ const len = pos - start;
398
+ const b = Buffer.alloc(len);
399
+ await fh.read(b, 0, len, start);
400
+ buf = Buffer.concat([b, buf]);
401
+ pos = start;
402
+ if (buf.length > 8 * 1024 * 1024) break;
403
+ }
404
+ const recs = [];
405
+ for (const line of buf.toString("utf8").split("\n").filter((l) => l.trim()).slice(-n)) {
406
+ try {
407
+ recs.push(JSON.parse(line));
408
+ } catch {
409
+ }
410
+ }
411
+ return recs;
412
+ } finally {
413
+ await fh.close();
414
+ }
415
+ }
416
+ async function liveSessionPids(sockDir) {
417
+ let files = [];
418
+ try {
419
+ files = await readdir(sockDir);
420
+ } catch {
421
+ return [];
422
+ }
423
+ return files.filter((f) => f.endsWith(".sock")).map((f) => Number(f.replace(".sock", ""))).filter((p) => Number.isInteger(p) && p > 0).filter((pid) => {
424
+ try {
425
+ process.kill(pid, 0);
426
+ return true;
427
+ } catch {
428
+ return false;
429
+ }
430
+ });
431
+ }
432
+ async function pidCwds(pids) {
433
+ const byCwd = /* @__PURE__ */ new Map();
434
+ if (pids.length === 0) return byCwd;
435
+ try {
436
+ const lsof = existsSync("/usr/sbin/lsof") ? "/usr/sbin/lsof" : "lsof";
437
+ const { stdout } = await execFileAsync2(lsof, ["-a", "-p", pids.join(","), "-d", "cwd", "-Fn"], { maxBuffer: 4 * 1024 * 1024 });
438
+ let current = null;
439
+ for (const line of stdout.split("\n")) {
440
+ if (line.startsWith("p")) current = Number(line.slice(1));
441
+ else if (line.startsWith("n") && current) {
442
+ const cwd = await repoRoot(line.slice(1));
443
+ if (!byCwd.has(cwd)) byCwd.set(cwd, current);
444
+ }
445
+ }
446
+ } catch {
447
+ }
448
+ return byCwd;
449
+ }
450
+ async function collectRows(opts = {}) {
451
+ const now = opts.now ?? Date.now();
452
+ const machine = opts.machine ?? os2.hostname();
453
+ const files = await findTranscripts(opts.projectsDir ?? defaultProjectsDir());
454
+ const cwdToPid = await pidCwds(await liveSessionPids(opts.sockDir ?? "/tmp/cc-socks"));
455
+ const cutoff = now - (opts.maxAgeDays ?? 3) * 864e5;
456
+ const rows = [];
457
+ for (const file of files) {
458
+ try {
459
+ if ((await stat(file)).mtimeMs < cutoff) continue;
460
+ const records = await tailRecords(file);
461
+ if (records.length === 0) continue;
462
+ const rawCwd = [...records].reverse().find((r) => r?.cwd)?.cwd || "";
463
+ const tree = rawCwd ? await repoRoot(rawCwd) : "";
464
+ const pid = tree ? cwdToPid.get(tree) ?? null : null;
465
+ const row3 = buildStatusRow({
466
+ machine,
467
+ records,
468
+ workingTreeOverride: tree || void 0,
469
+ sessionIdFallback: path.basename(file, ".jsonl"),
470
+ alive: pid !== null,
471
+ pid,
472
+ allowlist: opts.questionTrees ?? [],
473
+ now
474
+ });
475
+ if (row3) rows.push(row3);
476
+ } catch {
477
+ }
478
+ }
479
+ const byKey = /* @__PURE__ */ new Map();
480
+ for (const r of rows) {
481
+ const prev = byKey.get(r.session_id);
482
+ if (!prev || (r.last_activity_at || "") > (prev.last_activity_at || "")) byKey.set(r.session_id, r);
483
+ }
484
+ return [...byKey.values()];
485
+ }
486
+ var prevNet = /* @__PURE__ */ new Map();
487
+ async function snapshot(opts = {}) {
488
+ const sessions = await collectRows(opts);
489
+ let host = null;
490
+ let bottleneck = null;
491
+ if (opts.sample !== false) {
492
+ try {
493
+ const pids = sessions.map((r) => r.pid).filter((p) => typeof p === "number");
494
+ const [h, proc] = await Promise.all([sampleHost(opts.probe === true), sampleProcs(pids)]);
495
+ const at = Date.now();
496
+ for (const row3 of sessions) {
497
+ if (row3.pid == null) continue;
498
+ const p = proc.procs.get(row3.pid);
499
+ if (p) {
500
+ row3.cpu_pct = p.cpuPct;
501
+ row3.rss_mb = Math.round(p.rssMb * 10) / 10;
502
+ }
503
+ const cur = proc.net.get(row3.pid);
504
+ const prev = prevNet.get(row3.pid);
505
+ if (cur && prev) {
506
+ const seconds = (at - prev.at) / 1e3;
507
+ row3.net_rx_bps = rateBps(prev.sample.bytesIn, cur.bytesIn, seconds);
508
+ row3.net_tx_bps = rateBps(prev.sample.bytesOut, cur.bytesOut, seconds);
509
+ }
510
+ }
511
+ prevNet = new Map([...proc.net].map(([pid, sample]) => [pid, { sample, at }]));
512
+ host = h;
513
+ bottleneck = deriveBottleneck(h);
514
+ } catch {
515
+ host = null;
516
+ bottleneck = null;
517
+ }
518
+ }
519
+ return { machine: opts.machine ?? os2.hostname(), generated_at: new Date(opts.now ?? Date.now()).toISOString(), sessions, host, bottleneck };
520
+ }
521
+ var esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
522
+ function ago(iso, now) {
523
+ if (!iso) return "unknown";
524
+ const s = Math.max(0, Math.floor((now - Date.parse(iso)) / 1e3));
525
+ if (s < 60) return `${s}s`;
526
+ if (s < 3600) return `${Math.floor(s / 60)}m`;
527
+ if (s < 86400) return `${Math.floor(s / 3600)}h`;
528
+ return `${Math.floor(s / 86400)}d`;
529
+ }
530
+ function totals(rows) {
531
+ const attention = rows.map((r) => deriveAttention(r.state, r.waiting));
532
+ return {
533
+ sessions: rows.length,
534
+ live: rows.filter((r) => r.state === "live").length,
535
+ // Counted from the derived attention, never the raw waiting flag: a session
536
+ // that asked something days ago and was left is not waiting on you now.
537
+ needs_you: attention.filter((a) => a === "needs-you").length,
538
+ abandoned: attention.filter((a) => a === "abandoned").length,
539
+ trees: new Set(rows.map((r) => r.working_tree)).size
540
+ };
541
+ }
542
+ function groupByTree(rows) {
543
+ const by = /* @__PURE__ */ new Map();
544
+ for (const r of rows) by.set(r.working_tree, [...by.get(r.working_tree) ?? [], r]);
545
+ const needs = (list2) => list2.some((r) => deriveAttention(r.state, r.waiting) === "needs-you");
546
+ const latest = (list2) => list2.map((r) => r.last_activity_at || "").sort().pop() || "";
547
+ return [...by.entries()].map(([tree, list2]) => ({
548
+ tree,
549
+ product: list2[0].product,
550
+ rows: list2.sort((a, b) => (b.last_activity_at || "").localeCompare(a.last_activity_at || ""))
551
+ })).sort((a, b) => Number(needs(b.rows)) - Number(needs(a.rows)) || latest(b.rows).localeCompare(latest(a.rows)));
552
+ }
553
+ function sessionRow(r, now) {
554
+ const attention = deriveAttention(r.state, r.waiting);
555
+ const badge = attention === "needs-you" ? '<span class="b need">waiting on a person</span>' : attention === "abandoned" ? '<span class="b old">asked, then left</span>' : "";
556
+ const res = r.cpu_pct != null || r.rss_mb != null ? `<span class="mut">${r.cpu_pct ?? "?"}% cpu \xB7 ${r.rss_mb ?? "?"} MB</span>` : "";
557
+ const question = r.blocked_question ? `<pre>${esc(r.blocked_question)}${r.question_redacted ? "\n[a secret-shaped string was removed]" : ""}</pre>` : attention !== "none" && !r.question_allowed ? '<p class="mut q">Question text is off for this tree.</p>' : "";
558
+ return `<li><span class="s ${r.state}">${r.state}</span> <span class="mut">${esc(r.branch || "no branch")} \xB7 active ${ago(r.last_activity_at, now)} ago</span> ${badge} ${res}${question}</li>`;
559
+ }
560
+ function renderPage(snap, now = Date.now()) {
561
+ const t = totals(snap.sessions);
562
+ const b = snap.bottleneck;
563
+ const chip = !b ? '<p class="mut">Host not sampled.</p>' : b.kind === "none" ? "" : `<p class="chip">${b.kind === "unknown" ? "Could not tell what this machine is short of." : `Bottleneck: ${esc(b.kind)}${b.reason ? ` (${esc(b.reason)})` : ""}`}</p>`;
564
+ const trees = groupByTree(snap.sessions).map((g) => `<section class="card"><h2>${esc(g.product)} <span class="mut">${esc(g.tree)}</span></h2><ul>${g.rows.map((r) => sessionRow(r, now)).join("")}</ul></section>`).join("");
565
+ return `<!doctype html>
566
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
567
+ <title>JQ Agents</title>
568
+ <style>
569
+ :root{--bg:#f7f6f2;--card:#fff;--fg:#1d1c19;--mut:#6b675e;--line:#dedbd2;--well:#f1efe9;--need:#a1500a;--ok:#1f6b45;--bad:#a3262b}
570
+ @media (prefers-color-scheme:dark){:root{--bg:#161512;--card:#1f1e1a;--fg:#ece9e1;--mut:#a09c91;--line:#35332d;--well:#161512;--need:#e0a25a;--ok:#7ccba0;--bad:#ef8a8e}}
571
+ body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.5 system-ui,sans-serif}
572
+ main{max-width:820px;margin:0 auto;padding:24px 16px 60px}
573
+ h1{font-size:24px;margin:0}h2{font-size:15px;margin:0;padding:10px 12px;word-break:break-all}
574
+ .mut{color:var(--mut);font-size:12px;font-weight:400}.tot{display:grid;grid-template-columns:repeat(4,1fr);gap:8px;margin:16px 0}
575
+ .tot div{background:var(--card);border:1px solid var(--line);border-radius:10px;padding:10px}.tot b{display:block;font-size:22px}
576
+ .card{background:var(--card);border:1px solid var(--line);border-radius:12px;margin:10px 0;overflow:hidden}
577
+ ul{list-style:none;margin:0;padding:0}li{border-top:1px solid var(--line);padding:8px 12px}
578
+ .s{font-size:11px;font-weight:700;text-transform:uppercase;border-radius:4px;padding:1px 6px;border:1px solid var(--line)}.s.live{color:var(--ok)}.s.dead{color:var(--mut)}
579
+ .b{font-size:12px;font-weight:600}.b.need{color:var(--need)}.b.old{color:var(--mut)}
580
+ .chip{border:1px solid var(--line);border-radius:8px;padding:6px 10px;font-size:13px}
581
+ pre{white-space:pre-wrap;word-break:break-word;background:var(--well);margin:8px 0 2px;padding:10px;border-radius:8px;font-size:12px}.q{margin:6px 0 0}
582
+ </style></head><body><main>
583
+ <h1>JQ Agents</h1>
584
+ <p class="mut">${esc(snap.machine)} \xB7 read ${esc(snap.generated_at)}. Refresh to read again. Read-only: answer a session where it is running.</p>
585
+ <div class="tot"><div><b>${t.needs_you}</b><span class="mut">waiting on a person</span></div><div><b>${t.abandoned}</b><span class="mut">asked, then left</span></div><div><b>${t.live}</b><span class="mut">live</span></div><div><b>${t.sessions}</b><span class="mut">sessions in ${t.trees} ${t.trees === 1 ? "tree" : "trees"}</span></div></div>
586
+ ${chip}
587
+ ${trees || '<p class="mut">No session has been active in the window read.</p>'}
588
+ </main></body></html>`;
589
+ }
590
+
591
+ // ../crosstalk/dist/index.mjs
592
+ import { existsSync as existsSync2, readdirSync, readFileSync, statSync } from "fs";
593
+ import path2 from "path";
594
+ var BOARD = "board";
595
+ var DAY_MS = 864e5;
596
+ function ageDays(sentAt, now) {
597
+ if (!sentAt) return null;
598
+ const t = Date.parse(sentAt);
599
+ if (Number.isNaN(t)) return null;
600
+ return Math.max(0, Math.floor((now - t) / DAY_MS));
601
+ }
602
+ function summarize(m, now) {
603
+ return {
604
+ id: m.id,
605
+ filename: m.filename,
606
+ from_session: m.from_session,
607
+ to_session: m.to_session,
608
+ subject: m.subject,
609
+ sent_at: m.sent_at,
610
+ acked: m.acked,
611
+ age_days: ageDays(m.sent_at, now),
612
+ kind: m.kind ?? null
613
+ };
614
+ }
615
+ var plural = (n, one, many) => n === 1 ? one : many;
616
+ function waitingBoard(messages, now) {
617
+ const byInbox = /* @__PURE__ */ new Map();
618
+ for (const m of messages) {
619
+ if (m.acked || m.to_session === BOARD) continue;
620
+ const list2 = byInbox.get(m.to_session) ?? [];
621
+ list2.push(m);
622
+ byInbox.set(m.to_session, list2);
623
+ }
624
+ const time = (m) => m.sent_at ? Date.parse(m.sent_at) || Infinity : Infinity;
625
+ const inboxes = [...byInbox.entries()].map(([product, list2]) => {
626
+ list2.sort((a, b) => time(a) - time(b));
627
+ const oldest = list2.find((m) => ageDays(m.sent_at, now) !== null) ?? null;
628
+ return {
629
+ product,
630
+ unread: list2.length,
631
+ oldest_sent_at: oldest?.sent_at ?? null,
632
+ oldest_age_days: oldest ? ageDays(oldest.sent_at, now) : null,
633
+ items: list2.map((m) => summarize(m, now))
634
+ };
635
+ });
636
+ inboxes.sort(
637
+ (a, b) => (b.oldest_age_days ?? -1) - (a.oldest_age_days ?? -1) || b.unread - a.unread || a.product.localeCompare(b.product)
638
+ );
639
+ const total = inboxes.reduce((n, i) => n + i.unread, 0);
640
+ const counted = messages.length;
641
+ let headline;
642
+ if (total === 0) {
643
+ headline = `Nothing is waiting: ${counted} ${plural(counted, "message", "messages")}, all acknowledged.`;
644
+ } else {
645
+ const top = inboxes[0];
646
+ const age2 = top.oldest_age_days === null ? "" : top.oldest_age_days === 0 ? ` The oldest was sent today, to ${top.product}.` : ` The oldest is ${top.oldest_age_days} ${plural(top.oldest_age_days, "day", "days")} old, in the ${top.product} inbox.`;
647
+ headline = `${total} unread ${plural(total, "message", "messages")} in ${inboxes.length} ${plural(inboxes.length, "inbox", "inboxes")}.${age2}`;
648
+ }
649
+ return { headline, total_unread: total, inboxes };
650
+ }
651
+ function normalizeSubject(subject) {
652
+ let s = (subject ?? "").trim();
653
+ while (/^(re|fwd?)\s*:\s*/i.test(s)) s = s.replace(/^(re|fwd?)\s*:\s*/i, "");
654
+ return s.replace(/\s+/g, " ").toLowerCase();
655
+ }
656
+ function citedStamps(body) {
657
+ if (!body) return [];
658
+ return [...new Set(body.match(/\b\d{8}-\d{6}(?!\d)/g) ?? [])];
659
+ }
660
+ function deriveThreads(messages, now) {
661
+ const parent = /* @__PURE__ */ new Map();
662
+ const find = (x) => {
663
+ let r = x;
664
+ while (parent.get(r) !== r) r = parent.get(r);
665
+ parent.set(x, r);
666
+ return r;
667
+ };
668
+ const union = (a, b) => {
669
+ const ra = find(a);
670
+ const rb = find(b);
671
+ if (ra !== rb) parent.set(ra, rb);
672
+ };
673
+ for (const m of messages) parent.set(m.id, m.id);
674
+ const byStamp = /* @__PURE__ */ new Map();
675
+ for (const m of messages) {
676
+ const stamp = m.filename.slice(0, 15);
677
+ byStamp.set(stamp, [...byStamp.get(stamp) ?? [], m.id]);
678
+ }
679
+ for (const m of messages) {
680
+ for (const stamp of citedStamps(m.body)) {
681
+ const hit = byStamp.get(stamp) ?? [];
682
+ if (hit.length === 1 && hit[0] !== m.id) union(m.id, hit[0]);
683
+ }
684
+ }
685
+ const stem = (f) => f.replace(/\.md$/, "");
686
+ const byStem = /* @__PURE__ */ new Map();
687
+ for (const m of messages) byStem.set(stem(m.filename), [...byStem.get(stem(m.filename)) ?? [], m.id]);
688
+ const byThread = /* @__PURE__ */ new Map();
689
+ for (const m of messages) {
690
+ if (!m.thread_id) continue;
691
+ const bare = /^\d{8}-\d{6}$/.test(m.thread_id);
692
+ const first = bare ? byStamp.get(m.thread_id) ?? [] : byStem.get(m.thread_id) ?? [];
693
+ if (first.length === 1) union(m.id, first[0]);
694
+ if (bare && first.length !== 1) continue;
695
+ const seen = byThread.get(m.thread_id);
696
+ if (seen) union(m.id, seen);
697
+ else byThread.set(m.thread_id, m.id);
698
+ }
699
+ const bySubject = /* @__PURE__ */ new Map();
700
+ for (const m of messages) {
701
+ const subject = normalizeSubject(m.subject);
702
+ if (!subject || subject === m.from_session || subject === m.to_session) continue;
703
+ const pair = [m.from_session, m.to_session].sort().join("|");
704
+ const key = `${pair}|${subject}`;
705
+ const seen = bySubject.get(key);
706
+ if (seen) union(m.id, seen);
707
+ else bySubject.set(key, m.id);
708
+ }
709
+ const groups = /* @__PURE__ */ new Map();
710
+ for (const m of messages) {
711
+ const root = find(m.id);
712
+ groups.set(root, [...groups.get(root) ?? [], m]);
713
+ }
714
+ const time = (m) => m.sent_at ? Date.parse(m.sent_at) || 0 : 0;
715
+ const threads = [...groups.values()].map((list2) => {
716
+ list2.sort((a, b) => time(a) - time(b) || a.filename.localeCompare(b.filename));
717
+ const first = list2[0];
718
+ const last = list2[list2.length - 1];
719
+ return {
720
+ id: first.filename,
721
+ subject: first.subject,
722
+ participants: [...new Set(list2.flatMap((m) => [m.from_session, m.to_session]))].sort(),
723
+ count: list2.length,
724
+ unread: list2.filter((m) => !m.acked).length,
725
+ first_at: first.sent_at,
726
+ last_at: last.sent_at,
727
+ messages: list2.map((m) => summarize(m, now))
728
+ };
729
+ });
730
+ threads.sort((a, b) => (Date.parse(b.last_at ?? "") || 0) - (Date.parse(a.last_at ?? "") || 0) || a.id.localeCompare(b.id));
731
+ return threads;
732
+ }
733
+ function boardPosts(messages, now) {
734
+ const today = new Date(now).toISOString().slice(0, 10);
735
+ const onBoard = messages.filter((m) => m.to_session === BOARD);
736
+ const time = (m) => m.sent_at ? Date.parse(m.sent_at) || 0 : 0;
737
+ const posts = onBoard.filter((m) => m.kind === "post").map((post2) => {
738
+ const thread = post2.thread_id ?? post2.filename.replace(/\.md$/, "");
739
+ const rest = onBoard.filter((m) => m.id !== post2.id && m.thread_id === thread).sort((a, b) => time(a) - time(b) || a.filename.localeCompare(b.filename));
740
+ const closing = rest.find((m) => m.kind === "close" && m.from_session === post2.from_session) ?? null;
741
+ const replies = rest.filter((m) => m.kind !== "close");
742
+ const expired2 = !!post2.expires_on && post2.expires_on < today;
743
+ return {
744
+ id: post2.filename,
745
+ title: post2.subject,
746
+ from: post2.from_session,
747
+ tags: post2.tags ?? [],
748
+ asked_at: post2.sent_at,
749
+ expires_on: post2.expires_on ?? null,
750
+ state: closing ? "closed" : expired2 ? "expired" : "open",
751
+ settled_by: closing ? closing.settled_by ?? null : null,
752
+ closing: closing ? summarize(closing, now) : null,
753
+ post: summarize(post2, now),
754
+ replies: replies.map((r) => ({ ...summarize(r, now), evidence: r.evidence ?? null }))
755
+ };
756
+ });
757
+ const open2 = posts.filter((p) => p.state !== "closed");
758
+ const rank = (p) => p.state === "expired" && p.replies.length === 0 ? 0 : p.state === "expired" ? 1 : 2;
759
+ open2.sort((a, b) => rank(a) - rank(b) || (a.expires_on ?? "9999").localeCompare(b.expires_on ?? "9999") || a.id.localeCompare(b.id));
760
+ const closed = posts.filter((p) => p.state === "closed").sort((a, b) => (Date.parse(b.closing?.sent_at ?? "") || 0) - (Date.parse(a.closing?.sent_at ?? "") || 0));
761
+ const unanswered = open2.filter((p) => p.replies.length === 0).length;
762
+ const expired = open2.filter((p) => p.state === "expired").length;
763
+ let headline;
764
+ if (posts.length === 0) headline = "No one has posted to the board yet.";
765
+ else if (open2.length === 0) headline = `Nothing is open. ${closed.length} ${plural(closed.length, "post has", "posts have")} been closed.`;
766
+ else {
767
+ headline = `${open2.length} open ${plural(open2.length, "post", "posts")}, ${unanswered} with no reply`;
768
+ headline += expired > 0 ? `, ${expired} past ${plural(expired, "its", "their")} date.` : ".";
769
+ }
770
+ return { headline, open: open2, closed };
771
+ }
772
+ var SETTLED_BY = ["source", "owner", "fix", "pushback", "nobody"];
773
+ function parseMessage(filename, raw, recipient, acked) {
774
+ let tags = null;
775
+ let expires = null;
776
+ let evidence = null;
777
+ let settledBy = null;
778
+ let kind = null;
779
+ let thread = null;
780
+ let replyTo = null;
781
+ let from = "";
782
+ let subject = null;
783
+ let sent = null;
784
+ let body = raw;
785
+ const fm = raw.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
786
+ if (fm) {
787
+ body = fm[2].trim();
788
+ for (const line of fm[1].split("\n")) {
789
+ const m = line.match(/^(\w+):\s*(.*)$/);
790
+ if (!m) continue;
791
+ if (m[1] === "from") from = m[2].trim();
792
+ else if (m[1] === "subject") subject = m[2].trim();
793
+ else if (m[1] === "sent") sent = m[2].trim();
794
+ else if (m[1] === "kind") kind = m[2].trim() || null;
795
+ else if (m[1] === "thread") thread = m[2].trim() || null;
796
+ else if (m[1] === "reply_to") replyTo = m[2].trim() || null;
797
+ else if (m[1] === "tags") {
798
+ const list2 = m[2].split(",").map((t) => t.trim().toLowerCase()).filter(Boolean);
799
+ tags = list2.length ? [...new Set(list2)] : null;
800
+ } else if (m[1] === "expires") expires = /^\d{4}-\d{2}-\d{2}$/.test(m[2].trim()) ? m[2].trim() : null;
801
+ else if (m[1] === "evidence") evidence = m[2].trim() || null;
802
+ else if (m[1] === "settled_by") settledBy = m[2].trim() || null;
803
+ }
804
+ }
805
+ if (!from) from = "unknown";
806
+ return {
807
+ filename,
808
+ from_session: from,
809
+ to_session: recipient,
810
+ subject,
811
+ body,
812
+ sent_at: sent && !Number.isNaN(Date.parse(sent)) ? new Date(sent).toISOString() : null,
813
+ acked,
814
+ // Only the kinds the tool writes; anything else is treated as unset.
815
+ kind: kind && ["brief", "question", "notice", "post", "close"].includes(kind) ? kind : null,
816
+ thread_id: thread,
817
+ reply_to: replyTo,
818
+ tags,
819
+ expires_on: expires,
820
+ evidence: evidence && ["verified", "assumed"].includes(evidence) ? evidence : null,
821
+ settled_by: settledBy && SETTLED_BY.includes(settledBy) ? settledBy : null
822
+ };
823
+ }
824
+ function names(dir) {
825
+ if (!existsSync2(dir)) return [];
826
+ return readdirSync(dir).filter((n) => statSync(path2.join(dir, n)).isDirectory());
827
+ }
828
+ function readMailbox(root) {
829
+ if (!existsSync2(path2.join(root, "inbox"))) throw new Error(`not a crosstalk mailbox (no inbox/ folder): ${root}`);
830
+ const byKey = /* @__PURE__ */ new Map();
831
+ for (const [base, acked] of [["inbox", false], ["archive", true]]) {
832
+ for (const name of names(path2.join(root, base))) {
833
+ const dir = path2.join(root, base, name);
834
+ for (const file of readdirSync(dir).filter((f) => f.endsWith(".md"))) {
835
+ const row22 = parseMessage(file, readFileSync(path2.join(dir, file), "utf8"), name, acked);
836
+ const key = `${name}/${file}`;
837
+ const prev = byKey.get(key);
838
+ if (!prev || acked && !prev.acked) byKey.set(key, { id: key, ...row22 });
839
+ }
840
+ }
841
+ }
842
+ return [...byKey.values()].sort((a, b) => a.id.localeCompare(b.id));
843
+ }
844
+ var esc2 = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
845
+ var age = (d) => d === null ? "no date" : d === 0 ? "today" : d === 1 ? "1 day" : `${d} days`;
846
+ var SETTLED = {
847
+ source: "settled by checking the source",
848
+ owner: "settled by the owner",
849
+ fix: "settled by a fix",
850
+ pushback: "settled after pushback",
851
+ nobody: "no one answered"
852
+ };
853
+ function row(m, bodies, note, showTo = false) {
854
+ const kind = m.kind && m.kind !== "brief" ? `<span class="kind">${esc2(m.kind)}</span> ` : "";
855
+ const to = showTo ? ` <span class="mut">to</span> <span class="chip">${esc2(m.to_session)}</span>` : "";
856
+ return `<details><summary><span class="chip">${esc2(m.from_session)}</span>${to} ${kind}<span class="subj">${esc2(m.subject || "(no subject)")}</span> <span class="note">${esc2(note)}</span></summary><p class="file">${esc2(m.filename)}</p><pre>${esc2(bodies[m.id] ?? "")}</pre></details>`;
857
+ }
858
+ function post(p, bodies) {
859
+ const state = p.state === "closed" ? SETTLED[p.settled_by ?? ""] ?? "closed" : p.state === "expired" ? `past its date (${p.expires_on})` : `open until ${p.expires_on ?? "closed"}`;
860
+ const replies = p.replies.map((r) => row(r, bodies, r.evidence === "verified" ? "checked" : r.evidence === "assumed" ? "from memory, not checked" : "did not say how they know")).join("");
861
+ return `<section class="card"><h3>${esc2(p.title || "(no title)")} ${p.tags.map((t) => `<span class="tag">${esc2(t)}</span>`).join(" ")} <span class="state ${p.state}">${esc2(state)}</span></h3>${row(p.post, bodies, p.post.age_days ? `asked ${age(p.post.age_days)} ago` : "asked today")}${replies}${p.closing ? row(p.closing, bodies, "closing note") : ""}${p.replies.length === 0 && p.state !== "closed" ? '<p class="mut">No replies yet.</p>' : ""}</section>`;
862
+ }
863
+ function renderPage2(r) {
864
+ const waiting = r.waiting.inboxes.map(
865
+ (i) => `<section class="card"><h3>${esc2(i.product)} inbox <span class="note">${i.unread} unread, oldest ${age(i.oldest_age_days)}</span></h3>${i.items.map((m) => row(m, r.bodies, `unread, ${age(m.age_days)}`)).join("")}</section>`
866
+ ).join("");
867
+ const threads = r.threads.map(
868
+ (t) => `<section class="card"><h3>${esc2(t.subject || "(no subject)")} <span class="note">${t.count} ${t.count === 1 ? "message" : "messages"}${t.unread ? `, ${t.unread} unread` : ""} \xB7 ${t.participants.map(esc2).join(", ")}</span></h3>${t.messages.map((m) => row(m, r.bodies, m.acked ? age(m.age_days) : `unread, ${age(m.age_days)}`, true)).join("")}</section>`
869
+ ).join("");
870
+ return `<!doctype html>
871
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
872
+ <title>Crosstalk</title>
873
+ <style>
874
+ :root{--bg:#f7f6f2;--card:#fff;--fg:#1d1c19;--mut:#6b675e;--line:#dedbd2;--well:#f1efe9;--warn:#a1500a;--bad:#a3262b;--ok:#1f6b45}
875
+ @media (prefers-color-scheme:dark){:root{--bg:#161512;--card:#1f1e1a;--fg:#ece9e1;--mut:#a09c91;--line:#35332d;--well:#161512;--warn:#e0a25a;--bad:#ef8a8e;--ok:#7ccba0}}
876
+ body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.5 system-ui,sans-serif}
877
+ main{max-width:860px;margin:0 auto;padding:24px 16px 60px}
878
+ h1{font-size:24px;margin:0}h2{font-size:17px;margin:28px 0 8px}h3{font-size:14px;margin:0;padding:10px 12px}
879
+ .lead{font-size:16px;font-weight:600;margin:6px 0}.mut,.note,.file{color:var(--mut);font-size:12px}.mut{padding:0 12px 10px;margin:0}
880
+ .card{background:var(--card);border:1px solid var(--line);border-radius:12px;margin:10px 0;overflow:hidden}
881
+ details{border-top:1px solid var(--line)}summary{cursor:pointer;padding:8px 12px}
882
+ .chip,.tag,.kind{font-size:11px;border:1px solid var(--line);border-radius:999px;padding:1px 7px}.tag{border-radius:4px;background:var(--well)}.kind{text-transform:uppercase;border-radius:4px}
883
+ .subj{font-weight:500}.file{font-family:ui-monospace,monospace;margin:0;padding:0 12px;word-break:break-all}
884
+ pre{white-space:pre-wrap;word-break:break-word;background:var(--well);margin:8px 12px 12px;padding:10px;border-radius:8px;font-size:12px;max-height:420px;overflow:auto}
885
+ .state{font-size:12px}.state.open{color:var(--ok)}.state.expired{color:var(--bad)}.state.closed{color:var(--mut)}
886
+ </style></head><body><main>
887
+ <h1>Crosstalk</h1>
888
+ <p class="note">${esc2(r.mailbox)} \xB7 ${r.total} messages \xB7 read ${esc2(r.generated_at)}. Refresh to read again. This page is read-only.</p>
889
+ <h2>Waiting</h2><p class="lead">${esc2(r.waiting.headline)}</p>${waiting}
890
+ <h2>Board</h2><p class="lead">${esc2(r.board.headline)}</p>${r.board.open.map((p) => post(p, r.bodies)).join("")}
891
+ ${r.board.closed.length ? `<details class="card"><summary>${r.board.closed.length} closed</summary>${r.board.closed.map((p) => post(p, r.bodies)).join("")}</details>` : ""}
892
+ <h2>Threads</h2><p class="note">The ${r.threads.length} with the newest activity. Where a message carries no thread id, threads are worked out from replies that cite a message or reuse its subject, so some related mail shows as separate.</p>${threads}
893
+ </main></body></html>`;
894
+ }
895
+ var THREADS_SHOWN = 60;
896
+ function buildReport(root, now = Date.now()) {
897
+ const messages = readMailbox(root);
898
+ const waiting = waitingBoard(messages, now);
899
+ const board = boardPosts(messages, now);
900
+ const threads = deriveThreads(messages.filter((m) => m.to_session !== BOARD), now).slice(0, THREADS_SHOWN);
901
+ const shown = /* @__PURE__ */ new Set();
902
+ for (const i of waiting.inboxes) for (const m of i.items) shown.add(m.id);
903
+ for (const t of threads) for (const m of t.messages) shown.add(m.id);
904
+ for (const p of [...board.open, ...board.closed]) {
905
+ shown.add(p.post.id);
906
+ for (const r of p.replies) shown.add(r.id);
907
+ if (p.closing) shown.add(p.closing.id);
908
+ }
909
+ const bodies = {};
910
+ for (const m of messages) if (shown.has(m.id)) bodies[m.id] = m.body;
911
+ return { mailbox: root, generated_at: new Date(now).toISOString(), total: messages.length, waiting, board, threads, bodies };
912
+ }
913
+
914
+ // ../groundcrew/dist/index.mjs
915
+ import { existsSync as existsSync3, readFileSync as readFileSync2, readdirSync as readdirSync2, statSync as statSync2 } from "fs";
916
+ import os3 from "os";
917
+ import path3 from "path";
918
+ var DOCS = "https://code.claude.com/docs/en";
919
+ var MEMORY_LINE_TARGET = 200;
920
+ var MEMORY_LINE_FAIL = 400;
921
+ var plural2 = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
922
+ var all = (files, pick) => files.flatMap(pick);
923
+ function deniesSecrets(rule) {
924
+ return /^Read\(/.test(rule) && /\.env|secret|credential|\.pem|\.key\b|id_rsa/i.test(rule);
925
+ }
926
+ function allowsEveryCommand(rule) {
927
+ return /^Bash(\(\s*(\*|:\*|\*\*)?\s*\))?$/.test(rule.trim());
928
+ }
929
+ function memoryChecks(facts) {
930
+ const source = `${DOCS}/memory.md`;
931
+ if (!facts.memory.length) {
932
+ return [
933
+ {
934
+ id: "memory-exists",
935
+ group: "setup",
936
+ title: "Project instructions",
937
+ status: "warn",
938
+ detail: "No CLAUDE.md or AGENTS.md was found for this project.",
939
+ fix: "Run /init to create one, then cut it down to the lines that prevent a mistake.",
940
+ source
941
+ }
942
+ ];
943
+ }
944
+ const checks = facts.memory.map((file) => {
945
+ const status = file.lines > MEMORY_LINE_FAIL ? "fail" : file.lines > MEMORY_LINE_TARGET ? "warn" : "pass";
946
+ return {
947
+ id: `memory-length:${file.label}`,
948
+ group: "setup",
949
+ title: `${file.label} length`,
950
+ status,
951
+ detail: status === "pass" ? `${plural2(file.lines, "line")}, under the ${MEMORY_LINE_TARGET}-line target.` : `${plural2(file.lines, "line")}. The docs say to target under ${MEMORY_LINE_TARGET} lines per file, because a longer file uses more context and is followed less well. Every session loads all of it.`,
952
+ fix: status === "pass" ? "" : `For each line, ask whether removing it would cause a mistake. Move what only some tasks need into a skill or into ${facts.ruleFiles ? "the existing" : "a"} .claude/rules/ file, and turn a rule that must happen every time into a hook.`,
953
+ source
954
+ };
955
+ });
956
+ const index = facts.autoMemoryIndex;
957
+ if (index) {
958
+ const over = index.lines > 200 || index.bytes > 25e3;
959
+ checks.push({
960
+ id: "auto-memory-index",
961
+ group: "setup",
962
+ title: "Auto memory index",
963
+ status: over ? "warn" : "pass",
964
+ detail: over ? `MEMORY.md is ${plural2(index.lines, "line")} and ${Math.round(index.bytes / 1e3)} KB. Only the first 200 lines or 25 KB are loaded, so the rest is never read.` : `MEMORY.md is ${plural2(index.lines, "line")}, inside what is loaded.`,
965
+ fix: over ? "Shorten the index, or merge entries, so the ones that matter are in the part that loads." : "",
966
+ source
967
+ });
968
+ }
969
+ return checks;
970
+ }
971
+ function automationChecks(facts) {
972
+ const events = [...new Set(all(facts.settings, (f) => f.hookEvents))].sort();
973
+ const allow = all(facts.settings, (f) => f.allow);
974
+ const skills = facts.skills.project + facts.skills.user;
975
+ const checks = [
976
+ {
977
+ id: "hooks",
978
+ group: "setup",
979
+ title: "Hooks",
980
+ status: events.length ? "pass" : "warn",
981
+ detail: events.length ? `Hooks run on: ${events.join(", ")}.` : "No hook is configured, so nothing runs automatically.",
982
+ fix: events.length ? "" : "Our suggestion: a rule that must happen every time, such as formatting or a lint run after an edit, belongs in a hook. A line in CLAUDE.md is advice that can be skipped.",
983
+ source: `${DOCS}/hooks.md`
984
+ },
985
+ {
986
+ id: "allow-rules",
987
+ group: "setup",
988
+ title: "Pre-approved commands",
989
+ status: allow.length ? "pass" : "warn",
990
+ detail: allow.length ? `${plural2(allow.length, "allow rule")} across ${plural2(facts.settings.filter((f) => f.allow.length).length, "settings file")}.` : "No allow rule is set, so every command asks for approval.",
991
+ fix: allow.length ? "" : "Use /permissions to allow the commands you trust, such as your test and lint commands.",
992
+ source: `${DOCS}/permissions.md`
993
+ },
994
+ {
995
+ id: "skills",
996
+ group: "setup",
997
+ title: "Skills",
998
+ status: "info",
999
+ detail: skills ? `${plural2(facts.skills.project, "project skill")} and ${plural2(facts.skills.user, "user skill")}.` : "No skill is defined. A skill holds knowledge that only some tasks need, so it stays out of every other session.",
1000
+ fix: "",
1001
+ source: `${DOCS}/skills.md`
1002
+ }
1003
+ ];
1004
+ if (facts.legacyCommands) {
1005
+ checks.push({
1006
+ id: "legacy-commands",
1007
+ group: "setup",
1008
+ title: "Custom commands",
1009
+ status: "info",
1010
+ detail: `${plural2(facts.legacyCommands, "file")} in .claude/commands/. They still work. The docs merge commands into skills and prefer a skill for new work.`,
1011
+ fix: "",
1012
+ source: `${DOCS}/skills.md`
1013
+ });
1014
+ }
1015
+ checks.push({
1016
+ id: "subagents-and-mcp",
1017
+ group: "setup",
1018
+ title: "Subagents and connected tools",
1019
+ status: "info",
1020
+ detail: `${plural2(facts.subagents.project + facts.subagents.user, "subagent")}. ${plural2(facts.mcpServers.project, "project MCP server")} and ${plural2(facts.mcpServers.user, "user MCP server")}.`,
1021
+ fix: "",
1022
+ source: `${DOCS}/mcp.md`
1023
+ });
1024
+ return checks;
1025
+ }
1026
+ function guardrailChecks(facts) {
1027
+ const files = facts.settings;
1028
+ const deny = all(files, (f) => f.deny);
1029
+ const secretRules = deny.filter(deniesSecrets);
1030
+ const broad = all(files, (f) => f.allow.filter(allowsEveryCommand).map((rule) => `${rule} in ${f.label}`));
1031
+ const modes = files.filter((f) => f.defaultMode).map((f) => ({ mode: f.defaultMode, label: f.label }));
1032
+ const bypass = modes.find((m) => m.mode === "bypassPermissions");
1033
+ const loose = modes.find((m) => m.mode === "dontAsk" || m.mode === "auto");
1034
+ const sandboxOn = files.some((f) => f.sandboxEnabled === true);
1035
+ const windows = facts.platform === "win32";
1036
+ const reach = files.reduce((sum, f) => sum + f.additionalDirectories, 0);
1037
+ const retention = files.map((f) => f.cleanupPeriodDays).find((d) => d !== null) ?? null;
1038
+ const checks = [
1039
+ {
1040
+ id: "deny-secrets",
1041
+ group: "guardrails",
1042
+ title: "Secrets are off limits",
1043
+ status: secretRules.length ? "pass" : facts.secretFiles.length ? "fail" : "warn",
1044
+ detail: secretRules.length ? `${plural2(secretRules.length, "deny rule")} cover secret files: ${secretRules.join(", ")}.` : facts.secretFiles.length ? `No deny rule covers secret files, and this project has ${facts.secretFiles.join(", ")}. The agent can read ${facts.secretFiles.length === 1 ? "it" : "them"}.` : "No deny rule covers secret files. None was found in the project, so nothing is exposed today.",
1045
+ fix: secretRules.length ? "" : `Add deny rules to .claude/settings.json: ${facts.secretFiles.length ? facts.secretFiles.map((file) => `"Read(./${file})"`).join(", ") : '"Read(./.env)" and "Read(./secrets/**)", for example'}. A deny rule is checked before any allow rule.`,
1046
+ source: `${DOCS}/permissions.md`
1047
+ },
1048
+ {
1049
+ id: "broad-allow",
1050
+ group: "guardrails",
1051
+ title: "No blanket approval of shell commands",
1052
+ status: broad.length ? "fail" : "pass",
1053
+ detail: broad.length ? `These rules approve every shell command: ${broad.join("; ")}.` : "No allow rule approves every shell command.",
1054
+ fix: broad.length ? "Replace the blanket rule with rules for the commands you trust." : "",
1055
+ source: `${DOCS}/permissions.md`
1056
+ },
1057
+ {
1058
+ id: "default-mode",
1059
+ group: "guardrails",
1060
+ title: "Permission mode",
1061
+ status: bypass ? "fail" : loose ? "warn" : "pass",
1062
+ detail: bypass ? `${bypass.label} sets the default mode to bypassPermissions, so nothing asks for approval.` : loose ? `${loose.label} sets the default mode to ${loose.mode}, which approves actions without asking.` : modes.length ? `Default mode: ${modes.map((m) => `${m.mode} (${m.label})`).join(", ")}.` : "No default mode is set, so the standard mode applies and actions ask for approval.",
1063
+ fix: bypass ? "Use this mode only inside a container or a virtual machine that holds nothing you care about." : loose ? "Check that this is what you intend on a machine with real credentials." : "",
1064
+ source: `${DOCS}/permissions.md`
1065
+ },
1066
+ {
1067
+ id: "sandbox",
1068
+ group: "guardrails",
1069
+ title: "Sandbox",
1070
+ status: sandboxOn ? "pass" : windows ? "info" : "warn",
1071
+ detail: sandboxOn ? "The sandbox is enabled, so commands run inside OS-level limits." : windows ? "The sandbox is off. It is not supported on native Windows." : "The sandbox is off, which is the default. Commands run with your full access to files and the network.",
1072
+ fix: sandboxOn || windows ? "" : 'Turn it on with /sandbox, or set "sandbox": { "enabled": true } in settings.',
1073
+ source: `${DOCS}/sandboxing.md`
1074
+ },
1075
+ {
1076
+ id: "reach",
1077
+ group: "guardrails",
1078
+ title: "Reach outside the project",
1079
+ status: "info",
1080
+ detail: reach ? `${reach} additional ${reach === 1 ? "directory" : "directories"} outside the project can be reached.` : "No additional directory is granted, so the agent works inside the project.",
1081
+ fix: "",
1082
+ source: `${DOCS}/permissions.md`
1083
+ },
1084
+ {
1085
+ id: "retention",
1086
+ group: "guardrails",
1087
+ title: "Session records",
1088
+ status: "info",
1089
+ detail: `Session transcripts are kept for ${retention ?? 30} days${retention === null ? ", the default" : ""}. They are the record of what the agent did.`,
1090
+ fix: "",
1091
+ source: `${DOCS}/sessions.md`
1092
+ }
1093
+ ];
1094
+ if (files.some((f) => f.scope === "managed")) {
1095
+ checks.push({
1096
+ id: "managed",
1097
+ group: "guardrails",
1098
+ title: "Managed settings",
1099
+ status: "info",
1100
+ detail: "A managed settings file is present. Its rules come first and a project cannot override them.",
1101
+ fix: "",
1102
+ source: `${DOCS}/managed-settings.md`
1103
+ });
1104
+ }
1105
+ return checks;
1106
+ }
1107
+ function looksLikeACheck(command) {
1108
+ return /\b(test|tests|jest|vitest|pytest|mocha|lint|eslint|ruff|tsc|typecheck|type-check|mypy|pyright|check|build|cargo (test|check|clippy)|go (test|vet))\b/i.test(command);
1109
+ }
1110
+ function verificationChecks(facts) {
1111
+ const files = facts.settings;
1112
+ const allowed = all(files, (f) => f.allow.filter((rule) => /^Bash\(/.test(rule) && looksLikeACheck(rule)));
1113
+ const hooked = all(files, (f) => f.hookCommands.filter((h) => looksLikeACheck(h.command)));
1114
+ const stopEvents = [...new Set(all(files, (f) => f.hookEvents.filter((event) => event === "Stop" || event === "SubagentStop")))].sort();
1115
+ const unscoped = facts.subagentFiles.filter((agent) => !agent.limitsTools).map((agent) => agent.name);
1116
+ const checks = [
1117
+ {
1118
+ id: "verify-command",
1119
+ group: "verification",
1120
+ title: "The agent can run your checks",
1121
+ status: allowed.length || hooked.length ? "pass" : "warn",
1122
+ detail: allowed.length || hooked.length ? `${plural2(allowed.length, "allow rule")} and ${plural2(hooked.length, "hook")} name a test, lint, type-check or build command.` : 'No allow rule and no hook names a test, lint, type-check or build command. Without a check it can run, the agent only has "looks done" to go on.',
1123
+ fix: allowed.length || hooked.length ? "" : "Our suggestion: pre-approve the commands that check a change, so the agent can run them without asking each time.",
1124
+ source: `${DOCS}/permissions.md`
1125
+ },
1126
+ {
1127
+ id: "stop-check",
1128
+ group: "verification",
1129
+ title: "Something checks the work before the agent stops",
1130
+ status: stopEvents.length ? "pass" : "warn",
1131
+ detail: stopEvents.length ? `A hook runs on ${stopEvents.join(" and ")}. A Stop hook can send the agent back to keep working.` : "No hook runs when the agent finishes. The agent decides on its own that it is done, and you find out whether it was.",
1132
+ fix: stopEvents.length ? "" : "Our suggestion: a Stop hook that runs a fast check and exits with code 2 when it fails. The docs say that sends Claude back to keep working, and they cap consecutive continuations at eight, so it cannot loop forever.",
1133
+ source: `${DOCS}/hooks.md`
1134
+ }
1135
+ ];
1136
+ if (facts.subagentFiles.length) {
1137
+ checks.push({
1138
+ id: "subagent-scope",
1139
+ group: "verification",
1140
+ title: "Each subagent is limited to the tools its job needs",
1141
+ status: unscoped.length ? "warn" : "pass",
1142
+ detail: unscoped.length ? `${plural2(unscoped.length, "subagent")} set no tools line: ${unscoped.join(", ")}. The docs say a subagent then "inherits every tool available to subagents".` : `All ${plural2(facts.subagentFiles.length, "subagent")} limit their tools.`,
1143
+ fix: unscoped.length ? "Add a tools line to the frontmatter that lists only what the subagent needs, or a disallowedTools line that removes what it must not use." : "",
1144
+ source: `${DOCS}/sub-agents.md`
1145
+ });
1146
+ } else {
1147
+ checks.push({
1148
+ id: "subagent-scope",
1149
+ group: "verification",
1150
+ title: "Subagents",
1151
+ status: "info",
1152
+ detail: "No subagent is defined. A subagent with a narrow job, such as a reviewer that sees only the diff, checks work in a fresh context.",
1153
+ fix: "",
1154
+ source: `${DOCS}/sub-agents.md`
1155
+ });
1156
+ }
1157
+ return checks;
1158
+ }
1159
+ function promptFor(check, facts) {
1160
+ if (check.status !== "fail" && check.status !== "warn") return "";
1161
+ const [id, label] = check.id.split(":");
1162
+ switch (id) {
1163
+ case "memory-exists":
1164
+ return "/init";
1165
+ case "memory-length": {
1166
+ const file = facts.memory.find((m) => m.label === label);
1167
+ return `${label} is ${file?.lines ?? "many"} lines. The Claude Code docs say to target under ${MEMORY_LINE_TARGET} lines per file, because a longer file uses more context and is followed less well. Read it and give me a plan before you edit anything. For each section, say one of: keep; delete, because the code or the README already says it; move to a skill, because only some tasks need it; move to a file under .claude/rules/; or turn into a hook, because it must happen every time. Give the line count the file would have after the plan. Change nothing until I approve it.`;
1168
+ }
1169
+ case "auto-memory-index":
1170
+ return "The auto memory index MEMORY.md is longer than what loads (the first 200 lines or 25 KB). Read it and propose which entries to merge, shorten or remove so that the ones that matter load. Show me the new index before you save it.";
1171
+ case "hooks":
1172
+ return 'This project has no Claude Code hooks. Look at how it formats, lints and tests code. Propose at most two hooks for .claude/settings.json that run after an edit (the PostToolUse event, with the matcher "Edit|Write"), for example the formatter on the changed file. For each one, show me the JSON, the command it runs and how long that command takes. Do not change the settings file until I approve.';
1173
+ case "allow-rules":
1174
+ return "/permissions";
1175
+ case "deny-secrets": {
1176
+ const rules = facts.secretFiles.length ? facts.secretFiles.map((file) => `Read(./${file})`).join(", ") : "Read(./.env), Read(./secrets/**)";
1177
+ return `Add deny rules to the permissions.deny array in .claude/settings.json so that Claude Code cannot read secret files: ${rules}. Keep every rule that is already in the file. Show me the diff before you save it, and tell me how to confirm afterwards that a read of one of these files is refused.`;
1178
+ }
1179
+ case "broad-allow":
1180
+ return "My Claude Code settings hold an allow rule that approves every shell command. Find it in the settings files, then list the shell commands this project really needs, such as its test, lint and build commands. Propose scoped allow rules for those to replace the blanket rule. Show me the diff before you save it.";
1181
+ case "sandbox":
1182
+ return "/sandbox";
1183
+ case "verify-command":
1184
+ return "/permissions";
1185
+ case "stop-check":
1186
+ return "Nothing checks your work before you stop. Look at how this project tests and lints, and find the fastest check that catches a broken change, such as the type check. Propose a Stop hook for .claude/settings.json that runs it and exits with code 2 when it fails, so that you are sent back to keep working. Show me the JSON, the command and how long the command takes. Do not change the settings file until I approve.";
1187
+ case "subagent-scope":
1188
+ return "Some of my subagents inherit every tool. For each subagent file under .claude/agents/, read what it is for and propose a tools line in its frontmatter that lists only the tools that job needs. Show me the proposed line for each file before you edit any of them.";
1189
+ default:
1190
+ return "";
1191
+ }
1192
+ }
1193
+ function runChecks(facts) {
1194
+ const checks = [...memoryChecks(facts), ...automationChecks(facts), ...guardrailChecks(facts), ...verificationChecks(facts)];
1195
+ return checks.map((check) => ({ ...check, prompt: promptFor(check, facts) }));
1196
+ }
1197
+ function summarize2(checks) {
1198
+ const count = (status) => checks.filter((c) => c.status === status).length;
1199
+ const [pass, warn, fail, info] = [count("pass"), count("warn"), count("fail"), count("info")];
1200
+ const judged = pass + warn + fail;
1201
+ return { pass, warn, fail, info, score: judged ? Math.round(pass / judged * 100) : 0 };
1202
+ }
1203
+ var SECRET_NAMES = /^(\.env(\..+)?|secrets?(\..+)?|credentials(\..+)?|.*\.pem|id_rsa)$/i;
1204
+ var NOT_SECRET = /\.(example|sample|template)$/i;
1205
+ var SECRET_DEPTH = 3;
1206
+ var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", "dist", "build", "vendor", "coverage"]);
1207
+ var home = () => os3.homedir();
1208
+ var configDir = () => process.env.CLAUDE_CONFIG_DIR || path3.join(home(), ".claude");
1209
+ var tilde = (file) => file.startsWith(home()) ? `~${file.slice(home().length)}` : file;
1210
+ function canRead(project) {
1211
+ try {
1212
+ readdirSync2(project);
1213
+ return true;
1214
+ } catch {
1215
+ return false;
1216
+ }
1217
+ }
1218
+ function readJson(file) {
1219
+ try {
1220
+ return JSON.parse(readFileSync2(file, "utf-8"));
1221
+ } catch {
1222
+ return null;
1223
+ }
1224
+ }
1225
+ function countFiles(dir, test) {
1226
+ if (!existsSync3(dir)) return 0;
1227
+ let total = 0;
1228
+ for (const entry of readdirSync2(dir, { withFileTypes: true })) {
1229
+ if (entry.isDirectory()) total += countFiles(path3.join(dir, entry.name), test);
1230
+ else if (test(entry.name)) total += 1;
1231
+ }
1232
+ return total;
1233
+ }
1234
+ function findSecretFiles(root, relative, depth) {
1235
+ const dir = path3.join(root, relative);
1236
+ if (depth > SECRET_DEPTH || !existsSync3(dir)) return [];
1237
+ const found = [];
1238
+ for (const entry of readdirSync2(dir, { withFileTypes: true })) {
1239
+ const here = relative ? `${relative}/${entry.name}` : entry.name;
1240
+ if (entry.isDirectory()) {
1241
+ if (!SKIP_DIRS.has(entry.name) && !entry.name.startsWith(".")) found.push(...findSecretFiles(root, here, depth + 1));
1242
+ } else if (SECRET_NAMES.test(entry.name) && !NOT_SECRET.test(entry.name)) {
1243
+ found.push(here);
1244
+ }
1245
+ }
1246
+ return found;
1247
+ }
1248
+ function hookCommands(hooks) {
1249
+ const found = [];
1250
+ for (const [event, groups] of Object.entries(hooks)) {
1251
+ for (const group of Array.isArray(groups) ? groups : []) {
1252
+ for (const handler of Array.isArray(group?.hooks) ? group.hooks : []) {
1253
+ if (typeof handler?.command === "string") found.push({ event, command: handler.command });
1254
+ }
1255
+ }
1256
+ }
1257
+ return found;
1258
+ }
1259
+ function subagentFiles(dir) {
1260
+ if (!existsSync3(dir)) return [];
1261
+ const found = [];
1262
+ for (const entry of readdirSync2(dir, { withFileTypes: true })) {
1263
+ const file = path3.join(dir, entry.name);
1264
+ if (entry.isDirectory()) found.push(...subagentFiles(file));
1265
+ else if (entry.name.endsWith(".md")) {
1266
+ const frontmatter = /^---\n([\s\S]*?)\n---/.exec(readFileSync2(file, "utf-8"))?.[1] ?? "";
1267
+ found.push({ name: entry.name.replace(/\.md$/, ""), limitsTools: /^(tools|disallowedTools)\s*:/m.test(frontmatter) });
1268
+ }
1269
+ }
1270
+ return found;
1271
+ }
1272
+ var isMarkdown = (name) => name.endsWith(".md");
1273
+ var strings = (value) => Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
1274
+ function gather(project) {
1275
+ const filesRead = [];
1276
+ const label = (file) => file.startsWith(project + path3.sep) ? file.slice(project.length + 1) : tilde(file);
1277
+ const memoryFile = (file) => {
1278
+ if (!existsSync3(file) || !statSync2(file).isFile()) return null;
1279
+ const text = readFileSync2(file, "utf-8");
1280
+ filesRead.push(label(file));
1281
+ return { label: label(file), lines: text.split("\n").length - (text.endsWith("\n") ? 1 : 0), bytes: Buffer.byteLength(text) };
1282
+ };
1283
+ const memory = [
1284
+ path3.join(project, "CLAUDE.md"),
1285
+ path3.join(project, ".claude", "CLAUDE.md"),
1286
+ path3.join(project, "CLAUDE.local.md"),
1287
+ path3.join(project, "AGENTS.md"),
1288
+ path3.join(configDir(), "CLAUDE.md")
1289
+ ].map(memoryFile).filter((file) => file !== null);
1290
+ const settingsFile = (scope, file) => {
1291
+ const json = readJson(file);
1292
+ if (!json) return null;
1293
+ filesRead.push(label(file));
1294
+ const permissions = json.permissions || {};
1295
+ const hooks = json.hooks && typeof json.hooks === "object" ? json.hooks : {};
1296
+ return {
1297
+ scope,
1298
+ label: label(file),
1299
+ allow: strings(permissions.allow),
1300
+ ask: strings(permissions.ask),
1301
+ deny: strings(permissions.deny),
1302
+ defaultMode: typeof permissions.defaultMode === "string" ? permissions.defaultMode : null,
1303
+ additionalDirectories: strings(permissions.additionalDirectories).length,
1304
+ hookEvents: Object.keys(hooks).filter((event) => Array.isArray(hooks[event]) && hooks[event].length > 0),
1305
+ hookCommands: hookCommands(hooks),
1306
+ sandboxEnabled: typeof json.sandbox?.enabled === "boolean" ? json.sandbox.enabled : null,
1307
+ cleanupPeriodDays: typeof json.cleanupPeriodDays === "number" ? json.cleanupPeriodDays : null
1308
+ };
1309
+ };
1310
+ const managed = process.platform === "darwin" ? "/Library/Application Support/ClaudeCode/managed-settings.json" : process.platform === "win32" ? "C:\\Program Files\\ClaudeCode\\managed-settings.json" : "/etc/claude-code/managed-settings.json";
1311
+ const settings = [
1312
+ settingsFile("managed", managed),
1313
+ settingsFile("local", path3.join(project, ".claude", "settings.local.json")),
1314
+ settingsFile("project", path3.join(project, ".claude", "settings.json")),
1315
+ settingsFile("user", path3.join(configDir(), "settings.json"))
1316
+ ].filter((file) => file !== null);
1317
+ const projectMcp = readJson(path3.join(project, ".mcp.json"));
1318
+ const userConfig = readJson(path3.join(home(), ".claude.json"));
1319
+ const userServers = Object.keys(userConfig?.mcpServers || {}).length + Object.keys(userConfig?.projects?.[project]?.mcpServers || {}).length;
1320
+ if (projectMcp) filesRead.push(".mcp.json");
1321
+ if (userConfig) filesRead.push("~/.claude.json (MCP server names only)");
1322
+ const encoded = project.replace(/[^a-zA-Z0-9]/g, "-");
1323
+ return {
1324
+ filesRead,
1325
+ facts: {
1326
+ platform: process.platform,
1327
+ memory,
1328
+ ruleFiles: countFiles(path3.join(project, ".claude", "rules"), isMarkdown) + countFiles(path3.join(configDir(), "rules"), isMarkdown),
1329
+ autoMemoryIndex: memoryFile(path3.join(configDir(), "projects", encoded, "memory", "MEMORY.md")),
1330
+ settings,
1331
+ skills: {
1332
+ project: countFiles(path3.join(project, ".claude", "skills"), (name) => name === "SKILL.md"),
1333
+ user: countFiles(path3.join(configDir(), "skills"), (name) => name === "SKILL.md")
1334
+ },
1335
+ subagents: {
1336
+ project: countFiles(path3.join(project, ".claude", "agents"), isMarkdown),
1337
+ user: countFiles(path3.join(configDir(), "agents"), isMarkdown)
1338
+ },
1339
+ subagentFiles: [...subagentFiles(path3.join(project, ".claude", "agents")), ...subagentFiles(path3.join(configDir(), "agents"))],
1340
+ legacyCommands: countFiles(path3.join(project, ".claude", "commands"), isMarkdown),
1341
+ mcpServers: { project: Object.keys(projectMcp?.mcpServers || {}).length, user: userServers },
1342
+ secretFiles: findSecretFiles(project, "", 0).sort()
1343
+ }
1344
+ };
1345
+ }
1346
+ var esc3 = (text) => text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
1347
+ var STATUS = {
1348
+ fail: { icon: "\u2715", word: "Fix" },
1349
+ warn: { icon: "!", word: "Look" },
1350
+ pass: { icon: "\u2713", word: "Good" },
1351
+ info: { icon: "i", word: "Fact" }
1352
+ };
1353
+ var GROUP_TITLE = { setup: "Setup", guardrails: "Guardrails", verification: "Verification" };
1354
+ var GROUPS = [
1355
+ { key: "setup", intro: "What loads into every session, and what runs without being asked." },
1356
+ { key: "guardrails", intro: "What the agent may reach, and what stops it." },
1357
+ { key: "verification", intro: "Who checks the work when the agent says it is done." }
1358
+ ];
1359
+ var ORDER = ["fail", "warn", "pass", "info"];
1360
+ var needsFix = (check) => check.status === "fail" || check.status === "warn";
1361
+ var anchor = (check) => `check-${check.id.replace(/[^a-zA-Z0-9]+/g, "-")}`;
1362
+ var CSS = `
1363
+ :root{--bg:#faf9f6;--card:#fff;--fg:#1c1b19;--mut:#5f5c55;--line:#dddad1;--well:#f1efe9;--fail:#d03b3b;--warn:#fab219;--pass:#0ca30c;--info:#8f8e86}
1364
+ @media (prefers-color-scheme:dark){:root{--bg:#161512;--card:#1f1e1a;--fg:#ece9e1;--mut:#a09c91;--line:#35332d;--well:#161512}}
1365
+ *{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.5 system-ui,sans-serif}
1366
+ main{max-width:860px;margin:0 auto;padding:28px 16px 60px}h1{font-size:26px;margin:0}h2{font-size:19px;margin:36px 0 2px}
1367
+ p{margin:6px 0}.mut{color:var(--mut)}code,pre{font:13px/1.5 ui-monospace,Menlo,monospace}a{color:inherit}[id]{scroll-margin-top:14px}
1368
+ .score{display:flex;flex-wrap:wrap;gap:10px;margin:18px 0 0}.tile{flex:1;min-width:120px;background:var(--card);border:1px solid var(--line);
1369
+ border-radius:10px;padding:10px 14px}.tile b{display:block;font-size:26px;line-height:1.15}.tile span{font-size:12.5px;color:var(--mut)}
1370
+ .bar{display:flex;gap:2px;height:8px;margin:14px 0 0}.bar i{display:block;border-radius:999px}
1371
+ .todo{margin:14px 0 0;padding:0;list-style:none}.todo li{display:flex;gap:8px;align-items:center;padding:3px 0;font-size:14.5px}
1372
+ .check{background:var(--card);border:1px solid var(--line);border-left-width:5px;border-radius:10px;padding:12px 14px;margin:10px 0 0}
1373
+ .check h3{font-size:15.5px;margin:0;display:flex;align-items:center;gap:8px}.check p{font-size:14px}
1374
+ .dot{display:inline-flex;align-items:center;justify-content:center;width:18px;height:18px;border-radius:50%;font-size:11px;font-weight:700;
1375
+ color:#fff;flex:none}.word{font-size:11.5px;font-weight:600;color:var(--mut);border:1px solid var(--line);border-radius:999px;padding:0 8px;margin-left:auto}
1376
+ .fix{border-top:1px solid var(--line);margin-top:8px;padding-top:8px}.src{font-size:12.5px}
1377
+ .prompt{margin-top:10px;border:1px solid var(--line);border-radius:8px;background:var(--well)}
1378
+ .prompt header{display:flex;align-items:center;gap:8px;padding:6px 10px;border-bottom:1px solid var(--line);font-size:12.5px;color:var(--mut)}
1379
+ .prompt pre{margin:0;padding:10px;white-space:pre-wrap;overflow-wrap:anywhere;color:var(--fg)}
1380
+ .prompt button{margin-left:auto;font:600 12.5px system-ui,sans-serif;color:var(--fg);background:var(--card);border:1px solid var(--line);border-radius:6px;
1381
+ padding:3px 12px;cursor:pointer}.prompt button:hover{border-color:var(--mut)}.prompt button:focus-visible{outline:2px solid var(--fg);outline-offset:2px}
1382
+ .rows{margin:10px 0 0;padding:0;list-style:none;background:var(--card);border:1px solid var(--line);border-radius:10px}
1383
+ .rows li{display:grid;grid-template-columns:18px minmax(120px,220px) 1fr;gap:4px 10px;align-items:start;padding:8px 12px;font-size:14px}
1384
+ .rows li+li{border-top:1px solid var(--line)}.rows .dot{margin-top:2px}.rows b{font-weight:600}.rows .src{grid-column:3}
1385
+ @media (max-width:600px){.rows li{grid-template-columns:18px 1fr}.rows span.d,.rows .src{grid-column:2}}
1386
+ footer{margin-top:40px;border-top:1px solid var(--line);padding-top:12px;font-size:13px;color:var(--mut)}footer li{margin:2px 0}
1387
+ ${ORDER.map((s) => `.s-${s}{border-left-color:var(--${s})}.s-${s} .dot,.s-${s}.dot,.bar .b-${s}{background:var(--${s})}`).join("")}
1388
+ .s-warn .dot,.s-warn.dot{color:#0b0b0b}`;
1389
+ var COPY_SCRIPT = `document.addEventListener('click',function(e){var b=e.target.closest('button[data-copy]');if(!b)return;
1390
+ var t=document.getElementById(b.getAttribute('data-copy')).textContent;
1391
+ function done(){b.textContent='Copied';setTimeout(function(){b.textContent='Copy'},1600)}
1392
+ function old(){var a=document.createElement('textarea');a.value=t;document.body.appendChild(a);a.select();document.execCommand('copy');a.remove();done()}
1393
+ if(navigator.clipboard&&window.isSecureContext){navigator.clipboard.writeText(t).then(done,old)}else{old()}});`;
1394
+ var dot = (status) => `<span class="dot s-${status}" aria-hidden="true">${STATUS[status].icon}</span>`;
1395
+ var sourceLink = (check) => `<a href="${esc3(check.source)}" target="_blank" rel="noopener noreferrer">${esc3(check.source.replace(/^https:\/\/code\.claude\.com\/docs\/en\//, "docs: ").replace(/\.md$/, ""))}</a>`;
1396
+ function fixCard(check) {
1397
+ const status = STATUS[check.status];
1398
+ const id = anchor(check);
1399
+ const isCommand = check.prompt.startsWith("/");
1400
+ const prompt = check.prompt ? `<div class="prompt"><header>${isCommand ? "Type this command in Claude Code" : "Paste this into Claude Code"}<button type="button" data-copy="${id}-prompt">Copy</button></header><pre id="${id}-prompt">${esc3(check.prompt)}</pre></div>` : "";
1401
+ return `<section class="check s-${check.status}" id="${id}"><h3>${dot(check.status)}${esc3(check.title)}<span class="word">${status.word}</span></h3><p>${esc3(check.detail)}</p>${check.fix ? `<p class="fix"><b>What to change:</b> ${esc3(check.fix)}</p>` : ""}${prompt}<p class="src mut">Rests on ${sourceLink(check)}</p></section>`;
1402
+ }
1403
+ var row2 = (check) => `<li>${dot(check.status)}<b>${esc3(check.title)}<span class="mut"> \xB7 ${STATUS[check.status].word}</span></b><span class="d">${esc3(check.detail)}</span><span class="src mut">${sourceLink(check)}</span></li>`;
1404
+ function renderPage3(report2) {
1405
+ const { summary } = report2;
1406
+ const judged = summary.pass + summary.warn + summary.fail;
1407
+ const bar = ["fail", "warn", "pass"].filter((s) => summary[s] > 0).map((s) => `<i class="b-${s}" style="flex:${summary[s]}"></i>`).join("");
1408
+ const sorted = [...report2.checks].sort((a, b) => ORDER.indexOf(a.status) - ORDER.indexOf(b.status));
1409
+ const fixes = sorted.filter(needsFix);
1410
+ const todo = fixes.length ? `<h2>Do these first</h2><ul class="todo">${fixes.map((c) => `<li>${dot(c.status)}<a href="#${anchor(c)}">${esc3(c.title)}</a><span class="mut">${GROUP_TITLE[c.group]}</span></li>`).join("")}</ul>` : '<h2>Nothing to fix</h2><p class="mut">Every check that can fail passes.</p>';
1411
+ const groups = GROUPS.map((group) => {
1412
+ const mine = sorted.filter((c) => c.group === group.key);
1413
+ const rest = mine.filter((c) => !needsFix(c));
1414
+ return `<h2>${GROUP_TITLE[group.key]}</h2><p class="mut">${group.intro}</p>${mine.filter(needsFix).map(fixCard).join("")}` + (rest.length ? `<ul class="rows">${rest.map(row2).join("")}</ul>` : "");
1415
+ }).join("");
1416
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>JQ Groundcrew: ${esc3(report2.project)}</title><style>${CSS}</style></head><body><main><h1>JQ Groundcrew</h1><p class="mut">The setup check for Claude Code. How it is set up for <code>${esc3(report2.project)}</code>. Read ${esc3(report2.generatedAt)}. Refresh to read again.</p><div class="score"><div class="tile"><b>${summary.fail}</b><span>to fix</span></div><div class="tile"><b>${summary.warn}</b><span>to look at</span></div><div class="tile"><b>${summary.pass}</b><span>good</span></div><div class="tile"><b>${summary.score}%</b><span>of ${judged} checks pass</span></div></div><div class="bar" role="img" aria-label="${summary.fail} to fix, ${summary.warn} to look at, ${summary.pass} good">${bar}</div>` + todo + groups + `<footer><p>This page was made on your machine from the files below, and it loads nothing, so nothing left the machine. Its one script copies a prompt to your clipboard when you press Copy. It read settings and counted files. It did not read the contents of any secret file, and it read no session transcript.</p><p>A suggested prompt asks Claude Code to show its plan or its diff first. Read that before you approve it.</p><ul>${report2.filesRead.map((file) => `<li><code>${esc3(file)}</code></li>`).join("")}</ul><p>Each check names the page of Anthropic\u2019s Claude Code documentation it rests on. The documentation was checked on 2026-11-14 and can change.</p></footer></main><script>${COPY_SCRIPT}</script></body></html>
1417
+ `;
1418
+ }
1419
+ function report(project) {
1420
+ const { facts, filesRead } = gather(project);
1421
+ const checks = runChecks(facts);
1422
+ return { project: tilde(project), generatedAt: (/* @__PURE__ */ new Date()).toLocaleString("en-US"), filesRead, checks, summary: summarize2(checks) };
1423
+ }
1424
+
1425
+ // src/collect.ts
1426
+ import { existsSync as existsSync5, readdirSync as readdirSync3, readFileSync as readFileSync4, statSync as statSync3 } from "fs";
1427
+ import path5 from "path";
1428
+
1429
+ // src/deck.ts
1430
+ import { createHash } from "crypto";
1431
+ import { existsSync as existsSync4, readFileSync as readFileSync3 } from "fs";
1432
+ import os4 from "os";
1433
+ import path4 from "path";
1434
+ var expandHome = (p) => p === "~" || p.startsWith("~/") ? path4.join(os4.homedir(), p.slice(1)) : p;
1435
+ function defaultConfigFile() {
1436
+ return path4.join(os4.homedir(), ".jq", "config.json");
1437
+ }
1438
+ function loadConfig(file) {
1439
+ if (!existsSync4(file)) return {};
1440
+ let raw;
1441
+ try {
1442
+ raw = JSON.parse(readFileSync3(file, "utf8"));
1443
+ } catch (e) {
1444
+ throw new Error(`cannot read ${file}: ${e?.message || e}`);
1445
+ }
1446
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error(`${file} must hold a JSON object`);
1447
+ const r = raw;
1448
+ const out = {};
1449
+ if (typeof r.mailbox === "string") out.mailbox = expandHome(r.mailbox);
1450
+ if (r.names && typeof r.names === "object" && !Array.isArray(r.names)) {
1451
+ out.names = {};
1452
+ for (const [k, v] of Object.entries(r.names)) if (typeof v === "string") out.names[k] = path4.resolve(expandHome(v));
1453
+ }
1454
+ if (Array.isArray(r.report)) out.report = r.report.filter((q) => typeof q === "string");
1455
+ if (Array.isArray(r.sendQuestions)) out.sendQuestions = r.sendQuestions.filter((q) => typeof q === "string").map(expandHome);
1456
+ if (Array.isArray(r.questions)) out.questions = r.questions.filter((q) => typeof q === "string").map(expandHome);
1457
+ return out;
1458
+ }
1459
+ function findMailbox(opts) {
1460
+ const named = opts.flag || opts.config || opts.env;
1461
+ if (named) return path4.resolve(expandHome(named));
1462
+ let dir = path4.resolve(opts.cwd);
1463
+ for (; ; ) {
1464
+ if (existsSync4(path4.join(dir, ".crosstalk"))) return dir;
1465
+ const up = path4.dirname(dir);
1466
+ if (up === dir) return null;
1467
+ dir = up;
1468
+ }
1469
+ }
1470
+ var repoId = (tree) => createHash("sha1").update(tree).digest("hex").slice(0, 10);
1471
+ function matchInbox(folder, inboxes) {
1472
+ const f = folder.toLowerCase();
1473
+ const exact = inboxes.find((i) => i.toLowerCase() === f);
1474
+ if (exact) return exact;
1475
+ const starts = inboxes.filter((i) => f.startsWith(i.toLowerCase()) && /[-_. ]/.test(f[i.length] ?? ""));
1476
+ return starts.length === 1 ? starts[0] : null;
1477
+ }
1478
+ var plural3 = (n, one, many) => `${n} ${n === 1 ? one : many}`;
1479
+ function buildHeadline(repos, mail, mailNote) {
1480
+ const needs = repos.reduce((n, r) => n + r.needs_you, 0);
1481
+ const sessions = repos.reduce((n, r) => n + r.sessions, 0);
1482
+ const failing = repos.filter((r) => r.setup && r.setup.fail > 0).length;
1483
+ const checked = repos.filter((r) => r.setup).length;
1484
+ const parts = [
1485
+ needs > 0 ? `${plural3(needs, "session is", "sessions are")} waiting on you` : `No session is waiting on you (${plural3(sessions, "session", "sessions")} read)`,
1486
+ mail ? mail.total_unread > 0 ? plural3(mail.total_unread, "unread message", "unread messages") : "no unread mail" : mailNote ? "the mailbox could not be read" : "no mailbox set",
1487
+ failing > 0 ? `${plural3(failing, "repository has", "repositories have")} a setup check to fix` : `no failing setup check in ${plural3(checked, "repository", "repositories")}`
1488
+ ];
1489
+ return parts.join(", ") + ".";
1490
+ }
1491
+ function buildOverview(input) {
1492
+ const { snapshot: snapshot2, waiting } = input;
1493
+ const byTree = /* @__PURE__ */ new Map();
1494
+ for (const r of snapshot2.sessions) byTree.set(r.working_tree, [...byTree.get(r.working_tree) ?? [], r]);
1495
+ const inboxes = new Set(input.inboxes ?? []);
1496
+ const named = new Map(Object.entries(input.names ?? {}).map(([inbox, tree]) => [tree, inbox]));
1497
+ const matched = /* @__PURE__ */ new Set();
1498
+ const repos = [...new Set(input.trees)].map((tree) => {
1499
+ const rows = byTree.get(tree) ?? [];
1500
+ const attention = rows.map((r) => deriveAttention(r.state, r.waiting));
1501
+ const name = rows[0]?.product || tree.split("/").filter(Boolean).pop() || tree;
1502
+ const setup = input.setups.get(tree);
1503
+ const inbox = waiting ? named.get(tree) ?? matchInbox(name, [...inboxes]) : null;
1504
+ if (inbox) matched.add(inbox);
1505
+ const waitingFor = inbox ? waiting?.inboxes.find((i) => i.product === inbox) : void 0;
1506
+ return {
1507
+ id: repoId(tree),
1508
+ name,
1509
+ tree,
1510
+ sessions: rows.length,
1511
+ live: rows.filter((r) => r.state === "live").length,
1512
+ needs_you: attention.filter((a) => a === "needs-you").length,
1513
+ abandoned: attention.filter((a) => a === "abandoned").length,
1514
+ last_activity_at: rows.map((r) => r.last_activity_at || "").sort().pop() || null,
1515
+ waiting_since: rows.filter((_, i) => attention[i] === "needs-you").map((r) => r.last_activity_at || "").filter(Boolean).sort()[0] ?? null,
1516
+ questions: rows.filter((r, i) => attention[i] === "needs-you" && r.question_allowed && !!r.blocked_question).map((r) => ({ asked_at: r.last_activity_at, text: r.blocked_question })).sort((a, b) => (a.asked_at || "").localeCompare(b.asked_at || "")),
1517
+ remote: input.remotes?.get(tree) ?? null,
1518
+ setup: setup && "summary" in setup ? { score: setup.summary.score, fail: setup.summary.fail, warn: setup.summary.warn } : null,
1519
+ setup_note: setup && "error" in setup ? setup.error : setup ? null : "not checked",
1520
+ inbox,
1521
+ unread: inbox ? waitingFor?.unread ?? 0 : null,
1522
+ oldest_unread_days: waitingFor?.oldest_age_days ?? null
1523
+ };
1524
+ });
1525
+ repos.sort((a, b) => b.needs_you - a.needs_you || (b.last_activity_at || "").localeCompare(a.last_activity_at || "") || a.name.localeCompare(b.name));
1526
+ const mail = waiting ? {
1527
+ total_unread: waiting.total_unread,
1528
+ headline: waiting.headline,
1529
+ unmatched: waiting.inboxes.filter((i) => !matched.has(i.product)).map((i) => ({ inbox: i.product, unread: i.unread }))
1530
+ } : null;
1531
+ const mailNote = input.mailNote ?? null;
1532
+ return {
1533
+ machine: snapshot2.machine,
1534
+ generated_at: snapshot2.generated_at,
1535
+ headline: buildHeadline(repos, mail, mailNote),
1536
+ repos,
1537
+ mailbox: input.mailbox,
1538
+ mail,
1539
+ mail_note: mailNote
1540
+ };
1541
+ }
1542
+ function normalizeRemote(url) {
1543
+ const u = url.trim();
1544
+ const m = /^[a-z+]+:\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?\/(.+)$/i.exec(u) ?? /^(?:[^@/]+@)?([^/:]+):(?!\/)(.+)$/.exec(u);
1545
+ if (!m) return null;
1546
+ const repoPath = m[2].replace(/\.git$/i, "").replace(/^\/+|\/+$/g, "");
1547
+ if (!repoPath || /\s/.test(repoPath)) return null;
1548
+ return `${m[1].toLowerCase()}/${repoPath}`;
1549
+ }
1550
+ function originIn(config) {
1551
+ let inOrigin = false;
1552
+ for (const line of config.split("\n")) {
1553
+ const section = /^\s*\[(.+)\]\s*$/.exec(line);
1554
+ if (section) inOrigin = /^remote\s+"origin"$/.test(section[1].trim());
1555
+ else if (inOrigin) {
1556
+ const url = /^\s*url\s*=\s*(.+?)\s*$/.exec(line);
1557
+ if (url) return normalizeRemote(url[1]);
1558
+ }
1559
+ }
1560
+ return null;
1561
+ }
1562
+ function under(tree, folders) {
1563
+ return folders.some((f) => {
1564
+ const folder = path4.resolve(expandHome(f));
1565
+ return tree === folder || tree.startsWith(folder + path4.sep);
1566
+ });
1567
+ }
1568
+ function reportable(r, only) {
1569
+ return only.some((entry) => {
1570
+ const e = entry.trim();
1571
+ if (!e) return false;
1572
+ if (e.toLowerCase() === r.name.toLowerCase() || !!r.remote && e.toLowerCase() === r.remote.toLowerCase()) return true;
1573
+ return /^[~/.]/.test(e) && path4.resolve(expandHome(e)) === r.tree;
1574
+ });
1575
+ }
1576
+ function teamReport(o, only = null, sendQuestions = []) {
1577
+ return {
1578
+ v: 1,
1579
+ generated_at: o.generated_at,
1580
+ repos: o.repos.filter((r) => only === null || reportable(r, only)).map((r) => ({
1581
+ name: r.name,
1582
+ remote: r.remote,
1583
+ sessions: r.sessions,
1584
+ live: r.live,
1585
+ needs_you: r.needs_you,
1586
+ abandoned: r.abandoned,
1587
+ waiting_since: r.waiting_since,
1588
+ last_activity_at: r.last_activity_at,
1589
+ setup: r.setup,
1590
+ unread: r.unread,
1591
+ ...r.questions.length > 0 && under(r.tree, sendQuestions) ? { questions: r.questions } : {}
1592
+ }))
1593
+ };
1594
+ }
1595
+
1596
+ // src/collect.ts
1597
+ function looksLikeProject(dir) {
1598
+ return [".git", ".claude", "CLAUDE.md"].some((f) => existsSync5(path5.join(dir, f)));
1599
+ }
1600
+ function checkSetup(tree) {
1601
+ if (!existsSync5(tree)) return { error: "the folder is gone" };
1602
+ if (!canRead(tree)) return { error: "the folder cannot be read" };
1603
+ try {
1604
+ return { summary: summarize2(runChecks(gather(tree).facts)) };
1605
+ } catch (e) {
1606
+ return { error: String(e?.message || e) };
1607
+ }
1608
+ }
1609
+ function remoteOf(tree) {
1610
+ try {
1611
+ let gitDir = path5.join(tree, ".git");
1612
+ if (statSync3(gitDir).isFile()) {
1613
+ const m = /^gitdir:\s*(.+)$/m.exec(readFileSync4(gitDir, "utf8"));
1614
+ if (!m) return null;
1615
+ gitDir = path5.resolve(tree, m[1].trim());
1616
+ const common = path5.join(gitDir, "commondir");
1617
+ if (existsSync5(common)) gitDir = path5.resolve(gitDir, readFileSync4(common, "utf8").trim());
1618
+ }
1619
+ return originIn(readFileSync4(path5.join(gitDir, "config"), "utf8"));
1620
+ } catch {
1621
+ return null;
1622
+ }
1623
+ }
1624
+ function treesOf(snap, cwd) {
1625
+ const trees = [...new Set(snap.sessions.map((r) => r.working_tree))];
1626
+ if (cwd && !trees.includes(cwd) && looksLikeProject(cwd)) trees.push(cwd);
1627
+ return trees;
1628
+ }
1629
+ async function collectOverview(opts) {
1630
+ const snap = await snapshot({ ...opts, sample: false });
1631
+ const trees = treesOf(snap, opts.cwd);
1632
+ const setups = new Map(trees.map((t) => [t, checkSetup(t)]));
1633
+ let waiting = null;
1634
+ let inboxes = [];
1635
+ let mailNote = null;
1636
+ if (opts.mailbox) {
1637
+ try {
1638
+ waiting = waitingBoard(readMailbox(opts.mailbox), opts.now ?? Date.now());
1639
+ inboxes = readdirSync3(path5.join(opts.mailbox, "inbox"), { withFileTypes: true }).filter((e) => e.isDirectory() && e.name !== BOARD).map((e) => e.name);
1640
+ } catch (e) {
1641
+ mailNote = String(e?.message || e);
1642
+ }
1643
+ }
1644
+ const remotes = /* @__PURE__ */ new Map();
1645
+ for (const t of trees) {
1646
+ const remote = remoteOf(t);
1647
+ if (remote) remotes.set(t, remote);
1648
+ }
1649
+ return buildOverview({ snapshot: snap, trees, setups, waiting, inboxes, mailbox: opts.mailbox, mailNote, names: opts.names, remotes });
1650
+ }
1651
+
1652
+ // src/page.ts
1653
+ var TABS = ["overview", "sessions", "setup", "mail"];
1654
+ var TAB_TITLE = { overview: "Overview", sessions: "Sessions", setup: "Setup", mail: "Mail" };
1655
+ var esc4 = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
1656
+ function pickRepo(repos, asked) {
1657
+ const checked = repos.filter((r) => r.setup);
1658
+ return checked.find((r) => r.id === asked) ?? checked.find((r) => r.setup.fail > 0) ?? checked[0] ?? null;
1659
+ }
1660
+ function setupCell(r) {
1661
+ if (!r.setup) return `<span class="mut">${esc4(r.setup_note || "not checked")}</span>`;
1662
+ const s = r.setup;
1663
+ const word = s.fail > 0 ? `<span class="bad">${s.fail} to fix</span>` : s.warn > 0 ? `<span class="warn">${s.warn} to look at</span>` : '<span class="ok">all good</span>';
1664
+ return `<a href="/?tab=setup&amp;repo=${r.id}">${s.score}%</a> ${word}`;
1665
+ }
1666
+ function mailCell(r) {
1667
+ if (r.unread === null) return '<span class="mut">no inbox</span>';
1668
+ if (r.unread === 0) return '<span class="mut">none unread</span>';
1669
+ const age2 = r.oldest_unread_days ? `, oldest ${r.oldest_unread_days}d` : "";
1670
+ return `<a href="/?tab=mail">${r.unread} unread</a><span class="mut">${age2}</span>`;
1671
+ }
1672
+ function sessionsCell(r) {
1673
+ if (r.sessions === 0) return '<span class="mut">none</span>';
1674
+ const need = r.needs_you > 0 ? ` <span class="warn">${r.needs_you} waiting on you</span>` : "";
1675
+ const left = r.abandoned > 0 ? ` <span class="mut">${r.abandoned} asked, then left</span>` : "";
1676
+ return `<a href="/?tab=sessions">${r.sessions}</a> <span class="mut">(${r.live} live)</span>${need}${left}`;
1677
+ }
1678
+ function overview(o) {
1679
+ if (o.repos.length === 0) {
1680
+ return '<p class="card pad">No Claude Code session has been active in the window read, and this folder is not a project. Start a session, or run <code>jq-deck</code> inside a repository.</p>';
1681
+ }
1682
+ const rows = o.repos.map(
1683
+ (r) => `<tr><th scope="row">${esc4(r.name)}<span class="path">${esc4(r.tree)}</span></th><td data-l="Sessions">${sessionsCell(r)}</td><td data-l="Setup">${setupCell(r)}</td><td data-l="Mail">${mailCell(r)}</td></tr>`
1684
+ ).join("");
1685
+ const unmatched = o.mail?.unmatched.length ? `<p class="mut note">Unread mail for an inbox with no repository on this page: ${o.mail.unmatched.map((u) => `${esc4(u.inbox)} (${u.unread})`).join(", ")}. <a href="/?tab=mail">Open Mail</a>. To tie an inbox to a folder, add it under <code>names</code> in the config file.</p>` : "";
1686
+ return `<div class="card"><table><thead><tr><th scope="col">Repository</th><th scope="col">Sessions</th><th scope="col">Setup</th><th scope="col">Mail</th></tr></thead><tbody>${rows}</tbody></table></div>${unmatched}`;
1687
+ }
1688
+ function setupTab(o, asked) {
1689
+ const chosen = pickRepo(o.repos, asked);
1690
+ if (!chosen) return '<p class="card pad">No repository to check yet. A repository appears here once a session has run in it.</p>';
1691
+ const chips = o.repos.filter((r) => r.setup).map((r) => `<a class="chip${r.id === chosen.id ? " on" : ""}" href="/?tab=setup&amp;repo=${r.id}"${r.id === chosen.id ? ' aria-current="true"' : ""}>${esc4(r.name)} <b>${r.setup.score}%</b></a>`).join("");
1692
+ return `<nav class="chips" aria-label="Repository">${chips}</nav><iframe title="Setup check for ${esc4(chosen.name)}" src="/raw/setup?repo=${chosen.id}"></iframe>`;
1693
+ }
1694
+ function mailTab(o) {
1695
+ if (o.mail_note) return `<p class="card pad">The mailbox at <code>${esc4(o.mailbox)}</code> could not be read: ${esc4(o.mail_note)}</p>`;
1696
+ if (!o.mailbox) {
1697
+ return `<div class="card pad"><p>No mailbox found. A mailbox lets sessions send each other briefs and questions.</p><p>To make one, with one name per session:</p><pre>npx @point-seven-studio/jq-crosstalk init ~/crosstalk api web</pre><p>Then start this page with <code>--mailbox ~/crosstalk</code>, or set <code>$CROSSTALK_DIR</code>.</p></div>`;
1698
+ }
1699
+ return '<iframe title="Mailbox" src="/raw/mail"></iframe>';
1700
+ }
1701
+ function renderShell(o, tab, repo, version) {
1702
+ const body = tab === "overview" ? overview(o) : tab === "sessions" ? '<iframe title="Sessions" src="/raw/sessions"></iframe>' : tab === "setup" ? setupTab(o, repo) : mailTab(o);
1703
+ const needs = o.repos.reduce((n, r) => n + r.needs_you, 0);
1704
+ const failing = o.repos.filter((r) => r.setup && r.setup.fail > 0).length;
1705
+ const count = { overview: 0, sessions: needs, setup: failing, mail: o.mail?.total_unread ?? 0 };
1706
+ const tabs = TABS.map(
1707
+ (t) => `<a href="/?tab=${t}"${t === tab ? ' class="on" aria-current="page"' : ""}>${TAB_TITLE[t]}${count[t] > 0 ? ` <b>${count[t]}</b>` : ""}</a>`
1708
+ ).join("");
1709
+ return `<!doctype html>
1710
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
1711
+ <title>JQ Deck</title>
1712
+ <style>
1713
+ :root{--bg:#f7f6f2;--card:#fff;--fg:#1d1c19;--mut:#6b675e;--line:#dedbd2;--well:#f1efe9;--warn:#a1500a;--ok:#1f6b45;--bad:#a3262b;--link:#1d4f91}
1714
+ @media (prefers-color-scheme:dark){:root{--bg:#161512;--card:#1f1e1a;--fg:#ece9e1;--mut:#a09c91;--line:#35332d;--well:#161512;--warn:#e0a25a;--ok:#7ccba0;--bad:#ef8a8e;--link:#8fb8ee}}
1715
+ *{box-sizing:border-box}
1716
+ body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.5 system-ui,sans-serif;display:flex;flex-direction:column;min-height:100vh}
1717
+ header{padding:16px 16px 0;max-width:1000px;width:100%;margin:0 auto}
1718
+ h1{font-size:22px;margin:0}.head{margin:4px 0 0;font-weight:600}
1719
+ .mut{color:var(--mut);font-size:12px}.ok{color:var(--ok)}.warn{color:var(--warn)}.bad{color:var(--bad)}.ok,.warn,.bad{font-size:12px;font-weight:600}
1720
+ a{color:var(--link)}
1721
+ nav.tabs{display:flex;gap:4px;margin-top:14px;border-bottom:1px solid var(--line);overflow-x:auto}
1722
+ nav.tabs a{padding:8px 12px;text-decoration:none;color:var(--mut);border-bottom:2px solid transparent;white-space:nowrap}
1723
+ nav.tabs a.on{color:var(--fg);border-color:var(--fg);font-weight:600}
1724
+ nav.tabs b{font-size:11px;border:1px solid var(--line);border-radius:9px;padding:0 6px;margin-left:2px}
1725
+ main{flex:1;display:flex;flex-direction:column;max-width:1000px;width:100%;margin:0 auto;padding:14px 16px 24px}
1726
+ iframe{flex:1;width:100%;min-height:70vh;border:1px solid var(--line);border-radius:12px;background:var(--bg)}
1727
+ .card{background:var(--card);border:1px solid var(--line);border-radius:12px;overflow:hidden}.pad{padding:14px 16px;margin:0}
1728
+ .pad p{margin:0 0 8px}.note{margin:10px 2px}
1729
+ table{width:100%;border-collapse:collapse}th,td{text-align:left;padding:10px 12px;border-top:1px solid var(--line);vertical-align:top}
1730
+ thead th{border-top:0;font-size:12px;color:var(--mut);font-weight:600}
1731
+ tbody th{font-weight:600}.path{display:block;font-weight:400;font-size:12px;color:var(--mut);word-break:break-all}
1732
+ .chips{display:flex;flex-wrap:wrap;gap:6px;margin-bottom:10px}
1733
+ .chip{border:1px solid var(--line);border-radius:14px;padding:2px 10px;font-size:13px;text-decoration:none;color:var(--fg);background:var(--card)}
1734
+ .chip.on{border-color:var(--fg);font-weight:600}
1735
+ code,pre{font:12px ui-monospace,monospace;background:var(--well);border-radius:4px;padding:1px 4px}pre{padding:10px;overflow-x:auto}
1736
+ @media (max-width:640px){thead{display:none}tr{display:block;border-top:1px solid var(--line);padding:8px 0}th,td{display:block;border:0;padding:3px 12px}td::before{content:attr(data-l) ": ";color:var(--mut);font-size:12px}}
1737
+ </style></head><body>
1738
+ <header>
1739
+ <h1>JQ Deck</h1>
1740
+ <p class="head">${esc4(o.headline)}</p>
1741
+ <p class="mut">${esc4(o.machine)} \xB7 read ${esc4(o.generated_at)}. Refresh to read again. Read-only: nothing on this page writes to a session or a mailbox.</p>
1742
+ <nav class="tabs" aria-label="Views">${tabs}</nav>
1743
+ </header>
1744
+ <main>${body}</main>
1745
+ <footer class="mut" style="max-width:1000px;width:100%;margin:0 auto;padding:0 16px 16px">JQ Deck ${esc4(version)} \xB7 this machine only</footer>
1746
+ </body></html>`;
1747
+ }
1748
+
1749
+ // src/cli.ts
1750
+ var DEFAULT_PORT = 4316;
1751
+ var list = (s) => (s || "").split(",").map((x) => x.trim()).filter(Boolean);
1752
+ function parseArgs(argv, env = {}) {
1753
+ const a = {
1754
+ json: false,
1755
+ watch: false,
1756
+ exec: null,
1757
+ intervalS: Number(env.JQ_DECK_INTERVAL_S) || 60,
1758
+ repos: null,
1759
+ allRepos: false,
1760
+ sendQuestions: null,
1761
+ port: DEFAULT_PORT,
1762
+ mailbox: null,
1763
+ config: env.JQ_DECK_CONFIG || defaultConfigFile(),
1764
+ questionTrees: env.JQ_AGENTS_QUESTION_TREES ? list(env.JQ_AGENTS_QUESTION_TREES) : null,
1765
+ probe: false,
1766
+ sample: true,
1767
+ maxAgeDays: Number(env.JQ_AGENTS_MAX_AGE_DAYS) || 3
1768
+ };
1769
+ const value = (i, flag) => {
1770
+ const v = argv[i + 1];
1771
+ if (v === void 0 || v.startsWith("--")) throw new Error(`${flag} needs a value`);
1772
+ return v;
1773
+ };
1774
+ for (let i = 0; i < argv.length; i++) {
1775
+ const f = argv[i];
1776
+ if (f === "--json") a.json = true;
1777
+ else if (f === "--watch") a.watch = true;
1778
+ else if (f === "--exec") a.exec = value(i++, f);
1779
+ else if (f === "--repos") a.repos = list(value(i++, f));
1780
+ else if (f === "--all-repos") a.allRepos = true;
1781
+ else if (f === "--send-questions") a.sendQuestions = list(value(i++, f));
1782
+ else if (f === "--interval") a.intervalS = Number(value(i++, f));
1783
+ else if (f === "--probe") a.probe = true;
1784
+ else if (f === "--no-sample") a.sample = false;
1785
+ else if (f === "--port") a.port = Number(value(i++, f));
1786
+ else if (f === "--mailbox") a.mailbox = value(i++, f);
1787
+ else if (f === "--config") a.config = value(i++, f);
1788
+ else if (f === "--questions") a.questionTrees = list(value(i++, f));
1789
+ else if (f === "--max-age-days") a.maxAgeDays = Number(value(i++, f));
1790
+ else throw new Error(`unknown option: ${f}`);
1791
+ }
1792
+ if (!Number.isInteger(a.port) || a.port < 1 || a.port > 65535) throw new Error("--port needs a number from 1 to 65535");
1793
+ if (!(a.maxAgeDays > 0)) throw new Error("--max-age-days needs a number above 0");
1794
+ if (!(a.intervalS >= 15)) throw new Error("--interval needs 15 seconds or more");
1795
+ if (a.watch && !a.exec) throw new Error("--watch needs --exec CMD (what should receive each report?)");
1796
+ if (a.exec && !a.watch) throw new Error("--exec goes with --watch");
1797
+ if ((a.repos || a.allRepos || a.sendQuestions) && !a.watch) throw new Error("--repos, --all-repos and --send-questions go with --watch");
1798
+ if (a.repos && a.allRepos) throw new Error("pass --repos or --all-repos, not both");
1799
+ return a;
1800
+ }
1801
+ function reportList(a, fromConfig) {
1802
+ if (a.allRepos) return null;
1803
+ const listed = a.repos ?? fromConfig ?? [];
1804
+ if (listed.length === 0) throw new Error('--watch needs to know which repositories to report: --repos name,name (or "report" in the config file), or --all-repos');
1805
+ return listed;
1806
+ }
1807
+ function buildContext(a, env, cwd, version) {
1808
+ const config = loadConfig(expandHome(a.config));
1809
+ return {
1810
+ port: a.port,
1811
+ version,
1812
+ probe: a.probe,
1813
+ sample: a.sample,
1814
+ report: a.watch ? reportList(a, config.report) : null,
1815
+ sendQuestions: a.watch ? (a.sendQuestions ?? config.sendQuestions ?? []).map((t) => path6.resolve(expandHome(t))) : [],
1816
+ deck: {
1817
+ mailbox: findMailbox({ flag: a.mailbox, config: config.mailbox, env: env.CROSSTALK_DIR, cwd }),
1818
+ names: config.names,
1819
+ // Off unless asked for: question text is a session's own words.
1820
+ questionTrees: (a.questionTrees ?? config.questions ?? []).map((t) => path6.resolve(expandHome(t))),
1821
+ maxAgeDays: a.maxAgeDays,
1822
+ cwd
1823
+ }
1824
+ };
1825
+ }
1826
+ var html = (body) => ({ status: 200, type: "text/html; charset=utf-8", body });
1827
+ var plain = (status, body) => ({ status, type: "text/plain; charset=utf-8", body });
1828
+ function hostAllowed(host, port) {
1829
+ return host === `127.0.0.1:${port}` || host === `localhost:${port}` || host === `[::1]:${port}`;
1830
+ }
1831
+ async function handle(url, host, ctx, overview2 = collectOverview) {
1832
+ if (!hostAllowed(host, ctx.port)) return plain(403, "jq-deck answers only on this machine");
1833
+ const u = new URL(url, "http://127.0.0.1");
1834
+ if (u.pathname === "/") {
1835
+ const asked = u.searchParams.get("tab");
1836
+ const tab = TABS.includes(asked ?? "") ? asked : "overview";
1837
+ return html(renderShell(await overview2(ctx.deck), tab, u.searchParams.get("repo"), ctx.version));
1838
+ }
1839
+ if (u.pathname === "/raw/sessions") {
1840
+ return html(renderPage(await snapshot({ questionTrees: ctx.deck.questionTrees, maxAgeDays: ctx.deck.maxAgeDays, projectsDir: ctx.deck.projectsDir, sockDir: ctx.deck.sockDir, probe: ctx.probe, sample: ctx.sample })));
1841
+ }
1842
+ if (u.pathname === "/raw/setup") {
1843
+ const row3 = (await overview2(ctx.deck)).repos.find((r) => r.id === u.searchParams.get("repo"));
1844
+ if (!row3 || !row3.setup) return plain(404, "no such repository on this page");
1845
+ return html(renderPage3(report(row3.tree)));
1846
+ }
1847
+ if (u.pathname === "/raw/mail") {
1848
+ if (!ctx.deck.mailbox) return plain(404, "no mailbox set");
1849
+ return html(renderPage2(buildReport(ctx.deck.mailbox)));
1850
+ }
1851
+ return plain(404, "not found");
1852
+ }
1853
+ function hand(cmd, report2) {
1854
+ return new Promise((resolve) => {
1855
+ const child = spawn(cmd, { shell: true, stdio: ["pipe", "inherit", "inherit"] });
1856
+ child.on("error", () => resolve(127));
1857
+ child.on("close", (code) => resolve(code ?? 1));
1858
+ child.stdin.on("error", () => {
1859
+ });
1860
+ child.stdin.end(JSON.stringify(report2));
1861
+ });
1862
+ }
1863
+ async function run2(argv, version) {
1864
+ const a = parseArgs(argv, process.env);
1865
+ const ctx = buildContext(a, process.env, process.cwd(), version);
1866
+ if (a.watch) {
1867
+ const tick = async () => {
1868
+ try {
1869
+ const report2 = teamReport(await collectOverview({ ...ctx.deck, questionTrees: ctx.sendQuestions }), ctx.report, ctx.sendQuestions);
1870
+ const code = await hand(a.exec, report2);
1871
+ const line = `jq-deck: ${report2.repos.length} ${report2.repos.length === 1 ? "repository" : "repositories"} reported to your command`;
1872
+ if (code === 0) console.log(line);
1873
+ else console.error(`${line}, which FAILED (exit ${code})`);
1874
+ } catch (e) {
1875
+ console.error("jq-deck: report failed:", e?.message || e);
1876
+ }
1877
+ };
1878
+ await tick();
1879
+ console.log(`jq-deck: reporting every ${a.intervalS}s (Ctrl-C to stop)`);
1880
+ console.log(ctx.sendQuestions.length ? `jq-deck: question text IS sent for sessions under: ${ctx.sendQuestions.join(", ")}` : "jq-deck: question text is not sent");
1881
+ setInterval(tick, a.intervalS * 1e3);
1882
+ return;
1883
+ }
1884
+ if (a.json) {
1885
+ console.log(JSON.stringify(await collectOverview(ctx.deck), null, 2));
1886
+ return;
1887
+ }
1888
+ createServer(async (req, res) => {
1889
+ let reply;
1890
+ try {
1891
+ reply = req.method === "GET" ? await handle(req.url || "/", req.headers.host, ctx) : plain(405, "read-only");
1892
+ } catch (e) {
1893
+ reply = plain(500, String(e?.message || e));
1894
+ }
1895
+ res.writeHead(reply.status, {
1896
+ "content-type": reply.type,
1897
+ "cache-control": "no-store",
1898
+ "x-frame-options": "SAMEORIGIN",
1899
+ "content-security-policy": "frame-ancestors 'self'"
1900
+ });
1901
+ res.end(reply.body);
1902
+ }).listen(a.port, "127.0.0.1", () => {
1903
+ console.log(`jq-deck: http://127.0.0.1:${a.port} (Ctrl-C to stop)`);
1904
+ console.log(ctx.deck.mailbox ? `jq-deck: mailbox ${ctx.deck.mailbox}` : "jq-deck: no mailbox found (pass --mailbox DIR to show mail)");
1905
+ });
1906
+ }
1907
+
1908
+ // src/main.ts
1909
+ var VERSION = true ? "0.3.1" : "dev";
1910
+ var HELP = `JQ Deck ${VERSION}: one page for your Claude Code sessions, their setup and their mail.
1911
+
1912
+ jq-deck open the page at http://127.0.0.1:${DEFAULT_PORT}
1913
+ jq-deck --json print the overview
1914
+ jq-deck --watch --exec CMD every interval, pipe a team report (JSON) to CMD:
1915
+ counts and scores per repository, no paths, no mail,
1916
+ and no question text unless you opt a folder in
1917
+ --repos NAME,NAME which repositories to report (required, or "report"
1918
+ in the config file); --all-repos reports every one
1919
+ --send-questions DIR,DIR also send what a waiting session asked, for sessions
1920
+ under these folders (default: none)
1921
+ --interval SECONDS for --watch (default 60)
1922
+ jq-deck --mailbox DIR the crosstalk mailbox to show (default: $CROSSTALK_DIR,
1923
+ or the nearest folder above you holding .crosstalk)
1924
+ jq-deck --questions DIR,DIR show the question a waiting session asked, for
1925
+ sessions under these folders (default: none)
1926
+ jq-deck --probe also time a connection to the API host
1927
+ jq-deck --no-sample skip CPU, memory and network sampling
1928
+ jq-deck --max-age-days N ignore sessions idle longer than this (default 3)
1929
+ jq-deck --config FILE default ~/.jq/config.json
1930
+ jq-deck --port NUMBER
1931
+
1932
+ It reads what jq-agents, jq-groundcrew and jq-crosstalk read, and writes nothing.
1933
+ The page is served to this machine only. Nothing leaves it unless you pass --exec
1934
+ (your command gets the report) or --probe (one timed connection).
1935
+
1936
+ Unofficial. Not affiliated with or endorsed by Anthropic.`;
1937
+ var args = process.argv.slice(2);
1938
+ if (args.includes("--help") || args.includes("-h")) console.log(HELP);
1939
+ else if (args.includes("--version") || args.includes("-v")) console.log(VERSION);
1940
+ else
1941
+ run2(args, VERSION).catch((error) => {
1942
+ console.error(error.message || error);
1943
+ process.exit(1);
1944
+ });