@point-seven-studio/jq-deck 0.3.1 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/jq-deck.mjs CHANGED
@@ -3,18 +3,295 @@
3
3
  // src/cli.ts
4
4
  import { spawn } from "child_process";
5
5
  import { createServer } from "http";
6
- import path6 from "path";
6
+
7
+ // src/presence.ts
8
+ import { existsSync, mkdirSync, readdirSync, readFileSync, unlinkSync, writeFileSync } from "fs";
9
+ import os from "os";
10
+ import path from "path";
11
+ var TOOLS = [
12
+ { id: "deck", name: "JQ Deck", what: "sessions, setup and mail on one page", port: 4316, run: "npx @point-seven-studio/jq-deck" },
13
+ { id: "agents", name: "JQ Agents", what: "every session, and which wait on a person", port: 4319, run: "npx @point-seven-studio/jq-agents" },
14
+ { id: "groundcrew", name: "JQ Groundcrew", what: "the setup check for one project", port: 4317, run: "npx @point-seven-studio/jq-groundcrew" },
15
+ { id: "crosstalk", name: "JQ Crosstalk", what: "the mailbox between sessions", port: 4318, run: "npx @point-seven-studio/jq-crosstalk view" }
16
+ ];
17
+ var esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
18
+ function runningDir(env = process.env) {
19
+ return env.JQ_RUNNING_DIR || path.join(os.homedir(), ".jq", "running");
20
+ }
21
+ var isTool = (id) => TOOLS.some((t) => t.id === id);
22
+ var validPort = (n) => typeof n === "number" && Number.isInteger(n) && n >= 1 && n <= 65535;
23
+ function alive(pid) {
24
+ try {
25
+ process.kill(pid, 0);
26
+ return true;
27
+ } catch (e) {
28
+ return e?.code === "EPERM";
29
+ }
30
+ }
31
+ function readRunning(dir = runningDir(), isAlive = alive) {
32
+ const found = { deck: null, groundcrew: null, crosstalk: null, agents: null };
33
+ if (!existsSync(dir)) return found;
34
+ let files;
35
+ try {
36
+ files = readdirSync(dir).filter((f) => f.endsWith(".json"));
37
+ } catch {
38
+ return found;
39
+ }
40
+ for (const file of files) {
41
+ try {
42
+ const entry = JSON.parse(readFileSync(path.join(dir, file), "utf-8"));
43
+ if (!isTool(entry?.tool) || !validPort(entry.port) || typeof entry.pid !== "number" || !isAlive(entry.pid)) continue;
44
+ const usual = TOOLS.find((t) => t.id === entry.tool).port;
45
+ if (found[entry.tool] === null || entry.port === usual) found[entry.tool] = entry.port;
46
+ } catch {
47
+ }
48
+ }
49
+ return found;
50
+ }
51
+ function announce(tool, port, dir = runningDir()) {
52
+ const file = path.join(dir, `${tool}.${process.pid}.json`);
53
+ let removed = false;
54
+ const remove = () => {
55
+ if (removed) return;
56
+ removed = true;
57
+ try {
58
+ unlinkSync(file);
59
+ } catch {
60
+ }
61
+ };
62
+ try {
63
+ mkdirSync(dir, { recursive: true });
64
+ for (const f of readdirSync(dir).filter((n) => n.endsWith(".json"))) {
65
+ try {
66
+ const pid = JSON.parse(readFileSync(path.join(dir, f), "utf-8"))?.pid;
67
+ if (typeof pid !== "number" || !alive(pid)) unlinkSync(path.join(dir, f));
68
+ } catch {
69
+ }
70
+ }
71
+ writeFileSync(file, JSON.stringify({ tool, port, pid: process.pid, started_at: (/* @__PURE__ */ new Date()).toISOString() }) + "\n", { mode: 384 });
72
+ } catch {
73
+ return remove;
74
+ }
75
+ process.once("exit", remove);
76
+ for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) {
77
+ process.once(signal, () => {
78
+ remove();
79
+ process.exit(signal === "SIGINT" ? 130 : 143);
80
+ });
81
+ }
82
+ return remove;
83
+ }
84
+ function readTeamUrl(file = process.env.JQ_CONFIG || path.join(os.homedir(), ".jq", "config.json")) {
85
+ try {
86
+ const team = JSON.parse(readFileSync(file, "utf-8"))?.team;
87
+ if (typeof team !== "string") return null;
88
+ const url = new URL(team);
89
+ if (url.protocol !== "https:" && url.protocol !== "http:") return null;
90
+ if (url.username || url.password) return null;
91
+ return url.href;
92
+ } catch {
93
+ return null;
94
+ }
95
+ }
96
+ var TOOLBAR_CSS = `
97
+ body{padding-bottom:64px}
98
+ .jqbar{position:fixed;left:0;right:0;bottom:0;z-index:5;display:flex;flex-wrap:wrap;align-items:center;gap:4px 14px;padding:8px 16px;font:13px/1.4 system-ui,sans-serif;background:var(--card,Canvas);color:var(--fg,CanvasText);border-top:1px solid var(--line,GrayText)}
99
+ .jqbar a{color:var(--link,LinkText)}
100
+ .jqbar .here{font-weight:700}
101
+ .jqbar details[open]{order:-1;flex-basis:100%}
102
+ .jqbar summary{cursor:pointer;color:var(--mut,GrayText);list-style:none;display:inline-block;padding:2px 0}
103
+ .jqbar summary::-webkit-details-marker{display:none}
104
+ .jqbar summary::after{content:" \u25B8"}
105
+ .jqbar details[open] summary::after{content:" \u25BE"}
106
+ .jqbar summary small,.jqbar a small{font-size:11px;font-weight:400}
107
+ .jqbar details>div{margin:4px 0 6px;padding:8px 10px;max-width:640px;border:1px solid var(--line,GrayText);border-radius:8px;background:var(--well,Canvas)}
108
+ .jqbar details>div p{margin:0 0 4px}
109
+ .jqbar code{font:12px ui-monospace,Menlo,monospace;word-break:break-all}
110
+ .jqbar a:focus-visible,.jqbar summary:focus-visible{outline:2px solid var(--link,LinkText);outline-offset:2px}
111
+ @media print{.jqbar{display:none}body{padding-bottom:0}}
112
+ `;
113
+ var local = (port) => `http://127.0.0.1:${port}`;
114
+ function toolItem(t, o) {
115
+ if (o.here === t.id) return `<span class="here" aria-current="page">${esc(t.name)}</span>`;
116
+ const start = `<p>To start it: <code>${esc(t.run)}</code></p>`;
117
+ if (o.running === null) {
118
+ return `<details><summary>${esc(t.name)} <small>on your computer</small></summary><div><p>${esc(t.name)} shows ${esc(t.what)}. It runs on your own computer, and this page cannot see whether it is running there.</p><p>If it is, it is at <a href="${local(t.port)}">${local(t.port)}</a>.</p>${start}</div></details>`;
119
+ }
120
+ const port = o.running[t.id];
121
+ if (port !== null) return `<a href="${local(port)}" title="${esc(t.what)}">${esc(t.name)}</a>`;
122
+ return `<details><summary>${esc(t.name)} <small>not running</small></summary><div><p>${esc(t.name)} shows ${esc(t.what)}. It is not running on this machine.</p>${start}<p>Then refresh this page.</p></div></details>`;
123
+ }
124
+ function teamItem(o) {
125
+ if (o.here === "team") return '<span class="here" aria-current="page">Team board</span>';
126
+ if (o.team) return `<a href="${esc(o.team)}" title="every machine on the team, on one page">Team board</a>`;
127
+ return '<details><summary>Team board <small>not set up</small></summary><div><p>A team board shows every machine on a team on one page. This machine has no address for one.</p><p>If your team has one, add a <code>"team"</code> line holding its address to <code>~/.jq/config.json</code>.</p><p>To host one: <code>npx @point-seven-studio/jq-deck-server</code></p></div></details>';
128
+ }
129
+ function toolbar(o) {
130
+ return `<nav class="jqbar" aria-label="JQ tools">${TOOLS.map((t) => toolItem(t, o)).join("")}${teamItem(o)}</nav>`;
131
+ }
132
+
133
+ // src/cli.ts
134
+ import path7 from "path";
7
135
 
8
136
  // ../agents/dist/index.mjs
9
137
  import { execFile as execFile2 } from "child_process";
10
- import { existsSync } from "fs";
138
+ import { existsSync as existsSync2 } from "fs";
11
139
  import { open, readdir, stat } from "fs/promises";
12
140
  import os2 from "os";
13
- import path from "path";
141
+ import path2 from "path";
14
142
  import { promisify as promisify2 } from "util";
15
143
  import { execFile } from "child_process";
16
144
  import { promisify } from "util";
17
- import os from "os";
145
+ import os3 from "os";
146
+ import { existsSync as existsSync22, mkdirSync as mkdirSync2, readFileSync as readFileSync2, renameSync, writeFileSync as writeFileSync2 } from "fs";
147
+ import os32 from "os";
148
+ import path22 from "path";
149
+ var EDIT_TOOLS = /* @__PURE__ */ new Set(["Edit", "Write", "MultiEdit", "NotebookEdit"]);
150
+ function looksLikeACheck(command) {
151
+ 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);
152
+ }
153
+ var CODE_FILE = /\.(ts|tsx|mts|cts|js|jsx|mjs|cjs|py|rb|go|rs|java|kt|swift|c|h|cc|cpp|hpp|cs|php|sql|sh|bash|zsh|json|ya?ml|toml|css|scss|less|html?|vue|svelte|tf|proto|gradle|xml|ini|cfg|conf|lock)$|(^|\/)(Dockerfile|Makefile|\.env[\w.]*)$/i;
154
+ var NOT_PROJECT = /^(\/tmp\/|\/private\/tmp\/|\/var\/folders\/|\/dev\/|\$)|(^|\/)\.claude\/|(^|\/)(node_modules|dist|build|out|coverage)\/|(^|\/)[._]?(tmp|temp|scratch)[\w.-]*(\/|$)|_tmp_|\.tmp\b/i;
155
+ function isCodePath(file) {
156
+ const clean = file.trim().replace(/^['"]|['"]$/g, "");
157
+ const name = clean.split("/").pop() || "";
158
+ if (/^[_.]/.test(name) && !/^\.env/.test(name)) return false;
159
+ return CODE_FILE.test(clean) && !NOT_PROJECT.test(clean);
160
+ }
161
+ function codePaths(text) {
162
+ return (text.match(/[~$\w@.{}\/-]+/g) || []).filter(isCodePath);
163
+ }
164
+ function maskQuotes(text) {
165
+ return text.replace(/'[^']*'|"(?:[^"\\]|\\.)*"/g, (quoted) => quoted[0] + "x".repeat(Math.max(0, quoted.length - 2)) + quoted[0]);
166
+ }
167
+ function splitHeredocs(command) {
168
+ const bodies = [];
169
+ const lines = command.split("\n");
170
+ const shell = [];
171
+ for (let i = 0; i < lines.length; i++) {
172
+ shell.push(lines[i]);
173
+ const tag = /<<-?\s*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\1/.exec(lines[i])?.[2];
174
+ if (!tag) continue;
175
+ const body = [];
176
+ i += 1;
177
+ while (i < lines.length && lines[i].trim() !== tag) body.push(lines[i++]);
178
+ bodies.push(body.join("\n"));
179
+ }
180
+ return { shell: shell.join("\n"), bodies };
181
+ }
182
+ function segments(shell) {
183
+ const masked = maskQuotes(shell);
184
+ const parts = [];
185
+ let from = 0;
186
+ for (const cut of [...masked.matchAll(/&&|\|\||;|\||\n/g), null]) {
187
+ const to = cut ? cut.index : masked.length;
188
+ const text = shell.slice(from, to).trim();
189
+ if (text) parts.push({ text, bare: masked.slice(from, to).trim() });
190
+ from = cut ? to + cut[0].length : to;
191
+ }
192
+ return parts;
193
+ }
194
+ function shellSegments(command) {
195
+ return segments(splitHeredocs(command).shell).map((part) => part.text);
196
+ }
197
+ var WRITES_A_FILE = /\bopen\([^)]*,\s*['"][wax]b?\+?['"]|\.write_text\(|\.write_bytes\(|\bwriteFile(Sync)?\(|\bappendFile(Sync)?\(|\bfs\.(rename|unlink|rm|cp|copyFile)(Sync)?\(|\bshutil\.(copy|move|rmtree)/;
198
+ function shellEdit(command) {
199
+ const { shell, bodies } = splitHeredocs(command);
200
+ const written = bodies.filter((body) => WRITES_A_FILE.test(body)).join("\n");
201
+ for (const { text, bare } of segments(shell)) {
202
+ const writer = /^(sudo\s+)?(sed|perl)\b.*\s-[a-zA-Z]*i/.test(bare) || /^(sudo\s+)?(mv|cp|rm|patch|tee)\s/.test(bare) || /^git\s+(apply|mv|rm)\b/.test(bare);
203
+ if (writer && codePaths(text).length) return text;
204
+ for (const hit of bare.matchAll(/(^|[^0-9&>=-])>>?\s*/g)) {
205
+ const target = /^\S+/.exec(text.slice(hit.index + hit[0].length))?.[0] ?? "";
206
+ if (isCodePath(target)) return text;
207
+ }
208
+ if (/^(python3?|node|ruby|perl|deno|bun)\b/.test(bare) && (written || WRITES_A_FILE.test(text)) && codePaths(`${written}
209
+ ${text}`).length) return text;
210
+ }
211
+ return "";
212
+ }
213
+ function ruleText(command) {
214
+ const words = (shellSegments(command)[0] || command).trim().split(/\s+/);
215
+ const kept = [];
216
+ for (const word of words.slice(0, 3)) {
217
+ if (kept.length && /[\/$<>'"=]|^\d/.test(word)) break;
218
+ kept.push(word);
219
+ }
220
+ return kept.join(" ").slice(0, 60);
221
+ }
222
+ var MAX_RULES = 200;
223
+ var MAX_TEXT = 80;
224
+ function parseConfig(raw) {
225
+ const o = raw && typeof raw === "object" ? raw : {};
226
+ const rules = (Array.isArray(o.rules) ? o.rules : []).filter((r) => !!r && typeof r === "object" && typeof r.tree === "string" && typeof r.text === "string" && (r.kind === "check" || r.kind === "not-edit")).map((r) => ({ tree: r.tree, kind: r.kind, text: r.text.trim().slice(0, MAX_TEXT) })).filter((r) => r.text.length >= 2 && r.tree).slice(0, MAX_RULES);
227
+ const muted = (Array.isArray(o.muted) ? o.muted : []).filter((t) => typeof t === "string" && !!t).slice(0, MAX_RULES);
228
+ const dismissed = {};
229
+ if (o.dismissed && typeof o.dismissed === "object") {
230
+ for (const [id, at] of Object.entries(o.dismissed).slice(0, 500)) if (typeof at === "string") dismissed[id] = at;
231
+ }
232
+ return { rules, muted, dismissed };
233
+ }
234
+ function rulesFor(config, tree) {
235
+ const mine = config.rules.filter((r) => r.tree === "*" || r.tree === tree);
236
+ return { checks: mine.filter((r) => r.kind === "check").map((r) => r.text), notEdits: mine.filter((r) => r.kind === "not-edit").map((r) => r.text) };
237
+ }
238
+ var blocks = (rec) => Array.isArray(rec.message?.content) ? rec.message.content.filter((b) => !!b && typeof b === "object") : [];
239
+ function isPrompt(rec) {
240
+ if (rec.type !== "user" || rec.isSidechain) return false;
241
+ const content = rec.message?.content;
242
+ return typeof content === "string" ? content.trim() !== "" : blocks(rec).some((b) => b.type === "text" || b.type === "image");
243
+ }
244
+ var short = (command, max = 120) => {
245
+ const one = redactSecrets(command.replace(/\s+/g, " ").trim()).text;
246
+ return one.length > max ? one.slice(0, max).trimEnd() + "\u2026" : one;
247
+ };
248
+ function deriveTurnCheckDetail(records, rules = {}) {
249
+ const extraChecks = rules.checks ?? [];
250
+ const notEdits = rules.notEdits ?? [];
251
+ const isCheck = (command) => looksLikeACheck(command) || extraChecks.some((text) => command.includes(text));
252
+ let start = -1;
253
+ for (let i = records.length - 1; i >= 0; i--) {
254
+ if (records[i] && isPrompt(records[i])) {
255
+ start = i;
256
+ break;
257
+ }
258
+ }
259
+ let step = 0;
260
+ let lastEdit = -1;
261
+ let edit = null;
262
+ const shell = [];
263
+ const errored = /* @__PURE__ */ new Set();
264
+ for (const rec of records.slice(start + 1)) {
265
+ if (!rec || rec.isSidechain) continue;
266
+ for (const block of blocks(rec)) {
267
+ step += 1;
268
+ if (block.type === "tool_result" && block.is_error === true && block.tool_use_id) errored.add(block.tool_use_id);
269
+ if (block.type !== "tool_use" || !block.name) continue;
270
+ if (EDIT_TOOLS.has(block.name)) {
271
+ const file = block.input?.file_path ?? block.input?.notebook_path;
272
+ if (typeof file === "string" && !isCodePath(file)) continue;
273
+ lastEdit = step;
274
+ edit = { via: "tool", text: block.name };
275
+ } else if (block.name === "Bash" && typeof block.input?.command === "string") {
276
+ const command = block.input.command;
277
+ const check = isCheck(command);
278
+ shell.push({ step, id: block.id, command, check });
279
+ const changed = check || rules.shellEdits === false ? "" : shellEdit(command);
280
+ if (changed && !notEdits.some((text) => changed.includes(text) || command.includes(text))) {
281
+ lastEdit = step;
282
+ edit = { via: "shell", text: changed };
283
+ }
284
+ }
285
+ }
286
+ }
287
+ if (lastEdit < 0 || !edit) return { result: start >= 0 ? "no-edits" : "unknown", via: null, evidence: null };
288
+ const after = shell.filter((c) => c.step > lastEdit);
289
+ const checks = after.filter((c) => c.check);
290
+ const last = checks[checks.length - 1];
291
+ const result = !last ? "unchecked" : last.id && errored.has(last.id) ? "failed" : "checked";
292
+ const evidence = result === "unchecked" || result === "failed" ? { via: edit.via, edit: edit.via === "shell" ? short(edit.text) : edit.text, after: [...new Set(after.filter((c) => !c.check).map((c) => short(c.command, 80)))].slice(-6) } : null;
293
+ return { result, via: edit.via, evidence };
294
+ }
18
295
  var META_RECORD_TYPES = /* @__PURE__ */ new Set([
19
296
  "last-prompt",
20
297
  "pr-link",
@@ -98,16 +375,16 @@ function lastActivityAt(records) {
98
375
  }
99
376
  return null;
100
377
  }
101
- function deriveState(alive, lastActivityIso, now) {
102
- if (!alive) return "dead";
378
+ function deriveState(alive2, lastActivityIso, now) {
379
+ if (!alive2) return "dead";
103
380
  if (!lastActivityIso) return "stale";
104
381
  const ageS = Math.max(0, (now - Date.parse(lastActivityIso)) / 1e3);
105
382
  if (ageS <= LIVE_WITHIN_S) return "live";
106
383
  if (ageS <= IDLE_WITHIN_S) return "idle";
107
384
  return "stale";
108
385
  }
109
- function deriveWaiting(rec, alive) {
110
- if (!alive || !rec || rec.type !== "assistant") return false;
386
+ function deriveWaiting(rec, alive2) {
387
+ if (!alive2 || !rec || rec.type !== "assistant") return false;
111
388
  return rec.message?.stop_reason === "end_turn";
112
389
  }
113
390
  function deriveAttention(state, waiting) {
@@ -121,7 +398,7 @@ function isTreeAllowed(workingTree, allowlist) {
121
398
  return allowlist.some((t) => t && (workingTree === t || workingTree.startsWith(t.replace(/\/+$/, "") + "/")));
122
399
  }
123
400
  function buildStatusRow(opts) {
124
- const { machine, records, sessionIdFallback, alive, pid, allowlist, now, workingTreeOverride } = opts;
401
+ const { machine, records, sessionIdFallback, alive: alive2, pid, allowlist, now, workingTreeOverride } = opts;
125
402
  const withCwd = [...records].reverse().find((r) => r?.cwd);
126
403
  const workingTree = workingTreeOverride || withCwd?.cwd || "";
127
404
  if (!workingTree) return null;
@@ -131,8 +408,8 @@ function buildStatusRow(opts) {
131
408
  const substantive = lastSubstantive(records);
132
409
  const assistant = lastAssistant(records);
133
410
  const activity = lastActivityAt(records);
134
- const state = deriveState(alive, activity, now);
135
- const waiting = deriveWaiting(substantive, alive);
411
+ const state = deriveState(alive2, activity, now);
412
+ const waiting = deriveWaiting(substantive, alive2);
136
413
  const rawText = assistant ? messageText(assistant) : "";
137
414
  const allowed = isTreeAllowed(workingTree, allowlist);
138
415
  let blocked_question = null;
@@ -142,6 +419,13 @@ function buildStatusRow(opts) {
142
419
  question_redacted = redacted;
143
420
  blocked_question = text.length > QUESTION_MAX_CHARS ? text.slice(0, QUESTION_MAX_CHARS).trimEnd() + "\u2026" : text;
144
421
  }
422
+ const saidDone = substantive?.type === "assistant" && substantive.message?.stop_reason === "end_turn";
423
+ const detail = saidDone ? deriveTurnCheckDetail(records, opts.turnCheck) : null;
424
+ let turn_check = detail?.result ?? null;
425
+ if (turn_check === "unchecked" || turn_check === "failed") {
426
+ if (opts.turnCheck?.muted || opts.turnCheck?.dismissedAt && opts.turnCheck.dismissedAt === activity) turn_check = "dismissed";
427
+ }
428
+ if (detail && opts.onTurnDetail) opts.onTurnDetail(detail);
145
429
  return {
146
430
  machine,
147
431
  product: workingTree.split("/").filter(Boolean).pop() || workingTree,
@@ -156,7 +440,9 @@ function buildStatusRow(opts) {
156
440
  ends_with_question: rawText ? endsWithQuestion(rawText) : false,
157
441
  blocked_question,
158
442
  question_redacted,
159
- question_allowed: allowed
443
+ question_allowed: allowed,
444
+ turn_check,
445
+ turn_check_via: detail?.via ?? null
160
446
  };
161
447
  }
162
448
  function parsePs(stdout) {
@@ -320,9 +606,9 @@ async function sampleHost(probe = false) {
320
606
  ]);
321
607
  const disk = parseIostat(iostat);
322
608
  return {
323
- cpuCount: os.cpus()?.length || 0,
324
- load1: parseLoadAvg(load) || os.loadavg()[0] || 0,
325
- memUsedPct: parseVmStat(vmstat, os.totalmem()),
609
+ cpuCount: os3.cpus()?.length || 0,
610
+ load1: parseLoadAvg(load) || os3.loadavg()[0] || 0,
611
+ memUsedPct: parseVmStat(vmstat, os3.totalmem()),
326
612
  swapUsedMb: parseSwapUsedMb(swap),
327
613
  diskReadMbs: disk?.readMbs ?? null,
328
614
  diskWriteMbs: disk?.writeMbs ?? null,
@@ -346,9 +632,9 @@ async function sampleProcs(pids) {
346
632
  }
347
633
  var execFileAsync2 = promisify2(execFile2);
348
634
  function defaultProjectsDir() {
349
- return path.join(process.env.CLAUDE_CONFIG_DIR || path.join(os2.homedir(), ".claude"), "projects");
635
+ return path2.join(process.env.CLAUDE_CONFIG_DIR || path2.join(os2.homedir(), ".claude"), "projects");
350
636
  }
351
- var TAIL_RECORDS = 60;
637
+ var TAIL_RECORDS = 200;
352
638
  async function findTranscripts(dir, out = []) {
353
639
  let entries;
354
640
  try {
@@ -357,7 +643,7 @@ async function findTranscripts(dir, out = []) {
357
643
  return out;
358
644
  }
359
645
  for (const e of entries) {
360
- const full = path.join(dir, e.name);
646
+ const full = path2.join(dir, e.name);
361
647
  if (e.isDirectory()) await findTranscripts(full, out);
362
648
  else if (e.isFile() && e.name.endsWith(".jsonl")) out.push(full);
363
649
  }
@@ -371,10 +657,10 @@ async function repoRoot(dir) {
371
657
  let cur = dir;
372
658
  for (let i = 0; i < 12; i++) {
373
659
  try {
374
- await stat(path.join(cur, ".git"));
660
+ await stat(path2.join(cur, ".git"));
375
661
  break;
376
662
  } catch {
377
- const parent = path.dirname(cur);
663
+ const parent = path2.dirname(cur);
378
664
  if (parent === cur) {
379
665
  cur = dir;
380
666
  break;
@@ -433,7 +719,7 @@ async function pidCwds(pids) {
433
719
  const byCwd = /* @__PURE__ */ new Map();
434
720
  if (pids.length === 0) return byCwd;
435
721
  try {
436
- const lsof = existsSync("/usr/sbin/lsof") ? "/usr/sbin/lsof" : "lsof";
722
+ const lsof = existsSync2("/usr/sbin/lsof") ? "/usr/sbin/lsof" : "lsof";
437
723
  const { stdout } = await execFileAsync2(lsof, ["-a", "-p", pids.join(","), "-d", "cwd", "-Fn"], { maxBuffer: 4 * 1024 * 1024 });
438
724
  let current = null;
439
725
  for (const line of stdout.split("\n")) {
@@ -462,17 +748,25 @@ async function collectRows(opts = {}) {
462
748
  const rawCwd = [...records].reverse().find((r) => r?.cwd)?.cwd || "";
463
749
  const tree = rawCwd ? await repoRoot(rawCwd) : "";
464
750
  const pid = tree ? cwdToPid.get(tree) ?? null : null;
751
+ const config = opts.turnCheck;
752
+ let evidence = null;
465
753
  const row3 = buildStatusRow({
754
+ turnCheck: config ? { ...rulesFor(config, tree), muted: config.muted.includes(tree), dismissedAt: config.dismissed[path2.basename(file, ".jsonl")] ?? null } : void 0,
755
+ onTurnDetail: (detail) => evidence = detail.evidence,
466
756
  machine,
467
757
  records,
468
758
  workingTreeOverride: tree || void 0,
469
- sessionIdFallback: path.basename(file, ".jsonl"),
759
+ sessionIdFallback: path2.basename(file, ".jsonl"),
470
760
  alive: pid !== null,
471
761
  pid,
472
762
  allowlist: opts.questionTrees ?? [],
473
763
  now
474
764
  });
475
- if (row3) rows.push(row3);
765
+ if (row3) {
766
+ if (config && row3.turn_check !== "dismissed" && (row3.turn_check === "unchecked" || row3.turn_check === "failed") && config.dismissed[row3.session_id] === row3.last_activity_at) row3.turn_check = "dismissed";
767
+ rows.push(row3);
768
+ if (evidence && opts.onEvidence) opts.onEvidence(row3.session_id, evidence);
769
+ }
476
770
  } catch {
477
771
  }
478
772
  }
@@ -485,7 +779,8 @@ async function collectRows(opts = {}) {
485
779
  }
486
780
  var prevNet = /* @__PURE__ */ new Map();
487
781
  async function snapshot(opts = {}) {
488
- const sessions = await collectRows(opts);
782
+ const turn_check = {};
783
+ const sessions = await collectRows(opts.evidence ? { ...opts, onEvidence: (id, e) => turn_check[id] = e } : opts);
489
784
  let host = null;
490
785
  let bottleneck = null;
491
786
  if (opts.sample !== false) {
@@ -516,9 +811,28 @@ async function snapshot(opts = {}) {
516
811
  bottleneck = null;
517
812
  }
518
813
  }
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]);
814
+ const snap = { machine: opts.machine ?? os2.hostname(), generated_at: new Date(opts.now ?? Date.now()).toISOString(), sessions, host, bottleneck };
815
+ if (opts.evidence) snap.local = { turn_check };
816
+ return snap;
817
+ }
818
+ var TOOLBAR_CSS2 = `
819
+ body{padding-bottom:64px}
820
+ .jqbar{position:fixed;left:0;right:0;bottom:0;z-index:5;display:flex;flex-wrap:wrap;align-items:center;gap:4px 14px;padding:8px 16px;font:13px/1.4 system-ui,sans-serif;background:var(--card,Canvas);color:var(--fg,CanvasText);border-top:1px solid var(--line,GrayText)}
821
+ .jqbar a{color:var(--link,LinkText)}
822
+ .jqbar .here{font-weight:700}
823
+ .jqbar details[open]{order:-1;flex-basis:100%}
824
+ .jqbar summary{cursor:pointer;color:var(--mut,GrayText);list-style:none;display:inline-block;padding:2px 0}
825
+ .jqbar summary::-webkit-details-marker{display:none}
826
+ .jqbar summary::after{content:" \u25B8"}
827
+ .jqbar details[open] summary::after{content:" \u25BE"}
828
+ .jqbar summary small,.jqbar a small{font-size:11px;font-weight:400}
829
+ .jqbar details>div{margin:4px 0 6px;padding:8px 10px;max-width:640px;border:1px solid var(--line,GrayText);border-radius:8px;background:var(--well,Canvas)}
830
+ .jqbar details>div p{margin:0 0 4px}
831
+ .jqbar code{font:12px ui-monospace,Menlo,monospace;word-break:break-all}
832
+ .jqbar a:focus-visible,.jqbar summary:focus-visible{outline:2px solid var(--link,LinkText);outline-offset:2px}
833
+ @media print{.jqbar{display:none}body{padding-bottom:0}}
834
+ `;
835
+ var esc2 = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
522
836
  function ago(iso, now) {
523
837
  if (!iso) return "unknown";
524
838
  const s = Math.max(0, Math.floor((now - Date.parse(iso)) / 1e3));
@@ -550,18 +864,44 @@ function groupByTree(rows) {
550
864
  rows: list2.sort((a, b) => (b.last_activity_at || "").localeCompare(a.last_activity_at || ""))
551
865
  })).sort((a, b) => Number(needs(b.rows)) - Number(needs(a.rows)) || latest(b.rows).localeCompare(latest(a.rows)));
552
866
  }
553
- function sessionRow(r, now) {
867
+ var hidden = (fields) => Object.entries(fields).map(([name, value]) => `<input type="hidden" name="${name}" value="${esc2(value)}">`).join("");
868
+ var form = (m, fields, label) => `<form method="post" action="/turn-check">${hidden({ token: m.token, ...fields })}<button type="submit">${esc2(label)}</button></form>`;
869
+ function whyPanel(r, evidence, m) {
870
+ const how = evidence.via === "shell" ? `<code>${esc2(evidence.edit)}</code>, a shell command` : `the ${esc2(evidence.edit)} tool`;
871
+ const verdict = r.turn_check === "failed" ? "The last check after it failed." : "No check ran after it.";
872
+ const after = evidence.after.length ? `<p>It ran these afterwards. If one of them is how this project checks its work, say so:</p><ul class="cmds">${evidence.after.map((command) => {
873
+ const text = ruleText(command);
874
+ return `<li><code>${esc2(command)}</code>${text.length >= 2 ? form(m, { action: "add-rule", kind: "check", tree: r.working_tree, text }, `Count "${text}" as a check here`) : ""}</li>`;
875
+ }).join("")}</ul>` : "";
876
+ const notEdit = evidence.via === "shell" && ruleText(evidence.edit).length >= 2 ? form(m, { action: "add-rule", kind: "not-edit", tree: r.working_tree, text: ruleText(evidence.edit) }, `"${ruleText(evidence.edit)}" does not edit code here`) : "";
877
+ return `<details class="why"><summary>Why, and is it wrong?</summary><p>The last edit was ${how}. ${verdict}</p>${after}<div class="acts">${notEdit}` + form(m, { action: "dismiss", session: r.session_id }, "Dismiss this one") + form(m, { action: "mute", tree: r.working_tree }, "Never label this tree") + "</div></details>";
878
+ }
879
+ function sessionRow(r, now, evidence, manage) {
554
880
  const attention = deriveAttention(r.state, r.waiting);
555
881
  const badge = attention === "needs-you" ? '<span class="b need">waiting on a person</span>' : attention === "abandoned" ? '<span class="b old">asked, then left</span>' : "";
882
+ const check = r.turn_check === "unchecked" ? '<span class="b need">stopped without running a check</span>' : r.turn_check === "failed" ? '<span class="b bad">stopped after a failed check</span>' : "";
556
883
  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>`;
884
+ const question = r.blocked_question ? `<pre>${esc2(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>' : "";
885
+ const why = check && evidence && manage ? whyPanel(r, evidence, manage) : "";
886
+ return `<li><span class="s ${r.state}">${r.state}</span> <span class="mut">${esc2(r.branch || "no branch")} \xB7 active ${ago(r.last_activity_at, now)} ago</span> ${[badge, check].filter(Boolean).join('<span class="mut"> \xB7 </span>')} ${res}${question}${why}</li>`;
887
+ }
888
+ function correctionsPanel(snap, m) {
889
+ const { rules, muted, dismissed } = m.config;
890
+ const items = [
891
+ ...rules.map((rule, index) => `<li><span>${rule.kind === "check" ? "Counts as a check" : "Does not edit code"}: <code>${esc2(rule.text)}</code> <span class="mut">in ${esc2(rule.tree === "*" ? "every tree" : rule.tree)}</span></span>${form(m, { action: "remove-rule", index: String(index) }, "Remove")}</li>`),
892
+ ...muted.map((tree) => `<li><span>Never labelled: <span class="mut">${esc2(tree)}</span></span>${form(m, { action: "unmute", tree }, "Label it again")}</li>`),
893
+ ...Object.keys(dismissed).map((session) => {
894
+ const row3 = snap.sessions.find((r) => r.session_id === session);
895
+ return `<li><span>Dismissed: <span class="mut">${esc2(row3 ? `${row3.product} \xB7 ${row3.branch || "no branch"}` : `session ${session.slice(0, 8)}`)}</span></span>${form(m, { action: "undismiss", session }, "Undo")}</li>`;
896
+ })
897
+ ];
898
+ return '<section class="card fix"><h2>Your corrections to the check label</h2>' + (items.length ? `<ul>${items.join("")}</ul>` : '<p class="mut pad">None yet. A label you think is wrong has a "Why, and is it wrong?" link under it.</p>') + '<p class="mut pad">Saved in <code>~/.jq/config.json</code> on this machine. Apart from its own running note in <code>~/.jq/running/</code>, this is the only file JQ Agents writes.</p></section>';
559
899
  }
560
- function renderPage(snap, now = Date.now()) {
900
+ function renderPage(snap, now = Date.now(), manage, bar = "") {
561
901
  const t = totals(snap.sessions);
562
902
  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("");
903
+ 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: ${esc2(b.kind)}${b.reason ? ` (${esc2(b.reason)})` : ""}`}</p>`;
904
+ const trees = groupByTree(snap.sessions).map((g) => `<section class="card"><h2>${esc2(g.product)} <span class="mut">${esc2(g.tree)}</span></h2><ul>${g.rows.map((r) => sessionRow(r, now, snap.local?.turn_check[r.session_id], manage)).join("")}</ul></section>`).join("");
565
905
  return `<!doctype html>
566
906
  <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
567
907
  <title>JQ Agents</title>
@@ -576,21 +916,45 @@ h1{font-size:24px;margin:0}h2{font-size:15px;margin:0;padding:10px 12px;word-bre
576
916
  .card{background:var(--card);border:1px solid var(--line);border-radius:12px;margin:10px 0;overflow:hidden}
577
917
  ul{list-style:none;margin:0;padding:0}li{border-top:1px solid var(--line);padding:8px 12px}
578
918
  .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)}
919
+ .b{font-size:12px;font-weight:600}.b.need{color:var(--need)}.b.old{color:var(--mut)}.b.bad{color:var(--bad)}
580
920
  .chip{border:1px solid var(--line);border-radius:8px;padding:6px 10px;font-size:13px}
921
+ .why{margin:6px 0 2px;font-size:13px}.why summary{cursor:pointer;color:var(--mut);font-size:12px}.why p{margin:6px 0}
922
+ code{font:12px ui-monospace,Menlo,monospace;background:var(--well);border-radius:4px;padding:1px 4px;word-break:break-all}
923
+ .cmds{border:1px solid var(--line);border-radius:8px}.cmds li,.fix li{display:flex;flex-wrap:wrap;gap:6px 10px;align-items:center;justify-content:space-between}
924
+ .acts{display:flex;flex-wrap:wrap;gap:6px;margin-top:8px}form{margin:0}
925
+ button{font:600 12px system-ui,sans-serif;color:var(--fg);background:var(--card);border:1px solid var(--line);border-radius:6px;padding:5px 10px;min-height:30px;cursor:pointer}
926
+ button:hover{border-color:var(--mut)}button:focus-visible{outline:2px solid var(--fg);outline-offset:2px}.pad{margin:0;padding:8px 12px}
581
927
  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>
928
+ ${bar ? TOOLBAR_CSS2 : ""}</style></head><body><main>
583
929
  <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>
930
+ <p class="mut">${esc2(snap.machine)} \xB7 read ${esc2(snap.generated_at)}. Refresh to read again. Read-only: answer a session where it is running.</p>
585
931
  <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
932
  ${chip}
587
933
  ${trees || '<p class="mut">No session has been active in the window read.</p>'}
588
- </main></body></html>`;
934
+ ${manage ? correctionsPanel(snap, manage) : ""}
935
+ </main>${bar}</body></html>`;
936
+ }
937
+ function defaultConfigFile() {
938
+ return process.env.JQ_CONFIG || path22.join(os32.homedir(), ".jq", "config.json");
939
+ }
940
+ function readAll(file) {
941
+ if (!existsSync22(file)) return {};
942
+ const parsed = JSON.parse(readFileSync2(file, "utf-8"));
943
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error(`${file} does not hold a JSON object`);
944
+ return parsed;
945
+ }
946
+ function readTurnCheckConfig(file = defaultConfigFile()) {
947
+ try {
948
+ return parseConfig(readAll(file).turnCheck);
949
+ } catch {
950
+ return parseConfig(null);
951
+ }
589
952
  }
590
953
 
591
954
  // ../crosstalk/dist/index.mjs
592
- import { existsSync as existsSync2, readdirSync, readFileSync, statSync } from "fs";
593
- import path2 from "path";
955
+ import { existsSync as existsSync3, readdirSync as readdirSync2, readFileSync as readFileSync3, statSync } from "fs";
956
+ import path3 from "path";
957
+ import { createHash, createPrivateKey, createPublicKey, generateKeyPairSync, sign, verify } from "crypto";
594
958
  var BOARD = "board";
595
959
  var DAY_MS = 864e5;
596
960
  function ageDays(sentAt, now) {
@@ -609,7 +973,9 @@ function summarize(m, now) {
609
973
  sent_at: m.sent_at,
610
974
  acked: m.acked,
611
975
  age_days: ageDays(m.sent_at, now),
612
- kind: m.kind ?? null
976
+ kind: m.kind ?? null,
977
+ author: m.author ?? null,
978
+ signature_state: m.signature_state ?? null
613
979
  };
614
980
  }
615
981
  var plural = (n, one, many) => n === 1 ? one : many;
@@ -778,6 +1144,7 @@ function parseMessage(filename, raw, recipient, acked) {
778
1144
  let kind = null;
779
1145
  let thread = null;
780
1146
  let replyTo = null;
1147
+ let author = null;
781
1148
  let from = "";
782
1149
  let subject = null;
783
1150
  let sent = null;
@@ -800,6 +1167,7 @@ function parseMessage(filename, raw, recipient, acked) {
800
1167
  } else if (m[1] === "expires") expires = /^\d{4}-\d{2}-\d{2}$/.test(m[2].trim()) ? m[2].trim() : null;
801
1168
  else if (m[1] === "evidence") evidence = m[2].trim() || null;
802
1169
  else if (m[1] === "settled_by") settledBy = m[2].trim() || null;
1170
+ else if (m[1] === "author") author = m[2].trim() || null;
803
1171
  }
804
1172
  }
805
1173
  if (!from) from = "unknown";
@@ -818,30 +1186,106 @@ function parseMessage(filename, raw, recipient, acked) {
818
1186
  tags,
819
1187
  expires_on: expires,
820
1188
  evidence: evidence && ["verified", "assumed"].includes(evidence) ? evidence : null,
821
- settled_by: settledBy && SETTLED_BY.includes(settledBy) ? settledBy : null
1189
+ settled_by: settledBy && SETTLED_BY.includes(settledBy) ? settledBy : null,
1190
+ author
822
1191
  };
823
1192
  }
1193
+ var VERSION = "jq-crosstalk-signed-v1";
1194
+ function signingPayload(f) {
1195
+ return Buffer.from(
1196
+ JSON.stringify([VERSION, f.filename, f.from, f.to, f.subject, f.sent, f.kind, f.thread, f.reply_to, f.author, f.body.trim()]),
1197
+ "utf8"
1198
+ );
1199
+ }
1200
+ function fingerprint(publicKey) {
1201
+ return createHash("sha256").update(Buffer.from(publicKey, "base64")).digest("hex").slice(0, 16);
1202
+ }
1203
+ function parseSigners(text) {
1204
+ const signers = /* @__PURE__ */ new Map();
1205
+ for (const line of text.split("\n")) {
1206
+ const m = line.match(/^([a-z0-9][a-z0-9-]*):\s*([A-Za-z0-9+/=]+)\s*$/);
1207
+ if (m) signers.set(m[1], m[2]);
1208
+ }
1209
+ return signers;
1210
+ }
1211
+ function splitMessage(filename, raw) {
1212
+ const fields = { filename, from: "", to: "", subject: "", sent: "", kind: "", thread: "", reply_to: "", author: "", body: raw };
1213
+ let signature = "";
1214
+ const fm = raw.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
1215
+ if (!fm) return { fields, signature };
1216
+ fields.body = fm[2];
1217
+ for (const line of fm[1].split("\n")) {
1218
+ const m = line.match(/^(\w+):\s*(.*)$/);
1219
+ if (!m) continue;
1220
+ const value = m[2].trim();
1221
+ if (m[1] === "signature") signature = value;
1222
+ else if (m[1] === "from" || m[1] === "to" || m[1] === "subject" || m[1] === "sent" || m[1] === "kind" || m[1] === "thread" || m[1] === "reply_to" || m[1] === "author") {
1223
+ fields[m[1]] = value;
1224
+ }
1225
+ }
1226
+ return { fields, signature };
1227
+ }
1228
+ function checkSignature(filename, raw, signers) {
1229
+ const { fields, signature } = splitMessage(filename, raw);
1230
+ const publicKey = signers.get(fields.from);
1231
+ const base = { from: fields.from, author: fields.author };
1232
+ if (!publicKey) return { ...base, state: signature ? "unknown-signer" : "not-required", key: "" };
1233
+ const key = fingerprint(publicKey);
1234
+ if (!signature) return { ...base, state: "unsigned", key };
1235
+ try {
1236
+ const ok = verify(
1237
+ null,
1238
+ signingPayload(fields),
1239
+ createPublicKey({ key: Buffer.from(publicKey, "base64"), format: "der", type: "spki" }),
1240
+ Buffer.from(signature, "base64")
1241
+ );
1242
+ return { ...base, state: ok ? "verified" : "failed", key };
1243
+ } catch {
1244
+ return { ...base, state: "failed", key };
1245
+ }
1246
+ }
824
1247
  function names(dir) {
825
- if (!existsSync2(dir)) return [];
826
- return readdirSync(dir).filter((n) => statSync(path2.join(dir, n)).isDirectory());
1248
+ if (!existsSync3(dir)) return [];
1249
+ return readdirSync2(dir).filter((n) => statSync(path3.join(dir, n)).isDirectory());
827
1250
  }
828
1251
  function readMailbox(root) {
829
- if (!existsSync2(path2.join(root, "inbox"))) throw new Error(`not a crosstalk mailbox (no inbox/ folder): ${root}`);
1252
+ if (!existsSync3(path3.join(root, "inbox"))) throw new Error(`not a crosstalk mailbox (no inbox/ folder): ${root}`);
1253
+ const signersFile = path3.join(root, "registry", "signers.txt");
1254
+ const signers = existsSync3(signersFile) ? parseSigners(readFileSync3(signersFile, "utf8")) : /* @__PURE__ */ new Map();
830
1255
  const byKey = /* @__PURE__ */ new Map();
831
1256
  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);
1257
+ for (const name of names(path3.join(root, base))) {
1258
+ const dir = path3.join(root, base, name);
1259
+ for (const file of readdirSync2(dir).filter((f) => f.endsWith(".md"))) {
1260
+ const raw = readFileSync3(path3.join(dir, file), "utf8");
1261
+ const row22 = parseMessage(file, raw, name, acked);
1262
+ const state = checkSignature(file, raw, signers).state;
836
1263
  const key = `${name}/${file}`;
837
1264
  const prev = byKey.get(key);
838
- if (!prev || acked && !prev.acked) byKey.set(key, { id: key, ...row22 });
1265
+ if (!prev || acked && !prev.acked) byKey.set(key, { id: key, ...row22, signature_state: state === "not-required" ? null : state });
839
1266
  }
840
1267
  }
841
1268
  }
842
1269
  return [...byKey.values()].sort((a, b) => a.id.localeCompare(b.id));
843
1270
  }
844
- var esc2 = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
1271
+ var TOOLBAR_CSS3 = `
1272
+ body{padding-bottom:64px}
1273
+ .jqbar{position:fixed;left:0;right:0;bottom:0;z-index:5;display:flex;flex-wrap:wrap;align-items:center;gap:4px 14px;padding:8px 16px;font:13px/1.4 system-ui,sans-serif;background:var(--card,Canvas);color:var(--fg,CanvasText);border-top:1px solid var(--line,GrayText)}
1274
+ .jqbar a{color:var(--link,LinkText)}
1275
+ .jqbar .here{font-weight:700}
1276
+ .jqbar details[open]{order:-1;flex-basis:100%}
1277
+ .jqbar summary{cursor:pointer;color:var(--mut,GrayText);list-style:none;display:inline-block;padding:2px 0}
1278
+ .jqbar summary::-webkit-details-marker{display:none}
1279
+ .jqbar summary::after{content:" \u25B8"}
1280
+ .jqbar details[open] summary::after{content:" \u25BE"}
1281
+ .jqbar summary small,.jqbar a small{font-size:11px;font-weight:400}
1282
+ .jqbar details>div{margin:4px 0 6px;padding:8px 10px;max-width:640px;border:1px solid var(--line,GrayText);border-radius:8px;background:var(--well,Canvas)}
1283
+ .jqbar details>div p{margin:0 0 4px}
1284
+ .jqbar code{font:12px ui-monospace,Menlo,monospace;word-break:break-all}
1285
+ .jqbar a:focus-visible,.jqbar summary:focus-visible{outline:2px solid var(--link,LinkText);outline-offset:2px}
1286
+ @media print{.jqbar{display:none}body{padding-bottom:0}}
1287
+ `;
1288
+ var esc3 = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
845
1289
  var age = (d) => d === null ? "no date" : d === 0 ? "today" : d === 1 ? "1 day" : `${d} days`;
846
1290
  var SETTLED = {
847
1291
  source: "settled by checking the source",
@@ -851,21 +1295,23 @@ var SETTLED = {
851
1295
  nobody: "no one answered"
852
1296
  };
853
1297
  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>`;
1298
+ const kind = m.kind && m.kind !== "brief" ? `<span class="kind">${esc3(m.kind)}</span> ` : "";
1299
+ const to = showTo ? ` <span class="mut">to</span> <span class="chip">${esc3(m.to_session)}</span>` : "";
1300
+ const who = m.author ? ` <span class="mut">${esc3(m.author)}</span>` : "";
1301
+ const signed = m.signature_state === "verified" ? ' <span class="kind">signed</span>' : m.signature_state ? ` <span class="kind">${m.signature_state === "unknown-signer" ? "signature not checked" : "NOT VERIFIED"}</span>` : "";
1302
+ return `<details><summary><span class="chip">${esc3(m.from_session)}</span>${who}${signed}${to} ${kind}<span class="subj">${esc3(m.subject || "(no subject)")}</span> <span class="note">${esc3(note)}</span></summary><p class="file">${esc3(m.filename)}</p><pre>${esc3(bodies[m.id] ?? "")}</pre></details>`;
857
1303
  }
858
1304
  function post(p, bodies) {
859
1305
  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
1306
  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>`;
1307
+ return `<section class="card"><h3>${esc3(p.title || "(no title)")} ${p.tags.map((t) => `<span class="tag">${esc3(t)}</span>`).join(" ")} <span class="state ${p.state}">${esc3(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
1308
  }
863
- function renderPage2(r) {
1309
+ function renderPage2(r, bar = "") {
864
1310
  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>`
1311
+ (i) => `<section class="card"><h3>${esc3(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
1312
  ).join("");
867
1313
  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>`
1314
+ (t) => `<section class="card"><h3>${esc3(t.subject || "(no subject)")} <span class="note">${t.count} ${t.count === 1 ? "message" : "messages"}${t.unread ? `, ${t.unread} unread` : ""} \xB7 ${t.participants.map(esc3).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
1315
  ).join("");
870
1316
  return `<!doctype html>
871
1317
  <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
@@ -883,14 +1329,14 @@ details{border-top:1px solid var(--line)}summary{cursor:pointer;padding:8px 12px
883
1329
  .subj{font-weight:500}.file{font-family:ui-monospace,monospace;margin:0;padding:0 12px;word-break:break-all}
884
1330
  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
1331
  .state{font-size:12px}.state.open{color:var(--ok)}.state.expired{color:var(--bad)}.state.closed{color:var(--mut)}
886
- </style></head><body><main>
1332
+ ${bar ? TOOLBAR_CSS3 : ""}</style></head><body><main>
887
1333
  <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("")}
1334
+ <p class="note">${esc3(r.mailbox)} \xB7 ${r.total} messages \xB7 read ${esc3(r.generated_at)}. Refresh to read again. This page is read-only.</p>
1335
+ <h2>Waiting</h2><p class="lead">${esc3(r.waiting.headline)}</p>${waiting}
1336
+ <h2>Board</h2><p class="lead">${esc3(r.board.headline)}</p>${r.board.open.map((p) => post(p, r.bodies)).join("")}
891
1337
  ${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
1338
  <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>`;
1339
+ </main>${bar}</body></html>`;
894
1340
  }
895
1341
  var THREADS_SHOWN = 60;
896
1342
  function buildReport(root, now = Date.now()) {
@@ -912,9 +1358,9 @@ function buildReport(root, now = Date.now()) {
912
1358
  }
913
1359
 
914
1360
  // ../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";
1361
+ import { existsSync as existsSync4, readFileSync as readFileSync4, readdirSync as readdirSync3, statSync as statSync2 } from "fs";
1362
+ import os4 from "os";
1363
+ import path4 from "path";
918
1364
  var DOCS = "https://code.claude.com/docs/en";
919
1365
  var MEMORY_LINE_TARGET = 200;
920
1366
  var MEMORY_LINE_FAIL = 400;
@@ -926,6 +1372,136 @@ function deniesSecrets(rule) {
926
1372
  function allowsEveryCommand(rule) {
927
1373
  return /^Bash(\(\s*(\*|:\*|\*\*)?\s*\))?$/.test(rule.trim());
928
1374
  }
1375
+ var COMMAND_HEADS = new Set(
1376
+ "git gh npm npx pnpm yarn bun node deno python python3 pip pip3 uv poetry cargo go make docker kubectl helm terraform aws gcloud az psql mysql sqlite3 redis-cli curl wget ssh scp rsync rm mv cp chmod chown sudo kill pkill brew apt railway vercel netlify fly heroku firebase wrangler tsc eslint ruff prettier dprint jest vitest pytest nx turbo gradle mvn dotnet rails rake bundle composer php launchctl systemctl".split(" ")
1377
+ );
1378
+ var NEVER_WORDS = /\b(never|do not|don['’]t|must not|mustn['’]t|not allowed|forbidden|prohibited)\b/i;
1379
+ var ASK_WORDS = /\bask\b[^.]{0,40}\b(first|before)\b|\bgo-ahead\b|\bwithout (asking|approval|permission|confirmation)\b|\b(needs?|requires?|get|wait for) [^.]{0,30}\b(approval|confirmation|sign-off|say-so)\b|\bconfirm (first|before)\b/i;
1380
+ var BARE_COMMANDS = /\b(git (?:push|reset --hard|reset|rebase|merge|commit|clean|stash)|gh (?:pr|issue|release|repo) [a-z]+|npm publish|rm -rf)\b/g;
1381
+ var restrictionKind = (text) => ASK_WORDS.test(text) ? "ask" : NEVER_WORDS.test(text) ? "never" : null;
1382
+ function commandStart(span) {
1383
+ const words = span.trim().replace(/^\$\s+/, "").split(/\s+/);
1384
+ if (!COMMAND_HEADS.has(words[0])) return "";
1385
+ const kept = [words[0]];
1386
+ for (const word of words.slice(1, 3)) {
1387
+ if (!/^(--?[a-z][a-z-]*|[a-z0-9][a-z0-9:_-]*)$/i.test(word)) break;
1388
+ kept.push(word);
1389
+ }
1390
+ return kept.join(" ");
1391
+ }
1392
+ function findRestrictedCommands(text, file) {
1393
+ const found = [];
1394
+ const seen = /* @__PURE__ */ new Set();
1395
+ const add = (kind, command, line) => {
1396
+ if (!command || seen.has(command)) return;
1397
+ seen.add(command);
1398
+ found.push({ file, line, kind, command });
1399
+ };
1400
+ const commandsIn = (part) => {
1401
+ const spans = [...part.matchAll(/`([^`]+)`/g)].flatMap((m) => m[1].split("/").map(commandStart));
1402
+ const bare = [...part.replace(/`[^`]*`/g, " ").matchAll(BARE_COMMANDS)].map((m) => m[1]);
1403
+ return [...spans, ...bare].filter(Boolean);
1404
+ };
1405
+ const readBlock = (block2, line, inherited) => {
1406
+ let matched = false;
1407
+ for (const sentence of block2.split(/(?<=[.!?:])\s+|\s[—–]\s|;\s/)) {
1408
+ const kind = restrictionKind(sentence);
1409
+ if (!kind) continue;
1410
+ matched = true;
1411
+ const at = sentence.search(kind === "ask" ? ASK_WORDS : NEVER_WORDS);
1412
+ for (const command of commandsIn(kind === "ask" ? sentence : sentence.slice(at))) add(kind, command, line);
1413
+ }
1414
+ if (!matched && inherited) for (const command of commandsIn(block2)) add(inherited, command, line);
1415
+ };
1416
+ let headingKind = null;
1417
+ let block = "";
1418
+ let blockLine = 0;
1419
+ let blockIsItem = false;
1420
+ let fenced = false;
1421
+ const flush = () => {
1422
+ if (block) readBlock(block, blockLine, blockIsItem ? headingKind : null);
1423
+ block = "";
1424
+ };
1425
+ text.split("\n").forEach((raw, index) => {
1426
+ if (/^\s*(```|~~~)/.test(raw)) {
1427
+ flush();
1428
+ fenced = !fenced;
1429
+ return;
1430
+ }
1431
+ if (fenced) return;
1432
+ if (/^#{1,6}\s/.test(raw)) {
1433
+ flush();
1434
+ headingKind = restrictionKind(raw);
1435
+ return;
1436
+ }
1437
+ if (!raw.trim()) return flush();
1438
+ const startsItem = /^\s*([-*+]|\d+[.)])\s/.test(raw) || /^\s*\|/.test(raw);
1439
+ if (startsItem) flush();
1440
+ if (!block) {
1441
+ blockLine = index + 1;
1442
+ blockIsItem = startsItem;
1443
+ }
1444
+ block += (block ? " " : "") + raw.trim();
1445
+ });
1446
+ flush();
1447
+ return found;
1448
+ }
1449
+ function ruleCovers(rule, command) {
1450
+ const trimmed = rule.trim();
1451
+ if (allowsEveryCommand(trimmed)) return true;
1452
+ const inner = /^Bash\((.*)\)$/.exec(trimmed)?.[1];
1453
+ if (inner === void 0) return false;
1454
+ const pattern = inner.replace(/:\*$/, " *").trim();
1455
+ const regex = new RegExp("^" + pattern.split("*").map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*") + "$");
1456
+ return regex.test(command) || regex.test(`${command} x`);
1457
+ }
1458
+ var NO_PROMPT_MODES = /* @__PURE__ */ new Set(["bypassPermissions", "auto"]);
1459
+ function proseFindings(facts) {
1460
+ const files = facts.settings;
1461
+ const covers = (rules, command) => rules.some((rule) => ruleCovers(rule, command));
1462
+ const [deny, ask, allow] = [all(files, (f) => f.deny), all(files, (f) => f.ask), all(files, (f) => f.allow)];
1463
+ const noPrompt = files.some((f) => f.defaultMode !== null && NO_PROMPT_MODES.has(f.defaultMode));
1464
+ return (facts.restricted ?? []).map((r) => {
1465
+ const enforced = covers(deny, r.command) || r.kind === "ask" && covers(ask, r.command);
1466
+ const state = enforced ? "enforced" : covers(allow, r.command) || noPrompt ? "allowed" : r.kind === "ask" ? "prompt" : "open";
1467
+ return { ...r, state };
1468
+ });
1469
+ }
1470
+ var nameFinding = (f) => `"${f.command}" (${f.kind === "ask" ? "ask first" : "never"}, ${f.file} line ${f.line})`;
1471
+ var listFindings = (findings, limit = 4) => findings.slice(0, limit).map(nameFinding).join("; ") + (findings.length > limit ? `; and ${findings.length - limit} more` : "");
1472
+ function proseChecks(facts) {
1473
+ const source = `${DOCS}/permissions.md`;
1474
+ const base = { id: "prose-rules", group: "guardrails", title: "Rules in the instructions have a permission rule behind them", source };
1475
+ const findings = proseFindings(facts);
1476
+ if (!findings.length) {
1477
+ return [
1478
+ {
1479
+ ...base,
1480
+ status: "info",
1481
+ detail: 'No instruction file names a command to never run, or to ask about first. Only a command written out, such as "git push", is found.',
1482
+ fix: ""
1483
+ }
1484
+ ];
1485
+ }
1486
+ const allowed = findings.filter((f) => f.state === "allowed");
1487
+ const open2 = findings.filter((f) => f.state === "open");
1488
+ const prompt = findings.filter((f) => f.state === "prompt");
1489
+ const enforced = findings.filter((f) => f.state === "enforced");
1490
+ const parts = [];
1491
+ if (allowed.length) parts.push(`The instructions restrict ${plural2(allowed.length, "command")} that an allow rule or the permission mode lets run without asking: ${listFindings(allowed)}.`);
1492
+ if (open2.length) parts.push(`${plural2(open2.length, "command")} the instructions say never to run ${open2.length === 1 ? "has" : "have"} no deny rule: ${listFindings(open2)}.`);
1493
+ if (prompt.length) parts.push(`${plural2(prompt.length, "ask-first command")} ${prompt.length === 1 ? "is" : "are"} held only by the default prompt, which one "don't ask again" removes: ${listFindings(prompt, 3)}.`);
1494
+ if (enforced.length) parts.push(`${plural2(enforced.length, "restricted command")} ${enforced.length === 1 ? "has" : "have"} a rule behind ${enforced.length === 1 ? "it" : "them"}.`);
1495
+ const needsLook = allowed.length > 0 || open2.length > 0;
1496
+ return [
1497
+ {
1498
+ ...base,
1499
+ status: needsLook ? "warn" : "pass",
1500
+ detail: parts.join(" ") + (needsLook ? " This check reads words, so confirm each line means what it found." : ""),
1501
+ fix: needsLook ? `The docs say "Permission rules are enforced by Claude Code, not by the model", and that instructions "shape what Claude tries to do, but they don't change these rules". Add a deny rule for a command the instructions forbid and an ask rule for one they say to ask about, and remove an allow rule that contradicts them.` : ""
1502
+ }
1503
+ ];
1504
+ }
929
1505
  function memoryChecks(facts) {
930
1506
  const source = `${DOCS}/memory.md`;
931
1507
  if (!facts.memory.length) {
@@ -1104,13 +1680,13 @@ function guardrailChecks(facts) {
1104
1680
  }
1105
1681
  return checks;
1106
1682
  }
1107
- function looksLikeACheck(command) {
1683
+ function looksLikeACheck2(command) {
1108
1684
  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
1685
  }
1110
1686
  function verificationChecks(facts) {
1111
1687
  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)));
1688
+ const allowed = all(files, (f) => f.allow.filter((rule) => /^Bash\(/.test(rule) && looksLikeACheck2(rule)));
1689
+ const hooked = all(files, (f) => f.hookCommands.filter((h) => looksLikeACheck2(h.command)));
1114
1690
  const stopEvents = [...new Set(all(files, (f) => f.hookEvents.filter((event) => event === "Stop" || event === "SubagentStop")))].sort();
1115
1691
  const unscoped = facts.subagentFiles.filter((agent) => !agent.limitsTools).map((agent) => agent.name);
1116
1692
  const checks = [
@@ -1176,6 +1752,10 @@ function promptFor(check, facts) {
1176
1752
  const rules = facts.secretFiles.length ? facts.secretFiles.map((file) => `Read(./${file})`).join(", ") : "Read(./.env), Read(./secrets/**)";
1177
1753
  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
1754
  }
1755
+ case "prose-rules": {
1756
+ const findings = proseFindings(facts).filter((f) => f.state === "allowed" || f.state === "open");
1757
+ return `My instruction files restrict these commands, and no permission rule enforces it: ${findings.map(nameFinding).join("; ")}. First read each line and tell me if it really restricts that command. For each one that does, propose a rule for the permissions in .claude/settings.json: a deny rule where the instructions say never, an ask rule where they say to ask first. If an allow rule in any settings file approves one of these commands, show me that rule and say whether to remove it. Keep every other rule. Show me the diff before you save it, and tell me how to confirm afterwards that each rule works.`;
1758
+ }
1179
1759
  case "broad-allow":
1180
1760
  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
1761
  case "sandbox":
@@ -1190,9 +1770,80 @@ function promptFor(check, facts) {
1190
1770
  return "";
1191
1771
  }
1192
1772
  }
1773
+ var LAYER_OF = {
1774
+ "memory-exists": "guides",
1775
+ "memory-length": "guides",
1776
+ skills: "guides",
1777
+ "legacy-commands": "guides",
1778
+ hooks: "sensors",
1779
+ "verify-command": "sensors",
1780
+ "stop-check": "loop",
1781
+ "auto-memory-index": "memory",
1782
+ "allow-rules": "permissions",
1783
+ "subagents-and-mcp": "permissions",
1784
+ "deny-secrets": "permissions",
1785
+ "broad-allow": "permissions",
1786
+ "default-mode": "permissions",
1787
+ sandbox: "permissions",
1788
+ reach: "permissions",
1789
+ managed: "permissions",
1790
+ "prose-rules": "permissions",
1791
+ "subagent-scope": "permissions",
1792
+ retention: "observability"
1793
+ };
1794
+ function layerOf(id) {
1795
+ return LAYER_OF[id.split(":")[0]] ?? "guides";
1796
+ }
1797
+ var LAYERS = [
1798
+ {
1799
+ key: "guides",
1800
+ title: "Guides",
1801
+ what: "What steers the agent before it works: instructions, rules and skills.",
1802
+ unchecked: "It does not judge what the instructions say, only how long they are."
1803
+ },
1804
+ {
1805
+ key: "sensors",
1806
+ title: "Sensors",
1807
+ what: "What checks the work: tests, linters and hooks the agent can run.",
1808
+ unchecked: "It does not see your CI, so it cannot tell a check that always fails from one that works."
1809
+ },
1810
+ {
1811
+ key: "loop",
1812
+ title: "Loop",
1813
+ what: "What sends the agent back when the work is not done.",
1814
+ unchecked: "It does not look at retry or spending limits for runs with no person present."
1815
+ },
1816
+ {
1817
+ key: "memory",
1818
+ title: "Memory",
1819
+ what: "What carries over from one session to the next.",
1820
+ unchecked: "It does not look for handoff notes or a record of decisions."
1821
+ },
1822
+ {
1823
+ key: "permissions",
1824
+ title: "Permissions",
1825
+ what: "What the agent may do without asking, and what it may never do.",
1826
+ unchecked: "It finds a restricted command only when the instructions write it out, as in git push. It does not understand a rule in plain words."
1827
+ },
1828
+ {
1829
+ key: "observability",
1830
+ title: "Observability",
1831
+ what: "What a person can see of what the agent did.",
1832
+ unchecked: "It does not look for cost tracking or alerts."
1833
+ }
1834
+ ];
1193
1835
  function runChecks(facts) {
1194
- const checks = [...memoryChecks(facts), ...automationChecks(facts), ...guardrailChecks(facts), ...verificationChecks(facts)];
1195
- return checks.map((check) => ({ ...check, prompt: promptFor(check, facts) }));
1836
+ const checks = [...memoryChecks(facts), ...automationChecks(facts), ...guardrailChecks(facts), ...proseChecks(facts), ...verificationChecks(facts)];
1837
+ return checks.map((check) => ({ ...check, layer: layerOf(check.id), prompt: promptFor(check, facts) }));
1838
+ }
1839
+ function layerSummary(checks) {
1840
+ return LAYERS.map(({ key, title }) => {
1841
+ const mine = checks.filter((c) => c.layer === key);
1842
+ const count = (status) => mine.filter((c) => c.status === status).length;
1843
+ const [pass, warn, fail, info] = [count("pass"), count("warn"), count("fail"), count("info")];
1844
+ const state = fail ? "fix" : warn ? "look" : pass ? "good" : info ? "facts" : "none";
1845
+ return { layer: key, title, pass, warn, fail, info, state };
1846
+ });
1196
1847
  }
1197
1848
  function summarize2(checks) {
1198
1849
  const count = (status) => checks.filter((c) => c.status === status).length;
@@ -1204,12 +1855,12 @@ var SECRET_NAMES = /^(\.env(\..+)?|secrets?(\..+)?|credentials(\..+)?|.*\.pem|id
1204
1855
  var NOT_SECRET = /\.(example|sample|template)$/i;
1205
1856
  var SECRET_DEPTH = 3;
1206
1857
  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");
1858
+ var home = () => os4.homedir();
1859
+ var configDir = () => process.env.CLAUDE_CONFIG_DIR || path4.join(home(), ".claude");
1209
1860
  var tilde = (file) => file.startsWith(home()) ? `~${file.slice(home().length)}` : file;
1210
1861
  function canRead(project) {
1211
1862
  try {
1212
- readdirSync2(project);
1863
+ readdirSync3(project);
1213
1864
  return true;
1214
1865
  } catch {
1215
1866
  return false;
@@ -1217,25 +1868,31 @@ function canRead(project) {
1217
1868
  }
1218
1869
  function readJson(file) {
1219
1870
  try {
1220
- return JSON.parse(readFileSync2(file, "utf-8"));
1871
+ return JSON.parse(readFileSync4(file, "utf-8"));
1221
1872
  } catch {
1222
1873
  return null;
1223
1874
  }
1224
1875
  }
1225
1876
  function countFiles(dir, test) {
1226
- if (!existsSync3(dir)) return 0;
1877
+ if (!existsSync4(dir)) return 0;
1227
1878
  let total = 0;
1228
- for (const entry of readdirSync2(dir, { withFileTypes: true })) {
1229
- if (entry.isDirectory()) total += countFiles(path3.join(dir, entry.name), test);
1879
+ for (const entry of readdirSync3(dir, { withFileTypes: true })) {
1880
+ if (entry.isDirectory()) total += countFiles(path4.join(dir, entry.name), test);
1230
1881
  else if (test(entry.name)) total += 1;
1231
1882
  }
1232
1883
  return total;
1233
1884
  }
1885
+ function markdownFiles(dir) {
1886
+ if (!existsSync4(dir)) return [];
1887
+ return readdirSync3(dir, { withFileTypes: true }).flatMap(
1888
+ (entry) => entry.isDirectory() ? markdownFiles(path4.join(dir, entry.name)) : entry.name.endsWith(".md") ? [path4.join(dir, entry.name)] : []
1889
+ );
1890
+ }
1234
1891
  function findSecretFiles(root, relative, depth) {
1235
- const dir = path3.join(root, relative);
1236
- if (depth > SECRET_DEPTH || !existsSync3(dir)) return [];
1892
+ const dir = path4.join(root, relative);
1893
+ if (depth > SECRET_DEPTH || !existsSync4(dir)) return [];
1237
1894
  const found = [];
1238
- for (const entry of readdirSync2(dir, { withFileTypes: true })) {
1895
+ for (const entry of readdirSync3(dir, { withFileTypes: true })) {
1239
1896
  const here = relative ? `${relative}/${entry.name}` : entry.name;
1240
1897
  if (entry.isDirectory()) {
1241
1898
  if (!SKIP_DIRS.has(entry.name) && !entry.name.startsWith(".")) found.push(...findSecretFiles(root, here, depth + 1));
@@ -1257,13 +1914,13 @@ function hookCommands(hooks) {
1257
1914
  return found;
1258
1915
  }
1259
1916
  function subagentFiles(dir) {
1260
- if (!existsSync3(dir)) return [];
1917
+ if (!existsSync4(dir)) return [];
1261
1918
  const found = [];
1262
- for (const entry of readdirSync2(dir, { withFileTypes: true })) {
1263
- const file = path3.join(dir, entry.name);
1919
+ for (const entry of readdirSync3(dir, { withFileTypes: true })) {
1920
+ const file = path4.join(dir, entry.name);
1264
1921
  if (entry.isDirectory()) found.push(...subagentFiles(file));
1265
1922
  else if (entry.name.endsWith(".md")) {
1266
- const frontmatter = /^---\n([\s\S]*?)\n---/.exec(readFileSync2(file, "utf-8"))?.[1] ?? "";
1923
+ const frontmatter = /^---\n([\s\S]*?)\n---/.exec(readFileSync4(file, "utf-8"))?.[1] ?? "";
1267
1924
  found.push({ name: entry.name.replace(/\.md$/, ""), limitsTools: /^(tools|disallowedTools)\s*:/m.test(frontmatter) });
1268
1925
  }
1269
1926
  }
@@ -1273,20 +1930,25 @@ var isMarkdown = (name) => name.endsWith(".md");
1273
1930
  var strings = (value) => Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
1274
1931
  function gather(project) {
1275
1932
  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");
1933
+ const label = (file) => file.startsWith(project + path4.sep) ? file.slice(project.length + 1) : tilde(file);
1934
+ const restricted = [];
1935
+ const memoryFile = (file, instructions = true) => {
1936
+ if (!existsSync4(file) || !statSync2(file).isFile()) return null;
1937
+ const text = readFileSync4(file, "utf-8");
1280
1938
  filesRead.push(label(file));
1939
+ if (instructions) restricted.push(...findRestrictedCommands(text, label(file)));
1281
1940
  return { label: label(file), lines: text.split("\n").length - (text.endsWith("\n") ? 1 : 0), bytes: Buffer.byteLength(text) };
1282
1941
  };
1283
1942
  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);
1943
+ path4.join(project, "CLAUDE.md"),
1944
+ path4.join(project, ".claude", "CLAUDE.md"),
1945
+ path4.join(project, "CLAUDE.local.md"),
1946
+ path4.join(project, "AGENTS.md"),
1947
+ path4.join(configDir(), "CLAUDE.md")
1948
+ ].map((file) => memoryFile(file)).filter((file) => file !== null);
1949
+ for (const dir of [path4.join(project, ".claude", "rules"), path4.join(configDir(), "rules")]) {
1950
+ for (const file of markdownFiles(dir)) restricted.push(...findRestrictedCommands(readFileSync4(file, "utf-8"), label(file)));
1951
+ }
1290
1952
  const settingsFile = (scope, file) => {
1291
1953
  const json = readJson(file);
1292
1954
  if (!json) return null;
@@ -1310,12 +1972,12 @@ function gather(project) {
1310
1972
  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
1973
  const settings = [
1312
1974
  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"))
1975
+ settingsFile("local", path4.join(project, ".claude", "settings.local.json")),
1976
+ settingsFile("project", path4.join(project, ".claude", "settings.json")),
1977
+ settingsFile("user", path4.join(configDir(), "settings.json"))
1316
1978
  ].filter((file) => file !== null);
1317
- const projectMcp = readJson(path3.join(project, ".mcp.json"));
1318
- const userConfig = readJson(path3.join(home(), ".claude.json"));
1979
+ const projectMcp = readJson(path4.join(project, ".mcp.json"));
1980
+ const userConfig = readJson(path4.join(home(), ".claude.json"));
1319
1981
  const userServers = Object.keys(userConfig?.mcpServers || {}).length + Object.keys(userConfig?.projects?.[project]?.mcpServers || {}).length;
1320
1982
  if (projectMcp) filesRead.push(".mcp.json");
1321
1983
  if (userConfig) filesRead.push("~/.claude.json (MCP server names only)");
@@ -1325,25 +1987,43 @@ function gather(project) {
1325
1987
  facts: {
1326
1988
  platform: process.platform,
1327
1989
  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")),
1990
+ ruleFiles: countFiles(path4.join(project, ".claude", "rules"), isMarkdown) + countFiles(path4.join(configDir(), "rules"), isMarkdown),
1991
+ autoMemoryIndex: memoryFile(path4.join(configDir(), "projects", encoded, "memory", "MEMORY.md"), false),
1330
1992
  settings,
1331
1993
  skills: {
1332
- project: countFiles(path3.join(project, ".claude", "skills"), (name) => name === "SKILL.md"),
1333
- user: countFiles(path3.join(configDir(), "skills"), (name) => name === "SKILL.md")
1994
+ project: countFiles(path4.join(project, ".claude", "skills"), (name) => name === "SKILL.md"),
1995
+ user: countFiles(path4.join(configDir(), "skills"), (name) => name === "SKILL.md")
1334
1996
  },
1335
1997
  subagents: {
1336
- project: countFiles(path3.join(project, ".claude", "agents"), isMarkdown),
1337
- user: countFiles(path3.join(configDir(), "agents"), isMarkdown)
1998
+ project: countFiles(path4.join(project, ".claude", "agents"), isMarkdown),
1999
+ user: countFiles(path4.join(configDir(), "agents"), isMarkdown)
1338
2000
  },
1339
- subagentFiles: [...subagentFiles(path3.join(project, ".claude", "agents")), ...subagentFiles(path3.join(configDir(), "agents"))],
1340
- legacyCommands: countFiles(path3.join(project, ".claude", "commands"), isMarkdown),
2001
+ subagentFiles: [...subagentFiles(path4.join(project, ".claude", "agents")), ...subagentFiles(path4.join(configDir(), "agents"))],
2002
+ legacyCommands: countFiles(path4.join(project, ".claude", "commands"), isMarkdown),
1341
2003
  mcpServers: { project: Object.keys(projectMcp?.mcpServers || {}).length, user: userServers },
1342
- secretFiles: findSecretFiles(project, "", 0).sort()
2004
+ secretFiles: findSecretFiles(project, "", 0).sort(),
2005
+ restricted
1343
2006
  }
1344
2007
  };
1345
2008
  }
1346
- var esc3 = (text) => text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
2009
+ var TOOLBAR_CSS4 = `
2010
+ body{padding-bottom:64px}
2011
+ .jqbar{position:fixed;left:0;right:0;bottom:0;z-index:5;display:flex;flex-wrap:wrap;align-items:center;gap:4px 14px;padding:8px 16px;font:13px/1.4 system-ui,sans-serif;background:var(--card,Canvas);color:var(--fg,CanvasText);border-top:1px solid var(--line,GrayText)}
2012
+ .jqbar a{color:var(--link,LinkText)}
2013
+ .jqbar .here{font-weight:700}
2014
+ .jqbar details[open]{order:-1;flex-basis:100%}
2015
+ .jqbar summary{cursor:pointer;color:var(--mut,GrayText);list-style:none;display:inline-block;padding:2px 0}
2016
+ .jqbar summary::-webkit-details-marker{display:none}
2017
+ .jqbar summary::after{content:" \u25B8"}
2018
+ .jqbar details[open] summary::after{content:" \u25BE"}
2019
+ .jqbar summary small,.jqbar a small{font-size:11px;font-weight:400}
2020
+ .jqbar details>div{margin:4px 0 6px;padding:8px 10px;max-width:640px;border:1px solid var(--line,GrayText);border-radius:8px;background:var(--well,Canvas)}
2021
+ .jqbar details>div p{margin:0 0 4px}
2022
+ .jqbar code{font:12px ui-monospace,Menlo,monospace;word-break:break-all}
2023
+ .jqbar a:focus-visible,.jqbar summary:focus-visible{outline:2px solid var(--link,LinkText);outline-offset:2px}
2024
+ @media print{.jqbar{display:none}body{padding-bottom:0}}
2025
+ `;
2026
+ var esc22 = (text) => text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
1347
2027
  var STATUS = {
1348
2028
  fail: { icon: "\u2715", word: "Fix" },
1349
2029
  warn: { icon: "!", word: "Look" },
@@ -1392,54 +2072,67 @@ function done(){b.textContent='Copied';setTimeout(function(){b.textContent='Copy
1392
2072
  function old(){var a=document.createElement('textarea');a.value=t;document.body.appendChild(a);a.select();document.execCommand('copy');a.remove();done()}
1393
2073
  if(navigator.clipboard&&window.isSecureContext){navigator.clipboard.writeText(t).then(done,old)}else{old()}});`;
1394
2074
  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>`;
2075
+ var sourceLink = (check) => `<a href="${esc22(check.source)}" target="_blank" rel="noopener noreferrer">${esc22(check.source.replace(/^https:\/\/code\.claude\.com\/docs\/en\//, "docs: ").replace(/\.md$/, ""))}</a>`;
1396
2076
  function fixCard(check) {
1397
2077
  const status = STATUS[check.status];
1398
2078
  const id = anchor(check);
1399
2079
  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>`;
2080
+ 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">${esc22(check.prompt)}</pre></div>` : "";
2081
+ return `<section class="check s-${check.status}" id="${id}"><h3>${dot(check.status)}${esc22(check.title)}<span class="word">${status.word}</span></h3><p>${esc22(check.detail)}</p>${check.fix ? `<p class="fix"><b>What to change:</b> ${esc22(check.fix)}</p>` : ""}${prompt}<p class="src mut">Rests on ${sourceLink(check)}</p></section>`;
2082
+ }
2083
+ var row2 = (check) => `<li>${dot(check.status)}<b>${esc22(check.title)}<span class="mut"> \xB7 ${STATUS[check.status].word}</span></b><span class="d">${esc22(check.detail)}</span><span class="src mut">${sourceLink(check)}</span></li>`;
2084
+ var LAYER_DOT = { fix: "fail", look: "warn", good: "pass", facts: "info", none: "info" };
2085
+ function layerCount(row22) {
2086
+ const judged = row22.pass + row22.warn + row22.fail;
2087
+ if (judged) return `${row22.pass} of ${judged} good`;
2088
+ return row22.info ? "facts only" : "no check ran";
2089
+ }
2090
+ function layerPanel(checks) {
2091
+ const rows = layerSummary(checks).map((row22) => {
2092
+ const about = LAYERS.find((l) => l.key === row22.layer);
2093
+ return `<li>${dot(LAYER_DOT[row22.state])}<b>${about.title}<span class="mut"> \xB7 ${layerCount(row22)}</span></b><span class="d">${esc22(about.what)} <span class="mut">${esc22(about.unchecked)}</span></span></li>`;
2094
+ });
2095
+ return `<h2>Your harness, layer by layer</h2><p class="mut">An agent is a model and what surrounds it. These are six parts of what surrounds it, with what the checks below found in each.</p><ul class="rows">${rows.join("")}</ul>`;
1402
2096
  }
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) {
2097
+ function renderPage3(report2, toolsBar = "") {
1405
2098
  const { summary } = report2;
1406
2099
  const judged = summary.pass + summary.warn + summary.fail;
1407
2100
  const bar = ["fail", "warn", "pass"].filter((s) => summary[s] > 0).map((s) => `<i class="b-${s}" style="flex:${summary[s]}"></i>`).join("");
1408
2101
  const sorted = [...report2.checks].sort((a, b) => ORDER.indexOf(a.status) - ORDER.indexOf(b.status));
1409
2102
  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>';
2103
+ const todo = fixes.length ? `<h2>Do these first</h2><ul class="todo">${fixes.map((c) => `<li>${dot(c.status)}<a href="#${anchor(c)}">${esc22(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
2104
  const groups = GROUPS.map((group) => {
1412
2105
  const mine = sorted.filter((c) => c.group === group.key);
1413
2106
  const rest = mine.filter((c) => !needsFix(c));
1414
2107
  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
2108
  }).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>
2109
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>JQ Groundcrew: ${esc22(report2.project)}</title><style>${CSS}${toolsBar ? TOOLBAR_CSS4 : ""}</style></head><body><main><h1>JQ Groundcrew</h1><p class="mut">The setup check for Claude Code. How it is set up for <code>${esc22(report2.project)}</code>. Read ${esc22(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 + layerPanel(report2.checks) + 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 your instruction files, and counted the rest. 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>${esc22(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>${toolsBar}<script>${COPY_SCRIPT}</script></body></html>
1417
2110
  `;
1418
2111
  }
1419
2112
  function report(project) {
1420
2113
  const { facts, filesRead } = gather(project);
1421
2114
  const checks = runChecks(facts);
1422
- return { project: tilde(project), generatedAt: (/* @__PURE__ */ new Date()).toLocaleString("en-US"), filesRead, checks, summary: summarize2(checks) };
2115
+ return { project: tilde(project), generatedAt: (/* @__PURE__ */ new Date()).toLocaleString("en-US"), filesRead, checks, summary: summarize2(checks), layers: layerSummary(checks) };
1423
2116
  }
1424
2117
 
1425
2118
  // src/collect.ts
1426
- import { existsSync as existsSync5, readdirSync as readdirSync3, readFileSync as readFileSync4, statSync as statSync3 } from "fs";
1427
- import path5 from "path";
2119
+ import { existsSync as existsSync6, readdirSync as readdirSync4, readFileSync as readFileSync6, statSync as statSync3 } from "fs";
2120
+ import path6 from "path";
1428
2121
 
1429
2122
  // 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");
2123
+ import { createHash as createHash2 } from "crypto";
2124
+ import { existsSync as existsSync5, readFileSync as readFileSync5 } from "fs";
2125
+ import os5 from "os";
2126
+ import path5 from "path";
2127
+ var expandHome = (p) => p === "~" || p.startsWith("~/") ? path5.join(os5.homedir(), p.slice(1)) : p;
2128
+ function defaultConfigFile2() {
2129
+ return path5.join(os5.homedir(), ".jq", "config.json");
1437
2130
  }
1438
2131
  function loadConfig(file) {
1439
- if (!existsSync4(file)) return {};
2132
+ if (!existsSync5(file)) return {};
1440
2133
  let raw;
1441
2134
  try {
1442
- raw = JSON.parse(readFileSync3(file, "utf8"));
2135
+ raw = JSON.parse(readFileSync5(file, "utf8"));
1443
2136
  } catch (e) {
1444
2137
  throw new Error(`cannot read ${file}: ${e?.message || e}`);
1445
2138
  }
@@ -1449,7 +2142,7 @@ function loadConfig(file) {
1449
2142
  if (typeof r.mailbox === "string") out.mailbox = expandHome(r.mailbox);
1450
2143
  if (r.names && typeof r.names === "object" && !Array.isArray(r.names)) {
1451
2144
  out.names = {};
1452
- for (const [k, v] of Object.entries(r.names)) if (typeof v === "string") out.names[k] = path4.resolve(expandHome(v));
2145
+ for (const [k, v] of Object.entries(r.names)) if (typeof v === "string") out.names[k] = path5.resolve(expandHome(v));
1453
2146
  }
1454
2147
  if (Array.isArray(r.report)) out.report = r.report.filter((q) => typeof q === "string");
1455
2148
  if (Array.isArray(r.sendQuestions)) out.sendQuestions = r.sendQuestions.filter((q) => typeof q === "string").map(expandHome);
@@ -1458,16 +2151,16 @@ function loadConfig(file) {
1458
2151
  }
1459
2152
  function findMailbox(opts) {
1460
2153
  const named = opts.flag || opts.config || opts.env;
1461
- if (named) return path4.resolve(expandHome(named));
1462
- let dir = path4.resolve(opts.cwd);
2154
+ if (named) return path5.resolve(expandHome(named));
2155
+ let dir = path5.resolve(opts.cwd);
1463
2156
  for (; ; ) {
1464
- if (existsSync4(path4.join(dir, ".crosstalk"))) return dir;
1465
- const up = path4.dirname(dir);
2157
+ if (existsSync5(path5.join(dir, ".crosstalk"))) return dir;
2158
+ const up = path5.dirname(dir);
1466
2159
  if (up === dir) return null;
1467
2160
  dir = up;
1468
2161
  }
1469
2162
  }
1470
- var repoId = (tree) => createHash("sha1").update(tree).digest("hex").slice(0, 10);
2163
+ var repoId = (tree) => createHash2("sha1").update(tree).digest("hex").slice(0, 10);
1471
2164
  function matchInbox(folder, inboxes) {
1472
2165
  const f = folder.toLowerCase();
1473
2166
  const exact = inboxes.find((i) => i.toLowerCase() === f);
@@ -1561,8 +2254,8 @@ function originIn(config) {
1561
2254
  }
1562
2255
  function under(tree, folders) {
1563
2256
  return folders.some((f) => {
1564
- const folder = path4.resolve(expandHome(f));
1565
- return tree === folder || tree.startsWith(folder + path4.sep);
2257
+ const folder = path5.resolve(expandHome(f));
2258
+ return tree === folder || tree.startsWith(folder + path5.sep);
1566
2259
  });
1567
2260
  }
1568
2261
  function reportable(r, only) {
@@ -1570,7 +2263,7 @@ function reportable(r, only) {
1570
2263
  const e = entry.trim();
1571
2264
  if (!e) return false;
1572
2265
  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;
2266
+ return /^[~/.]/.test(e) && path5.resolve(expandHome(e)) === r.tree;
1574
2267
  });
1575
2268
  }
1576
2269
  function teamReport(o, only = null, sendQuestions = []) {
@@ -1595,10 +2288,10 @@ function teamReport(o, only = null, sendQuestions = []) {
1595
2288
 
1596
2289
  // src/collect.ts
1597
2290
  function looksLikeProject(dir) {
1598
- return [".git", ".claude", "CLAUDE.md"].some((f) => existsSync5(path5.join(dir, f)));
2291
+ return [".git", ".claude", "CLAUDE.md"].some((f) => existsSync6(path6.join(dir, f)));
1599
2292
  }
1600
2293
  function checkSetup(tree) {
1601
- if (!existsSync5(tree)) return { error: "the folder is gone" };
2294
+ if (!existsSync6(tree)) return { error: "the folder is gone" };
1602
2295
  if (!canRead(tree)) return { error: "the folder cannot be read" };
1603
2296
  try {
1604
2297
  return { summary: summarize2(runChecks(gather(tree).facts)) };
@@ -1608,15 +2301,15 @@ function checkSetup(tree) {
1608
2301
  }
1609
2302
  function remoteOf(tree) {
1610
2303
  try {
1611
- let gitDir = path5.join(tree, ".git");
2304
+ let gitDir = path6.join(tree, ".git");
1612
2305
  if (statSync3(gitDir).isFile()) {
1613
- const m = /^gitdir:\s*(.+)$/m.exec(readFileSync4(gitDir, "utf8"));
2306
+ const m = /^gitdir:\s*(.+)$/m.exec(readFileSync6(gitDir, "utf8"));
1614
2307
  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());
2308
+ gitDir = path6.resolve(tree, m[1].trim());
2309
+ const common = path6.join(gitDir, "commondir");
2310
+ if (existsSync6(common)) gitDir = path6.resolve(gitDir, readFileSync6(common, "utf8").trim());
1618
2311
  }
1619
- return originIn(readFileSync4(path5.join(gitDir, "config"), "utf8"));
2312
+ return originIn(readFileSync6(path6.join(gitDir, "config"), "utf8"));
1620
2313
  } catch {
1621
2314
  return null;
1622
2315
  }
@@ -1636,7 +2329,7 @@ async function collectOverview(opts) {
1636
2329
  if (opts.mailbox) {
1637
2330
  try {
1638
2331
  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);
2332
+ inboxes = readdirSync4(path6.join(opts.mailbox, "inbox"), { withFileTypes: true }).filter((e) => e.isDirectory() && e.name !== BOARD).map((e) => e.name);
1640
2333
  } catch (e) {
1641
2334
  mailNote = String(e?.message || e);
1642
2335
  }
@@ -1698,7 +2391,7 @@ function mailTab(o) {
1698
2391
  }
1699
2392
  return '<iframe title="Mailbox" src="/raw/mail"></iframe>';
1700
2393
  }
1701
- function renderShell(o, tab, repo, version) {
2394
+ function renderShell(o, tab, repo, version, bar = "") {
1702
2395
  const body = tab === "overview" ? overview(o) : tab === "sessions" ? '<iframe title="Sessions" src="/raw/sessions"></iframe>' : tab === "setup" ? setupTab(o, repo) : mailTab(o);
1703
2396
  const needs = o.repos.reduce((n, r) => n + r.needs_you, 0);
1704
2397
  const failing = o.repos.filter((r) => r.setup && r.setup.fail > 0).length;
@@ -1734,7 +2427,7 @@ tbody th{font-weight:600}.path{display:block;font-weight:400;font-size:12px;colo
1734
2427
  .chip.on{border-color:var(--fg);font-weight:600}
1735
2428
  code,pre{font:12px ui-monospace,monospace;background:var(--well);border-radius:4px;padding:1px 4px}pre{padding:10px;overflow-x:auto}
1736
2429
  @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>
2430
+ ${bar ? TOOLBAR_CSS : ""}</style></head><body>
1738
2431
  <header>
1739
2432
  <h1>JQ Deck</h1>
1740
2433
  <p class="head">${esc4(o.headline)}</p>
@@ -1743,7 +2436,7 @@ code,pre{font:12px ui-monospace,monospace;background:var(--well);border-radius:4
1743
2436
  </header>
1744
2437
  <main>${body}</main>
1745
2438
  <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>`;
2439
+ ${bar}</body></html>`;
1747
2440
  }
1748
2441
 
1749
2442
  // src/cli.ts
@@ -1760,7 +2453,7 @@ function parseArgs(argv, env = {}) {
1760
2453
  sendQuestions: null,
1761
2454
  port: DEFAULT_PORT,
1762
2455
  mailbox: null,
1763
- config: env.JQ_DECK_CONFIG || defaultConfigFile(),
2456
+ config: env.JQ_DECK_CONFIG || defaultConfigFile2(),
1764
2457
  questionTrees: env.JQ_AGENTS_QUESTION_TREES ? list(env.JQ_AGENTS_QUESTION_TREES) : null,
1765
2458
  probe: false,
1766
2459
  sample: true,
@@ -1807,17 +2500,19 @@ function reportList(a, fromConfig) {
1807
2500
  function buildContext(a, env, cwd, version) {
1808
2501
  const config = loadConfig(expandHome(a.config));
1809
2502
  return {
2503
+ runningDir: runningDir(env),
2504
+ configFile: expandHome(a.config),
1810
2505
  port: a.port,
1811
2506
  version,
1812
2507
  probe: a.probe,
1813
2508
  sample: a.sample,
1814
2509
  report: a.watch ? reportList(a, config.report) : null,
1815
- sendQuestions: a.watch ? (a.sendQuestions ?? config.sendQuestions ?? []).map((t) => path6.resolve(expandHome(t))) : [],
2510
+ sendQuestions: a.watch ? (a.sendQuestions ?? config.sendQuestions ?? []).map((t) => path7.resolve(expandHome(t))) : [],
1816
2511
  deck: {
1817
2512
  mailbox: findMailbox({ flag: a.mailbox, config: config.mailbox, env: env.CROSSTALK_DIR, cwd }),
1818
2513
  names: config.names,
1819
2514
  // Off unless asked for: question text is a session's own words.
1820
- questionTrees: (a.questionTrees ?? config.questions ?? []).map((t) => path6.resolve(expandHome(t))),
2515
+ questionTrees: (a.questionTrees ?? config.questions ?? []).map((t) => path7.resolve(expandHome(t))),
1821
2516
  maxAgeDays: a.maxAgeDays,
1822
2517
  cwd
1823
2518
  }
@@ -1834,10 +2529,11 @@ async function handle(url, host, ctx, overview2 = collectOverview) {
1834
2529
  if (u.pathname === "/") {
1835
2530
  const asked = u.searchParams.get("tab");
1836
2531
  const tab = TABS.includes(asked ?? "") ? asked : "overview";
1837
- return html(renderShell(await overview2(ctx.deck), tab, u.searchParams.get("repo"), ctx.version));
2532
+ const bar = toolbar({ here: "deck", running: readRunning(ctx.runningDir), team: readTeamUrl(ctx.configFile) });
2533
+ return html(renderShell(await overview2(ctx.deck), tab, u.searchParams.get("repo"), ctx.version, bar));
1838
2534
  }
1839
2535
  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 })));
2536
+ 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, turnCheck: readTurnCheckConfig(ctx.configFile) })));
1841
2537
  }
1842
2538
  if (u.pathname === "/raw/setup") {
1843
2539
  const row3 = (await overview2(ctx.deck)).repos.find((r) => r.id === u.searchParams.get("repo"));
@@ -1900,14 +2596,15 @@ async function run2(argv, version) {
1900
2596
  });
1901
2597
  res.end(reply.body);
1902
2598
  }).listen(a.port, "127.0.0.1", () => {
2599
+ announce("deck", a.port, ctx.runningDir);
1903
2600
  console.log(`jq-deck: http://127.0.0.1:${a.port} (Ctrl-C to stop)`);
1904
2601
  console.log(ctx.deck.mailbox ? `jq-deck: mailbox ${ctx.deck.mailbox}` : "jq-deck: no mailbox found (pass --mailbox DIR to show mail)");
1905
2602
  });
1906
2603
  }
1907
2604
 
1908
2605
  // 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.
2606
+ var VERSION2 = true ? "0.3.3" : "dev";
2607
+ var HELP = `JQ Deck ${VERSION2}: one page for your Claude Code sessions, their setup and their mail.
1911
2608
 
1912
2609
  jq-deck open the page at http://127.0.0.1:${DEFAULT_PORT}
1913
2610
  jq-deck --json print the overview
@@ -1936,9 +2633,9 @@ The page is served to this machine only. Nothing leaves it unless you pass --exe
1936
2633
  Unofficial. Not affiliated with or endorsed by Anthropic.`;
1937
2634
  var args = process.argv.slice(2);
1938
2635
  if (args.includes("--help") || args.includes("-h")) console.log(HELP);
1939
- else if (args.includes("--version") || args.includes("-v")) console.log(VERSION);
2636
+ else if (args.includes("--version") || args.includes("-v")) console.log(VERSION2);
1940
2637
  else
1941
- run2(args, VERSION).catch((error) => {
2638
+ run2(args, VERSION2).catch((error) => {
1942
2639
  console.error(error.message || error);
1943
2640
  process.exit(1);
1944
2641
  });