@futuvara/connect 0.3.4 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1554 @@
1
+ #!/usr/bin/env node
2
+ // Worktree dashboard: every git worktree and branch of this repo, live, from plan to production,
3
+ // with a prioritised list of what to do next. Node built-ins only, no install, no build step.
4
+ // node tools/worktree-dashboard/server.mjs [--port 4500] [--base main] [--config extra.json]
5
+ // Read-only: it never runs a git command that changes anything except `git fetch --prune`.
6
+ // How to read it, CONFIG, the plan convention, the deployed commit and new rules: README.md.
7
+
8
+ import http from "node:http";
9
+ import { execFile } from "node:child_process";
10
+ import fs from "node:fs";
11
+ import os from "node:os";
12
+ import path from "node:path";
13
+ import { fileURLToPath, pathToFileURL } from "node:url";
14
+
15
+ // ================================= CONFIG =================================
16
+ // Every setting lives here. `--config file.json` merges a JSON object over it (one level deep).
17
+ export const CONFIG = {
18
+ port: 4500,
19
+ host: "127.0.0.1", // local only: the page shows the repo's contents
20
+ base: "main", // the branch work lands in
21
+ remote: "origin",
22
+ staleDays: 3, // no commit and no file change for this long = stale
23
+ fetchIntervalMs: 2 * 60_000, // `git fetch --prune` and the gh PR list; 0 = never
24
+ refreshIntervalMs: 10_000, // fallback refresh when no file event arrives
25
+ // `git status` runs only for a worktree whose files changed, or whose last read is older
26
+ // than this. It takes 1.1–1.4 s per worktree on the Futuvara PC, so 19 of them every 10 s
27
+ // would keep a core busy.
28
+ statusMaxAgeMs: 60_000,
29
+ debounceMs: 500, // file events are batched for this long…
30
+ debounceMaxMs: 3_000, // …but never held back longer than this
31
+ gitTimeoutMs: 20_000,
32
+ gitConcurrency: 4, // git processes at once
33
+ maxCommits: 500, // per branch
34
+ // Plan files, tried in order in each worktree; `*` matches within one folder.
35
+ planFiles: ["PLAN.md", ".claude/plan.md", "docs/plan*.md", "TODO.md"],
36
+ // Then: the plan in this folder that the worktree is editing, else the one its own commits
37
+ // changed last. This repo keeps every plan in docs/plans/. "" turns it off.
38
+ planDir: "docs/plans/",
39
+ // A file event under any of these folder names never triggers a refresh.
40
+ watchIgnore: ["node_modules", ".next", ".turbo", ".vercel", ".firebase", ".cache", "coverage",
41
+ "test-results", "playwright-report", "__pycache__", ".pytest_cache", ".venv", "dist", "out"],
42
+ envCacheMs: 60_000,
43
+ envTimeoutMs: 5_000,
44
+ // Deployed environments, earliest first. Each finds its deployed commit one way:
45
+ // { name, branch: "origin/production" }
46
+ // { name, tag: "prod-*" } the newest matching tag
47
+ // { name, url, field: "sha", match: "<regex>" } a JSON field, or the whole body; `match`
48
+ // picks the commit id out (group 1)
49
+ // { name, command: ["bash", "-c", "…"] } its output is the commit id
50
+ // Optional `verifyUrl`: the environment counts as verified only when it answers 2xx.
51
+ // No staging exists for Futuvara yet; add it above prod when one does.
52
+ envs: [
53
+ { name: "prod", url: "https://app.futuvara.com/api/health", field: "commit", match: "pre-([0-9a-f]{7,40})" },
54
+ ],
55
+ // The action engine's thresholds and commands. Commands are only shown, never run.
56
+ actions: {
57
+ // This repo lands work through one release train: futu-git-sweep merges finished branches into
58
+ // local main and ships them; sessions never push branches or open PRs. When true, "push",
59
+ // "open a PR", "deploy" and "pull main" point to the sweep, and cleanup to futu-clean
60
+ // (worktree folders here hold node_modules links into main, so never remove them by hand).
61
+ // false gives plain git and gh commands.
62
+ releaseTrain: true,
63
+ sweepCommand: "/futu-git-sweep (in Claude Code, from one worktree)",
64
+ cleanCommand: "/futu-clean (in Claude Code)",
65
+ deployCommand: "npm run deploy", // used when releaseTrain is false
66
+ openCommand: 'code "{file}"', // opens a plan file
67
+ planTemplate: "docs/plans/TEMPLATE-worktree-plan.md",
68
+ planTarget: "docs/plans/{date}-{slug}.md",
69
+ uncommittedHours: 24, // uncommitted changes older than this → commit
70
+ behindBase: 50, // more commits behind the base than this → update
71
+ planStalledDays: 3, // no step ticked for this long while the branch is active
72
+ stashDays: 14, // stash entries older than this → review or drop
73
+ cleanupQuietHours: 24, // a merged branch is a cleanup candidate once quiet this long
74
+ groupMin: 3, // this many actions of one groupable rule become one grouped action
75
+ // The Actions tab's side panel turns the actions in view into one prompt for a Claude Code
76
+ // session started in the main worktree. {main} = its path, {count} = the number of actions.
77
+ prompt: "Work from the main worktree ({main}). Below are {count} actions from the worktree dashboard, most urgent first. " +
78
+ "For each one: check it still applies (the dashboard can be a minute old), do it, then say in one line what you did. " +
79
+ "Each suggested command is a hint; its cd shows where it applies. Stop and ask me before anything you cannot undo, and whenever a step needs my decision.",
80
+ trainPrompt: "Follow AGENTS.md: only futu-git-sweep lands and ships, so run the sweep once for every action that names it, not once per action; " +
81
+ "never reset local main; never push, open a pull request or deploy outside the sweep; clean up worktrees only through futu-clean.",
82
+ dismissForgetHours: 24, // a dismissal is forgotten once its action has been gone this long
83
+ disabled: [], // rule ids to switch off, e.g. ["no-plan"]
84
+ },
85
+ };
86
+ // ==========================================================================
87
+
88
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
89
+ const HISTORY_FILE = path.join(HERE, ".history.json");
90
+ const ACTIONS_FILE = path.join(HERE, ".actions-state.json");
91
+ let REPO = process.cwd();
92
+
93
+ // ---------------------------------------------------------------- processes
94
+ let running = 0;
95
+ const waiting = [];
96
+ function limited(fn) {
97
+ return new Promise((resolve, reject) => {
98
+ const start = () => {
99
+ running++;
100
+ fn().then(resolve, reject).finally(() => { running--; waiting.shift()?.(); });
101
+ };
102
+ if (running < CONFIG.gitConcurrency) start(); else waiting.push(start);
103
+ });
104
+ }
105
+
106
+ /** execFile, never a shell; rejects with the first stderr line and the exit code. */
107
+ export function run(cmd, args, { cwd = REPO, timeout = CONFIG.gitTimeoutMs, input } = {}) {
108
+ return limited(() => new Promise((resolve, reject) => {
109
+ const child = execFile(cmd, args, { cwd, timeout, maxBuffer: 256 << 20, windowsHide: true, encoding: "utf8" },
110
+ (err, stdout, stderr) => {
111
+ if (!err) return resolve(stdout);
112
+ const why = err.killed ? `timed out after ${timeout} ms` : String(stderr).trim().split("\n")[0] || err.message;
113
+ reject(Object.assign(new Error(`${cmd} ${args.slice(0, 3).join(" ")}: ${why}`), { code: err.code }));
114
+ });
115
+ if (input !== undefined) child.stdin.end(input);
116
+ }));
117
+ }
118
+ // --no-optional-locks: never take index.lock from a session that is committing.
119
+ const git = (args, opts) => run("git", ["--no-optional-locks", "-c", "core.quotepath=off", ...args], opts);
120
+ const lines = (s) => s.split("\n").map((l) => l.replace(/\r$/, "")).filter(Boolean);
121
+
122
+ // Results keyed by commit ids never change, so they are kept.
123
+ const memo = new Map();
124
+ function cached(key, fn) {
125
+ if (memo.has(key)) return memo.get(key);
126
+ const p = fn();
127
+ p.catch(() => memo.delete(key));
128
+ memo.set(key, p);
129
+ if (memo.size > 50_000) memo.delete(memo.keys().next().value);
130
+ return p;
131
+ }
132
+ const isAncestor = (a, b) => cached(`anc:${a}:${b}`, () =>
133
+ git(["merge-base", "--is-ancestor", a, b]).then(() => true, (e) => (e.code === 1 ? false : Promise.reject(e))));
134
+
135
+ // ---------------------------------------------------------------- plan
136
+ /** Title, summary, phases (H2/H3), checkbox steps with nesting, progress and the current step. */
137
+ export function parsePlan(text) {
138
+ const src = text.split(/\r?\n/);
139
+ let title = null, summary = null, fence = false, phase = null;
140
+ const phases = [], stack = [], all = [];
141
+ for (let i = 0; i < src.length; i++) {
142
+ const line = src[i];
143
+ if (/^\s*(```|~~~)/.test(line)) { fence = !fence; continue; }
144
+ if (fence) continue;
145
+ const h = line.match(/^(#{1,3})\s+(.+?)\s*#*\s*$/);
146
+ if (h) {
147
+ if (h[1].length > 1) { phase = { title: h[2], level: h[1].length, line: i + 1, steps: [], flat: [] }; phases.push(phase); stack.length = 0; }
148
+ else if (title === null) { title = h[2]; summary = paragraphAfter(src, i + 1); }
149
+ continue;
150
+ }
151
+ const m = line.match(/^(\s*)(?:[-*+]|\d+[.)])\s+\[([ xX~])\]\s+(.*)$/);
152
+ if (!m) continue;
153
+ const text = m[3].trim();
154
+ const state = /[xX]/.test(m[2]) ? "done" : m[2] === "~" || /\(in progress\)/i.test(text) ? "doing" : "todo";
155
+ const step = { text, state, line: i + 1, steps: [] };
156
+ if (!phase) { phase = { title: "Steps", level: 2, line: 0, steps: [], flat: [] }; phases.push(phase); }
157
+ const indent = m[1].replace(/\t/g, " ").length;
158
+ while (stack.length && stack.at(-1).indent >= indent) stack.pop();
159
+ (stack.length ? stack.at(-1).step.steps : phase.steps).push(step);
160
+ stack.push({ indent, step });
161
+ phase.flat.push(step);
162
+ all.push(step);
163
+ }
164
+ const cur = all.find((s) => s.state === "doing") ?? all.find((s) => s.state === "todo") ?? null;
165
+ return {
166
+ title, summary, ...progress(all),
167
+ current: cur ? { text: cur.text, line: cur.line, phase: phases.find((p) => p.flat.includes(cur))?.title ?? null } : null,
168
+ phases: phases.filter((p) => p.flat.length).map((p) => ({ title: p.title, level: p.level, line: p.line, ...progress(p.flat), steps: p.steps })),
169
+ };
170
+ }
171
+ function progress(steps) {
172
+ const total = steps.length, done = steps.filter((s) => s.state === "done").length, doing = steps.filter((s) => s.state === "doing").length;
173
+ return { total, done, doing, todo: total - done - doing, remaining: total - done, pct: total ? Math.round((done / total) * 100) : null };
174
+ }
175
+ function paragraphAfter(src, i) {
176
+ while (i < src.length && !src[i].trim()) i++;
177
+ const out = [];
178
+ for (; i < src.length && src[i].trim() && !/^#{1,6}\s/.test(src[i]); i++) out.push(src[i].trim());
179
+ const s = out.join(" ");
180
+ return s ? (s.length > 600 ? `${s.slice(0, 600)}…` : s) : null;
181
+ }
182
+
183
+ /** Each piece of work's furthest stage (0 = uncommitted) → tracker segments, counts and board column. */
184
+ export function stageView(items, n) {
185
+ const segments = [], counts = Array(n).fill(0);
186
+ for (const s of items) counts[s]++;
187
+ for (let k = 0; k < n; k++) {
188
+ const reached = items.filter((s) => s >= k).length;
189
+ segments.push(!items.length ? "none" : reached === items.length ? "full" : reached ? "partial" : "none");
190
+ }
191
+ return { column: items.length ? Math.min(...items) : null, furthest: items.length ? Math.max(...items) : null, segments, counts };
192
+ }
193
+
194
+ // ---------------------------------------------------------------- git readers
195
+ async function listWorktrees() {
196
+ const list = [];
197
+ let cur = null;
198
+ for (const line of lines(await git(["worktree", "list", "--porcelain"]))) {
199
+ if (line.startsWith("worktree ")) { cur = { path: line.slice(9), head: null, branch: null, detached: false, bare: false, locked: null, prunable: null }; list.push(cur); }
200
+ else if (!cur) continue;
201
+ else if (line.startsWith("HEAD ")) cur.head = line.slice(5);
202
+ else if (line.startsWith("branch ")) cur.branch = line.slice(7).replace(/^refs\/heads\//, "");
203
+ else if (line === "detached") cur.detached = true;
204
+ else if (line === "bare") cur.bare = true;
205
+ else if (line.startsWith("locked")) cur.locked = line.slice(7) || "locked";
206
+ else if (line.startsWith("prunable")) cur.prunable = line.slice(9) || "prunable";
207
+ }
208
+ list.forEach((w, i) => { w.isMain = i === 0; w.key = w.branch || `detached:${path.basename(w.path)}`; });
209
+ return list.filter((w) => !w.bare);
210
+ }
211
+
212
+ async function readRefs() {
213
+ const refs = new Map();
214
+ const out = await git(["for-each-ref", "--format=%(refname)%00%(objectname)%00%(upstream)%00%(upstream:track)%00%(committerdate:unix)%00%(subject)", "refs/heads", "refs/remotes"]);
215
+ for (const l of lines(out)) {
216
+ const [ref, sha, upstream, track, date, subject] = l.split("\0");
217
+ refs.set(ref, { ref, sha, upstream, track, at: Number(date) * 1000, subject });
218
+ }
219
+ return refs;
220
+ }
221
+
222
+ async function readStash() {
223
+ const out = await git(["stash", "list", "--format=%gd%x1f%ct%x1f%gs"]).catch(() => "");
224
+ return lines(out).map((l) => {
225
+ const [ref, ct, subject] = l.split("\x1f");
226
+ return { ref, at: Number(ct) * 1000, subject, branch: subject.match(/^(?:WIP on|On) ([^:]+):/)?.[1] ?? null };
227
+ });
228
+ }
229
+
230
+ async function readStatus(dir) {
231
+ const s = { staged: [], unstaged: [], untracked: [], conflicted: [], firstFileChange: null, lastFileChange: null };
232
+ const parts = (await git(["status", "--porcelain=v2", "--branch", "-z"], { cwd: dir })).split("\0");
233
+ for (let i = 0; i < parts.length; i++) {
234
+ const p = parts[i];
235
+ if (p[0] === "1" || p[0] === "2") {
236
+ const f = p.split(" ");
237
+ const file = f.slice(p[0] === "1" ? 8 : 9).join(" ");
238
+ if (p[0] === "2") i++; // the original path of a rename
239
+ if (f[1][0] !== ".") s.staged.push({ path: file, code: f[1][0] });
240
+ if (f[1][1] !== ".") s.unstaged.push({ path: file, code: f[1][1] });
241
+ } else if (p[0] === "u") s.conflicted.push({ path: p.split(" ").slice(10).join(" "), code: p.split(" ")[1] });
242
+ else if (p[0] === "?") s.untracked.push({ path: p.slice(2), code: "?" });
243
+ }
244
+ const changed = [...s.conflicted, ...s.unstaged, ...s.untracked, ...s.staged].slice(0, 300);
245
+ const times = (await Promise.all(changed.map((f) => fs.promises.stat(path.join(dir, f.path)).then((st) => st.mtimeMs, () => 0)))).filter(Boolean);
246
+ if (times.length) { s.firstFileChange = Math.min(...times); s.lastFileChange = Math.max(...times); }
247
+ return s;
248
+ }
249
+
250
+ // ---------------------------------------------------------------- environments
251
+ const envCache = new Map();
252
+ async function resolveEnv(env) {
253
+ const hit = envCache.get(env.name);
254
+ if (hit && Date.now() - hit.at < CONFIG.envCacheMs) return hit.value;
255
+ const value = await resolveEnvNow(env);
256
+ envCache.set(env.name, { at: Date.now(), value });
257
+ return value;
258
+ }
259
+ async function resolveEnvNow(env) {
260
+ const source = env.branch ? `branch ${env.branch}` : env.tag ? `tag ${env.tag}` : env.url ? env.url : env.command ? env.command.join(" ") : "not configured";
261
+ const r = { name: env.name, source, sha: null, raw: null, version: null, deployedAt: null, verified: null, error: null };
262
+ try {
263
+ let raw;
264
+ if (env.branch) { raw = (await git(["rev-parse", "--verify", `${env.branch}^{commit}`])).trim(); r.version = env.branch; }
265
+ else if (env.tag) {
266
+ const out = (await git(["for-each-ref", "--sort=-creatordate", "--count=1", "--format=%(refname:short)%00%(objectname)%00%(*objectname)%00%(creatordate:unix)", `refs/tags/${env.tag}`])).trim();
267
+ if (!out) throw new Error(`no tag matches ${env.tag}`);
268
+ const [name, obj, peeled, date] = out.split("\0");
269
+ raw = peeled || obj; r.version = name; r.deployedAt = Number(date) * 1000;
270
+ } else if (env.url) {
271
+ const res = await fetch(env.url, { signal: AbortSignal.timeout(CONFIG.envTimeoutMs), headers: { accept: "application/json" } });
272
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
273
+ const body = await res.text();
274
+ let json = null;
275
+ try { json = JSON.parse(body); } catch { /* a plain-text body is the commit id itself */ }
276
+ raw = json ? String((env.field || "sha").split(".").reduce((o, k) => o?.[k], json) ?? "") : body.trim();
277
+ r.version = json?.version ?? null;
278
+ r.deployedAt = json?.deployedAt ? Date.parse(json.deployedAt) || null : null;
279
+ } else if (env.command) raw = (await run(env.command[0], env.command.slice(1), { timeout: CONFIG.envTimeoutMs })).trim();
280
+ else throw new Error("no source configured");
281
+ r.raw = raw;
282
+ const id = raw.match(new RegExp(env.match || "\\b([0-9a-f]{7,40})\\b"))?.[1];
283
+ if (!id) throw new Error(`no commit id in "${raw.slice(0, 80)}"`);
284
+ r.sha = (await git(["rev-parse", "--verify", "--quiet", `${id}^{commit}`]).catch(() => { throw new Error(`commit ${id} is not in this clone yet`); })).trim();
285
+ if (!r.version && raw !== r.sha) r.version = raw;
286
+ r.verified = env.verifyUrl ? await fetch(env.verifyUrl, { signal: AbortSignal.timeout(CONFIG.envTimeoutMs) }).then((x) => x.ok, () => false) : true;
287
+ } catch (e) {
288
+ r.sha = null; r.error = e.name === "TimeoutError" ? `no answer in ${CONFIG.envTimeoutMs} ms` : e.cause ? `${e.message}: ${e.cause.code ?? e.cause.message}` : e.message;
289
+ }
290
+ return r;
291
+ }
292
+ async function tagList(pattern) {
293
+ const out = await git(["for-each-ref", "--sort=-creatordate", "--count=30", "--format=%(refname:short)%00%(objectname)%00%(*objectname)%00%(creatordate:unix)", `refs/tags/${pattern}`]);
294
+ return lines(out).map((l) => { const [name, obj, peeled, at] = l.split("\0"); return { name, sha: peeled || obj, at: Number(at) * 1000 }; }).reverse();
295
+ }
296
+
297
+ // ---------------------------------------------------------------- GitHub (optional)
298
+ let gh = { available: null, prs: [], at: 0, error: null };
299
+ async function refreshGh() {
300
+ try {
301
+ const out = await run("gh", ["pr", "list", "--state", "all", "--limit", "100", "--json",
302
+ "number,title,state,isDraft,reviewDecision,headRefName,baseRefName,mergedAt,url,mergeCommit,statusCheckRollup"], { timeout: 30_000 });
303
+ gh = { available: true, prs: JSON.parse(out), at: Date.now(), error: null };
304
+ } catch (e) {
305
+ gh = { available: false, prs: [], at: Date.now(), error: e.code === "ENOENT" ? "gh CLI not installed" : e.message };
306
+ }
307
+ }
308
+ function prFor(branch) {
309
+ const prs = gh.prs.filter((p) => p.headRefName === branch);
310
+ const p = prs.find((x) => x.state === "OPEN") ?? prs[0];
311
+ if (!p) return null;
312
+ const ci = { total: 0, passed: 0, failed: 0, pending: 0 };
313
+ for (const c of p.statusCheckRollup ?? []) {
314
+ const v = String(c.conclusion || c.state || "").toUpperCase();
315
+ ci.total++;
316
+ if (["SUCCESS", "NEUTRAL", "SKIPPED"].includes(v)) ci.passed++;
317
+ else if (["FAILURE", "ERROR", "TIMED_OUT", "CANCELLED", "ACTION_REQUIRED", "STARTUP_FAILURE"].includes(v)) ci.failed++;
318
+ else ci.pending++;
319
+ }
320
+ ci.state = !ci.total ? "none" : ci.failed ? "failing" : ci.pending ? "pending" : "passing";
321
+ return { number: p.number, title: p.title, state: p.state, isDraft: p.isDraft, reviewDecision: p.reviewDecision || null,
322
+ url: p.url, mergedAt: p.mergedAt ? Date.parse(p.mergedAt) : null, base: p.baseRefName, mergeCommit: p.mergeCommit?.oid ?? null, ci };
323
+ }
324
+
325
+ // ---------------------------------------------------------------- delivery
326
+ /** Commits on `target` whose patch equals a commit of the branch, or the whole branch squashed. */
327
+ async function equivalents(tip, target) {
328
+ const map = new Map();
329
+ const mb = (await git(["merge-base", target, tip]).catch(() => "")).trim();
330
+ if (!mb || mb === tip) return map;
331
+ const theirs = await cached(`pid:${mb}:${target}`, () => patchIds(["log", "-p", "--no-ext-diff", "--no-textconv", "--no-merges", "--format=commit %H", "--max-count=2000", `${mb}..${target}`]));
332
+ if (!theirs.size) return map;
333
+ for (const [pid, sha] of await patchIds(["log", "-p", "--no-ext-diff", "--no-textconv", "--no-merges", "--format=commit %H", `${mb}..${tip}`])) if (theirs.has(pid)) map.set(sha, theirs.get(pid));
334
+ for (const pid of (await patchIds(["diff", "--no-ext-diff", "--no-textconv", mb, tip])).keys()) {
335
+ if (!theirs.has(pid)) continue;
336
+ for (const sha of lines(await git(["rev-list", tip, `^${mb}`]))) if (!map.has(sha)) map.set(sha, theirs.get(pid));
337
+ }
338
+ return map;
339
+ }
340
+ async function patchIds(args) {
341
+ const patch = await git(args);
342
+ const ids = new Map();
343
+ if (!patch.trim()) return ids;
344
+ for (const l of lines(await git(["patch-id", "--stable"], { input: patch }))) { const [pid, sha] = l.split(" "); ids.set(pid, sha); }
345
+ return ids;
346
+ }
347
+
348
+ /** The first-parent merge on the remote base that brought each commit in: "PR #551". */
349
+ async function releaseMap(remoteBaseSha) {
350
+ const map = new Map();
351
+ if (!remoteBaseSha) return map;
352
+ for (const l of lines(await git(["log", "--first-parent", "--max-count=100", "--format=%H%x1f%P%x1f%ct%x1f%s", remoteBaseSha]))) {
353
+ const [sha, parents, ct, subject] = l.split("\x1f");
354
+ const pr = subject.match(/Merge pull request #(\d+)/)?.[1];
355
+ const info = { sha, at: Number(ct) * 1000, label: pr ? `PR #${pr}` : subject.match(/Merge branch '([^']+)'/)?.[1] ?? subject.slice(0, 60) };
356
+ map.set(sha, info);
357
+ const ps = parents.split(" ");
358
+ if (ps.length > 1) for (const c of lines(await cached(`brought:${sha}`, () => git(["rev-list", ps[1], `^${ps[0]}`])))) map.set(c, info);
359
+ }
360
+ return map;
361
+ }
362
+
363
+ async function birthPoint(name, tip) {
364
+ const born = lines(await git(["reflog", "show", "--format=%H", `refs/heads/${name}`, "--"]).catch(() => "")).at(-1);
365
+ if (!born) return null;
366
+ return born === tip || (await isAncestor(born, tip)) ? born : null;
367
+ }
368
+
369
+ /** Ahead/behind, own commits since the branch began, and how far each commit has travelled. */
370
+ async function analyzeBranch(ctx, b) {
371
+ const { baseSha, remoteBaseSha, envs } = ctx;
372
+ const a = { mergeBase: null, ahead: 0, behind: 0, start: null, commits: [], commitCount: 0, merged: "unmerged" };
373
+ if (baseSha) {
374
+ a.mergeBase = await cached(`mb:${baseSha}:${b.tip}`, () => git(["merge-base", baseSha, b.tip]).then((s) => s.trim(), () => null));
375
+ [a.behind, a.ahead] = await cached(`lr:${baseSha}:${b.tip}`, () => git(["rev-list", "--left-right", "--count", `${baseSha}...${b.tip}`]).then((s) => s.trim().split(/\s+/).map(Number)));
376
+ }
377
+ // The base branch's own work is what has not reached the last environment yet. Any other
378
+ // branch's is its first-parent line since it was created (its reflog), so work it already
379
+ // landed still shows, with how far it went; failing that, since the merge-base.
380
+ let start = b.isBase ? [...envs].reverse().find((e) => e.sha)?.sha ?? remoteBaseSha
381
+ : b.name ? await cached(`born:${b.name}:${b.tip}`, () => birthPoint(b.name, b.tip)) : null;
382
+ start ??= a.mergeBase ?? b.tip;
383
+ a.start = start;
384
+ if (start !== b.tip) {
385
+ const range = `${start}..${b.tip}`;
386
+ a.commitCount = Number(await cached(`cnt:${range}`, () => git(["rev-list", "--count", "--first-parent", range])));
387
+ a.commits = lines(await cached(`log:${range}`, () => git(["log", "--first-parent", `--max-count=${CONFIG.maxCommits}`, "--format=%H%x1f%an%x1f%ct%x1f%P%x1f%s", range])))
388
+ .map((l) => { const [sha, author, ct, parents, subject] = l.split("\x1f"); return { sha, author, at: Number(ct) * 1000, merge: parents.includes(" "), subject, in: {}, eq: null }; });
389
+ }
390
+ if (a.commits.length) {
391
+ const targets = [["pushed", b.upstreamSha], ["pushed", remoteBaseSha], ["main", baseSha], ["origin", remoteBaseSha], ...envs.map((e) => [`env:${e.name}`, e.sha])];
392
+ for (const [key, sha] of targets) {
393
+ if (!sha) continue;
394
+ const missing = new Set(lines(await cached(`ni:${b.tip}:${start}:${sha}`, () => git(["rev-list", b.tip, `^${start}`, `^${sha}`]))));
395
+ for (const c of a.commits) if (!missing.has(c.sha)) c.in[key] = true;
396
+ }
397
+ // Squash and rebase merges break ancestry: match by patch id instead.
398
+ if (!b.isBase) for (const [key, sha] of [["origin", remoteBaseSha], ["main", baseSha]]) {
399
+ if (!sha || a.commits.every((c) => c.in[key])) continue;
400
+ const eq = await cached(`sq:${b.tip}:${sha}`, () => equivalents(b.tip, sha));
401
+ for (const c of a.commits) if (!c.in[key] && eq.has(c.sha)) { c.in[key] = "squash"; c.eq ??= eq.get(c.sha); }
402
+ }
403
+ // gh says the PR merged (a squash on GitHub): its merge commit stands in for the branch.
404
+ if (b.pr?.state === "MERGED" && b.pr.base === CONFIG.base && b.pr.mergeCommit) {
405
+ for (const c of a.commits) if (!c.in.origin) { c.in.origin = "squash"; c.eq ??= b.pr.mergeCommit; }
406
+ }
407
+ for (const c of a.commits) {
408
+ if (c.in.origin) c.in.pushed ||= true;
409
+ if (c.eq) {
410
+ if (!c.in.main && baseSha && await isAncestor(c.eq, baseSha).catch(() => false)) c.in.main = "squash";
411
+ for (const e of envs) if (e.sha && !c.in[`env:${e.name}`] && await isAncestor(c.eq, e.sha).catch(() => false)) c.in[`env:${e.name}`] = "squash";
412
+ }
413
+ let s = 1;
414
+ if (c.in.pushed) s = b.pr?.state === "OPEN" ? 3 : 2;
415
+ if (c.in.main) s = 4;
416
+ if (c.in.origin) s = Math.max(s, 5);
417
+ envs.forEach((e, i) => { if (c.in[`env:${e.name}`]) s = 6 + i; });
418
+ c.stage = s;
419
+ }
420
+ // Which release brought it in, and the first matching tag of a tag environment.
421
+ const releases = await cached(`rel:${remoteBaseSha}`, () => releaseMap(remoteBaseSha));
422
+ for (const c of a.commits) c.release = releases.get(c.eq ?? c.sha) ?? releases.get(c.sha) ?? null;
423
+ for (const e of envs.filter((x) => x.tagPattern)) {
424
+ for (const t of await cached(`tags:${e.tagPattern}:${e.sha}`, () => tagList(e.tagPattern))) {
425
+ const missing = new Set(lines(await cached(`ni:${b.tip}:${start}:${t.sha}`, () => git(["rev-list", b.tip, `^${start}`, `^${t.sha}`]))));
426
+ for (const c of a.commits) if (!missing.has(c.sha)) (c.firstTag ??= {})[e.name] ??= t.name;
427
+ }
428
+ }
429
+ }
430
+ if (b.isBase) a.merged = "base";
431
+ else if (baseSha && await isAncestor(b.tip, baseSha)) a.merged = "merged";
432
+ else if (remoteBaseSha && await isAncestor(b.tip, remoteBaseSha)) a.merged = "merged (remote)";
433
+ else if (b.pr?.state === "MERGED") a.merged = "merged (squash)";
434
+ else if (a.commits.length && a.commits.filter((c) => !c.merge).every((c) => c.in.main || c.in.origin)) a.merged = "merged (squash)";
435
+ const tally = (pred) => { const cs = a.commits.filter(pred); return { count: cs.length, oldestAt: cs.length ? Math.min(...cs.map((c) => c.at)) : null }; };
436
+ a.unpushed = tally((c) => c.stage === 1); // on this machine only
437
+ a.unlanded = tally((c) => c.stage < 4); // not yet in local base
438
+ return a;
439
+ }
440
+
441
+ // ---------------------------------------------------------------- action engine
442
+ const PRIORITY = { critical: 0, high: 1, medium: 2, low: 3 };
443
+ const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
444
+ const since = (t) => { if (!t) return "a while"; const h = (Date.now() - t) / 36e5; return h < 1 ? `${Math.max(1, Math.round(h * 60))} min` : h < 48 ? `${Math.round(h)} h` : `${Math.round(h / 24)} days`; };
445
+ const cdTo = (p, cmd) => `cd "${p}" && ${cmd}`;
446
+ const train = () => CONFIG.actions.releaseTrain;
447
+ const slug = (s) => String(s).replace(/^.*\//, "").replace(/[^A-Za-z0-9]+/g, "-").replace(/^-|-$/g, "").toLowerCase();
448
+
449
+ // One function per rule. Each returns proposals { target, title, why, command, tab, since, commits }.
450
+ // To add a rule: append { id, priority, category, group?, run } — `group` is the title used when
451
+ // `groupMin` or more of its actions are folded into one. Thresholds belong in CONFIG.actions.
452
+ export const RULES = [
453
+ { id: "conflicts", priority: "critical", category: "Fix",
454
+ run: ({ items }) => items.filter((w) => w.dirty?.conflicted).map((w) => ({ target: w.target, tab: "changes", since: w.dirty.oldestAt,
455
+ title: `Resolve ${plural(w.dirty.conflicted, "conflicted file")} in ${w.label}`,
456
+ why: `Conflicts: ${w.conflictedFiles.slice(0, 3).join(", ")}${w.conflictedFiles.length > 3 ? "…" : ""}`,
457
+ command: cdTo(w.path, "git status && git diff --name-only --diff-filter=U") })) },
458
+ { id: "hotfix", priority: "critical", category: "Fix",
459
+ run: ({ snap }) => (snap.drift?.envs ?? []).filter((e) => e.hotfixCount).map((e) => ({ target: envTarget(e.name), tab: "environments",
460
+ title: `Merge ${e.name} back into ${CONFIG.base}`,
461
+ why: `${plural(e.hotfixCount, "commit")} in ${e.name} are not in ${CONFIG.remote}/${CONFIG.base}: ${e.hotfixes.slice(0, 2).map((h) => h.subject).join("; ")}`,
462
+ command: cdTo(snap.mainPath, `git merge ${snap.envs.find((x) => x.name === e.name)?.short}`), commits: e.hotfixCount })) },
463
+ { id: "ci-failing", priority: "critical", category: "Fix",
464
+ run: ({ items }) => items.filter((w) => w.pr?.state === "OPEN" && w.pr.ci.failed).map((w) => ({ target: w.target, tab: "health",
465
+ title: `Fix failing checks on PR #${w.pr.number} (${w.label})`, why: `${w.pr.ci.failed} of ${w.pr.ci.total} checks failing`,
466
+ command: `gh pr checks ${w.pr.number}` })) },
467
+
468
+ { id: "uncommitted", priority: "high", category: "Commit",
469
+ run: ({ items, now }) => items.filter((w) => w.dirty?.total && w.dirty.oldestAt && now - w.dirty.oldestAt > CONFIG.actions.uncommittedHours * 36e5).map((w) => ({
470
+ target: w.target, tab: "changes", since: w.dirty.oldestAt,
471
+ title: `Commit work in ${w.label}`, why: `${plural(w.dirty.total, "uncommitted file")}, the oldest changed ${since(w.dirty.oldestAt)} ago`,
472
+ command: cdTo(w.path, 'git add -A && git commit -m "…"') })) },
473
+ { id: "unpushed", priority: "high", category: "Sync",
474
+ run: ({ items }) => items.filter((w) => !w.isBase && (train() ? w.unlanded?.count : w.unpushed?.count)).map((w) => {
475
+ const u = train() ? w.unlanded : w.unpushed;
476
+ const done = w.plan?.total && w.plan.pct === 100 ? " The plan is complete." : "";
477
+ if (train()) return { target: w.target, tab: "delivery", since: u.oldestAt, commits: u.count,
478
+ title: `Land ${plural(u.count, "commit")} on ${w.label} with the next sweep`,
479
+ why: `${plural(u.count, "commit")} not in local ${CONFIG.base}, the oldest from ${since(u.oldestAt)} ago.${done}`, command: CONFIG.actions.sweepCommand };
480
+ return { target: w.target, tab: "delivery", since: u.oldestAt, commits: u.count,
481
+ title: w.upstream ? `Push ${plural(u.count, "local commit")} on ${w.label}` : `Push ${w.label} (never pushed)`,
482
+ why: `${plural(u.count, "commit")} not on ${CONFIG.remote}, the oldest from ${since(u.oldestAt)} ago.${done}`,
483
+ command: cdTo(w.path, w.upstream ? "git push" : `git push -u ${CONFIG.remote} ${w.branch}`) };
484
+ }) },
485
+ { id: "main-ahead", priority: "high", category: "Sync",
486
+ run: ({ snap }) => (snap.drift?.local?.ahead ? [{ target: repoTarget(), tab: "environments", commits: snap.drift.local.ahead,
487
+ title: train() ? `Ship ${plural(snap.drift.local.ahead, "commit")} waiting in local ${CONFIG.base}` : `Push ${CONFIG.base}`,
488
+ why: `Local ${CONFIG.base} is ${snap.drift.local.ahead} ahead of ${CONFIG.remote}/${CONFIG.base}`,
489
+ command: train() ? CONFIG.actions.sweepCommand : cdTo(snap.mainPath, `git push ${CONFIG.remote} ${CONFIG.base}`) }] : []) },
490
+ { id: "pr-ready", priority: "high", category: "Ship",
491
+ run: ({ items }) => items.filter((w) => w.pr?.state === "OPEN" && !w.pr.isDraft && w.pr.reviewDecision === "APPROVED" && w.pr.ci.state === "passing").map((w) => ({
492
+ target: w.target, tab: "delivery", title: `Merge PR #${w.pr.number} (${w.label})`, why: "Approved and every check passes", command: `gh pr merge ${w.pr.number}` })) },
493
+ { id: "plan-done", priority: "high", category: "Review",
494
+ run: ({ items }) => (train() ? [] : items.filter((w) => !w.isBase && w.plan?.total && w.plan.pct === 100 && !w.pr && !/^merged/.test(w.merged)).map((w) => ({
495
+ target: w.target, tab: "plan", title: `Open a PR for ${w.label}`, why: `Plan complete (${w.plan.done}/${w.plan.total}) and no pull request`,
496
+ command: cdTo(w.path, "gh pr create --fill") }))) },
497
+ { id: "promote", priority: "high", category: "Ship",
498
+ run: ({ snap }) => (snap.drift?.between ?? []).filter((b) => b.ahead && snap.envs.find((e) => e.name === b.from)?.verified).map((b) => ({
499
+ target: envTarget(b.to), tab: "environments", commits: b.ahead, title: `Promote ${b.from} to ${b.to}`,
500
+ why: `${b.from} is verified and ${plural(b.ahead, "commit")} ahead of ${b.to}`, command: train() ? CONFIG.actions.sweepCommand : CONFIG.actions.deployCommand })) },
501
+
502
+ { id: "behind-base", priority: "medium", category: "Sync",
503
+ run: ({ items }) => items.filter((w) => !w.isBase && w.behind > CONFIG.actions.behindBase && w.unlanded?.count).map((w) => ({
504
+ target: w.target, tab: "health", title: `Bring ${CONFIG.base} into ${w.label}`, why: `${w.behind} commits behind ${CONFIG.base}`,
505
+ command: cdTo(w.path, `git merge ${CONFIG.base}`) })) },
506
+ { id: "changes-requested", priority: "medium", category: "Review",
507
+ run: ({ items }) => items.filter((w) => w.pr?.state === "OPEN" && w.pr.reviewDecision === "CHANGES_REQUESTED").map((w) => ({
508
+ target: w.target, tab: "delivery", title: `Address review on PR #${w.pr.number} (${w.label})`, why: "Changes requested", command: `gh pr view ${w.pr.number} --comments` })) },
509
+ { id: "deploy", priority: "medium", category: "Ship",
510
+ run: ({ snap }) => { const e = snap.drift?.envs?.[0]; return e?.behind ? [{ target: envTarget(e.name), tab: "environments", commits: e.behind, since: e.groups.at(-1)?.at,
511
+ title: `Deploy ${plural(e.behind, "commit")} to ${e.name}`, why: `${CONFIG.remote}/${CONFIG.base} is ${e.behind} ahead of ${e.name}: ${e.groups.slice(0, 3).map((g) => g.label).join(", ")}`,
512
+ command: train() ? CONFIG.actions.sweepCommand : CONFIG.actions.deployCommand }] : []; } },
513
+ { id: "main-behind", priority: "medium", category: "Sync",
514
+ run: ({ snap }) => (snap.drift?.local?.behind ? [{ target: repoTarget(), tab: "environments", commits: snap.drift.local.behind,
515
+ title: `Update local ${CONFIG.base}`, why: `Local ${CONFIG.base} is ${snap.drift.local.behind} behind ${CONFIG.remote}/${CONFIG.base}${train() ? "; the next sweep takes it" : ""}`,
516
+ command: train() ? CONFIG.actions.sweepCommand : cdTo(snap.mainPath, "git pull --ff-only") }] : []) },
517
+ { id: "plan-stalled", priority: "medium", category: "Plan",
518
+ run: ({ items, now }) => { const d = CONFIG.actions.planStalledDays * 864e5; return items.filter((w) => w.plan?.total && w.plan.pct < 100 && w.plan.lastChangeAt && now - w.plan.lastChangeAt > d && w.lastActivityAt && now - w.lastActivityAt < d).map((w) => ({
519
+ target: w.target, tab: "plan", since: w.plan.lastChangeAt,
520
+ title: `Update the plan or unblock: "${(w.plan.current?.text ?? "").slice(0, 80)}"`,
521
+ why: `No step ticked in ${w.label} for ${since(w.plan.lastChangeAt)} while the branch is active (${w.plan.pct}%)`,
522
+ command: CONFIG.actions.openCommand.replace("{file}", `${w.path}/${w.plan.path}`) })); } },
523
+
524
+ { id: "no-plan", priority: "low", category: "Plan", group: (n) => `Add a plan to ${n} worktrees`,
525
+ run: ({ items }) => items.filter((w) => w.kind === "worktree" && !w.isBase && !w.detached && !w.plan && (w.unlanded?.count || w.dirty?.total)).map((w) => ({
526
+ target: w.target, tab: "plan", title: `Add a plan to ${w.label}`, why: "Work in progress and no plan file",
527
+ // a branch that predates the template lacks it: copy it from the dashboard's own checkout
528
+ command: cdTo(w.path, `cp "${fs.existsSync(path.join(w.path, CONFIG.actions.planTemplate)) ? CONFIG.actions.planTemplate : `${REPO}/${CONFIG.actions.planTemplate}`}" "${CONFIG.actions.planTarget.replace("{date}", new Date().toISOString().slice(0, 10)).replace("{slug}", slug(w.label))}"`) })) },
529
+ { id: "merged-cleanup", priority: "low", category: "Cleanup", group: (n) => `Delete ${n} merged branches`,
530
+ run: ({ items, now }) => items.filter((w) => !w.isBase && !w.detached && /^merged/.test(w.merged) && !w.dirty?.total && !w.unlanded?.count
531
+ && (!w.lastActivityAt || now - w.lastActivityAt > CONFIG.actions.cleanupQuietHours * 36e5)).map((w) => ({
532
+ target: w.target, tab: "health", since: w.lastActivityAt,
533
+ title: w.kind === "worktree" ? `Remove the merged worktree ${w.label}` : `Delete the merged branch ${w.label}`,
534
+ why: `${w.merged} into ${CONFIG.base}; quiet for ${since(w.lastActivityAt)}`,
535
+ command: train() ? CONFIG.actions.cleanCommand : w.kind === "worktree" ? `git worktree remove "${w.path}" && git branch -${w.merged === "merged" ? "d" : "D"} ${w.branch}` : `git branch -${w.merged === "merged" ? "d" : "D"} ${w.branch}` })) },
536
+ { id: "stale", priority: "low", category: "Review", group: (n) => `Review ${n} stale branches`,
537
+ run: ({ items }) => items.filter((w) => !w.isBase && w.stale && !w.pr && !/^merged/.test(w.merged)).map((w) => ({
538
+ target: w.target, tab: "commits", since: w.lastActivityAt, title: `Finish or close ${w.label}`, why: `No commit or file change for ${since(w.lastActivityAt)} and no PR`,
539
+ command: `git log --oneline ${CONFIG.base}..${w.branch ?? w.head}` })) },
540
+ { id: "worktree-state", priority: "low", category: "Cleanup",
541
+ run: ({ items }) => items.filter((w) => w.prunable || w.locked).map((w) => ({ target: w.target, tab: "health",
542
+ title: w.prunable ? `Prune the missing worktree ${w.label}` : `Unlock ${w.label}`, why: w.prunable || w.locked,
543
+ command: w.prunable ? "git worktree prune" : `git worktree unlock "${w.path}"` })) },
544
+ { id: "old-stash", priority: "low", category: "Cleanup", group: (n) => `Review ${n} old stash entries`,
545
+ run: ({ snap, now }) => snap.stash.filter((s) => now - s.at > CONFIG.actions.stashDays * 864e5).map((s) => ({
546
+ target: { type: "stash", key: s.ref, label: s.ref }, tab: null, since: s.at, title: `Review or drop ${s.ref}`,
547
+ why: `${since(s.at)} old: ${s.subject}`, command: `git stash show -p ${s.ref} # then: git stash drop ${s.ref}` })) },
548
+ ];
549
+ const envTarget = (name) => ({ type: "environment", key: name, label: name });
550
+ const repoTarget = () => ({ type: "repo", key: CONFIG.base, label: `local ${CONFIG.base}` });
551
+
552
+ /** Runs every rule; one failing rule becomes an error, never a missing snapshot. */
553
+ export function proposeActions(snap, details, now = Date.now()) {
554
+ const items = [
555
+ ...snap.worktrees.filter((w) => !w.error).map((w) => ({ ...w, kind: "worktree", label: w.branch || w.key, isBase: w.branch === CONFIG.base,
556
+ target: { type: "worktree", key: w.key, label: w.branch || w.key }, conflictedFiles: (details.get(w.key)?.files?.conflicted ?? []).map((f) => f.path) })),
557
+ ...snap.branches.filter((b) => !b.remote && !b.worktree && !b.error).map((b) => ({ ...b, kind: "branch", label: b.name, branch: b.name, path: snap.mainPath, isBase: b.name === CONFIG.base,
558
+ target: { type: "branch", key: b.name, label: b.name } })),
559
+ ];
560
+ const out = [], errors = [];
561
+ for (const rule of RULES) {
562
+ if (CONFIG.actions.disabled.includes(rule.id)) continue;
563
+ try {
564
+ for (const p of rule.run({ snap, items, now })) {
565
+ out.push({ id: `${rule.id}:${p.target.type}:${p.target.key}`, rule: rule.id, priority: rule.priority, category: rule.category,
566
+ link: p.target.type === "worktree" ? `#wt=${encodeURIComponent(p.target.key)}&tab=${p.tab ?? "summary"}` : p.target.type === "branch" ? "#tab=branches" : "#tab=environments",
567
+ since: p.since ?? null, commits: p.commits ?? 0, ...p });
568
+ }
569
+ } catch (e) { errors.push(`rule ${rule.id}: ${e.message}`); }
570
+ }
571
+ out.sort((a, b) => PRIORITY[a.priority] - PRIORITY[b.priority] || (a.since ?? Infinity) - (b.since ?? Infinity) || b.commits - a.commits);
572
+ return { actions: out, errors };
573
+ }
574
+
575
+ let actionState = (() => { try { return { dismissed: {}, snoozed: {}, seen: {}, ...JSON.parse(fs.readFileSync(ACTIONS_FILE, "utf8")) }; } catch { return { dismissed: {}, snoozed: {}, seen: {} }; } })();
576
+ const saveActionState = () => fs.writeFileSync(ACTIONS_FILE, JSON.stringify(actionState, null, 1));
577
+ /** Marks dismissed and snoozed actions hidden, forgets dismissals of long-resolved actions, and folds groups. */
578
+ function presentActions(raw, now = Date.now()) {
579
+ const ids = new Set(raw.map((a) => a.id));
580
+ let changed = false;
581
+ for (const id of ids) if (actionState.dismissed[id] || actionState.snoozed[id]) actionState.seen[id] = now;
582
+ for (const id of Object.keys(actionState.dismissed)) {
583
+ if (!ids.has(id) && now - (actionState.seen[id] ?? actionState.dismissed[id]) > CONFIG.actions.dismissForgetHours * 36e5) { delete actionState.dismissed[id]; delete actionState.seen[id]; changed = true; }
584
+ }
585
+ for (const [id, until] of Object.entries(actionState.snoozed)) if (until < now) { delete actionState.snoozed[id]; delete actionState.seen[id]; changed = true; }
586
+ if (changed) saveActionState();
587
+ const all = raw.map((a) => ({ ...a, hidden: actionState.dismissed[a.id] ? "dismissed" : actionState.snoozed[a.id] ? "snoozed" : null, snoozedUntil: actionState.snoozed[a.id] ?? null }));
588
+ const visible = all.filter((a) => !a.hidden), list = [];
589
+ const done = new Set();
590
+ for (const a of visible) {
591
+ if (done.has(a.id)) continue;
592
+ const rule = RULES.find((r) => r.id === a.rule);
593
+ const same = rule.group ? visible.filter((x) => x.rule === a.rule) : [];
594
+ if (same.length >= CONFIG.actions.groupMin) {
595
+ same.forEach((x) => done.add(x.id));
596
+ list.push({ ...a, id: `${a.rule}:*`, grouped: true, title: rule.group(same.length), why: same.map((x) => x.target.label).join(", "),
597
+ target: { type: "group", key: a.rule, label: plural(same.length, "target") }, link: "#tab=actions", commits: same.reduce((n, x) => n + x.commits, 0),
598
+ command: [...new Set(same.map((x) => x.command))].join("\n"), items: same });
599
+ } else { done.add(a.id); list.push(a); }
600
+ }
601
+ const counts = { critical: 0, high: 0, medium: 0, low: 0 };
602
+ for (const a of visible) counts[a.priority]++;
603
+ return { list, hidden: all.filter((a) => a.hidden), all, counts };
604
+ }
605
+
606
+ // ---------------------------------------------------------------- snapshot
607
+ const statusCache = new Map(); // worktree path → { at, head, value }
608
+ const marked = new Set(); // worktree paths whose files changed since their last status
609
+ const planCache = new Map();
610
+ const diffCache = new Map();
611
+ let history = (() => { try { return JSON.parse(fs.readFileSync(HISTORY_FILE, "utf8")); } catch { return {}; } })();
612
+ let historyTimer = null;
613
+ let lastFetch = { at: null, ok: null, error: null };
614
+
615
+ async function getStatus(wt) {
616
+ const hit = statusCache.get(wt.path);
617
+ if (hit && !marked.has(wt.path) && hit.head === wt.head && Date.now() - hit.at < CONFIG.statusMaxAgeMs) return hit;
618
+ marked.delete(wt.path);
619
+ const entry = { at: Date.now(), head: wt.head, value: await readStatus(wt.path) };
620
+ statusCache.set(wt.path, entry);
621
+ return entry;
622
+ }
623
+
624
+ function globOne(root, pattern) {
625
+ if (!pattern.includes("*")) return fs.existsSync(path.join(root, pattern)) ? pattern : null;
626
+ const dir = path.posix.dirname(pattern), re = new RegExp(`^${path.posix.basename(pattern).replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*")}$`);
627
+ try { return fs.readdirSync(path.join(root, dir)).sort().map((f) => `${dir}/${f}`).find((f) => re.test(path.posix.basename(f)) && fs.statSync(path.join(root, f)).isFile()) ?? null; } catch { return null; }
628
+ }
629
+ async function findPlan(wt, status, a) {
630
+ for (const p of CONFIG.planFiles) { const hit = globOne(wt.path, p); if (hit) return hit; }
631
+ if (!CONFIG.planDir) return null;
632
+ // `*-kb-content/` and `*-evidence/` folders hold staged knowledge-base documents, not plans
633
+ const isPlan = (p) => p.startsWith(CONFIG.planDir) && p.endsWith(".md") && !/(^|\/)README\.md$/i.test(p) && !/TEMPLATE/.test(p) && !/-(kb-content|evidence)\//.test(p);
634
+ const editing = [...status.unstaged, ...status.staged, ...status.untracked].map((f) => f.path).find(isPlan);
635
+ if (editing) return editing;
636
+ if (!a || a.start === wt.head) return null;
637
+ const touched = lines(await cached(`plans:${a.start}:${wt.head}`, () => git(["log", "--first-parent", "--no-merges", "--format=", "--name-only", `${a.start}..${wt.head}`, "--", CONFIG.planDir])));
638
+ return touched.find((p) => isPlan(p) && fs.existsSync(path.join(wt.path, p))) ?? null;
639
+ }
640
+ function readPlan(wt, rel) {
641
+ const abs = path.join(wt.path, rel), st = fs.statSync(abs), key = `${abs}:${st.mtimeMs}:${st.size}`;
642
+ if (planCache.get(abs)?.key !== key) planCache.set(abs, { key, plan: { path: rel, ...parsePlan(fs.readFileSync(abs, "utf8")) } });
643
+ return planCache.get(abs).plan;
644
+ }
645
+ function recordHistory(key, pct) {
646
+ const arr = (history[key] ??= []);
647
+ if (arr.at(-1)?.[1] === pct) return arr;
648
+ arr.push([Date.now(), pct]);
649
+ if (arr.length > 200) arr.splice(0, arr.length - 200);
650
+ clearTimeout(historyTimer);
651
+ historyTimer = setTimeout(() => fs.writeFile(HISTORY_FILE, JSON.stringify(history), () => {}), 1000);
652
+ return arr;
653
+ }
654
+ async function diffStat(wt, mergeBase, statusAt) {
655
+ const key = `${mergeBase}:${statusAt}:${wt.head}`;
656
+ if (diffCache.get(wt.path)?.key === key) return diffCache.get(wt.path).value;
657
+ const value = { files: 0, insertions: 0, deletions: 0, topDirs: [] };
658
+ if (mergeBase) {
659
+ const dirs = new Map();
660
+ for (const l of lines(await git(["diff", "--numstat", mergeBase], { cwd: wt.path }))) {
661
+ const [ins, del, ...rest] = l.split("\t");
662
+ const file = rest.join("\t").replace(/\{(.*) => (.*)\}/, "$2").replace(/^.* => /, "");
663
+ value.files++; value.insertions += Number(ins) || 0; value.deletions += Number(del) || 0;
664
+ const dir = file.includes("/") ? file.split("/").slice(0, 2).join("/").replace(/\/[^/]*\.[^/]*$/, "") : "(root)";
665
+ dirs.set(dir, (dirs.get(dir) ?? 0) + (Number(ins) || 0) + (Number(del) || 0) + 1);
666
+ }
667
+ value.topDirs = [...dirs].sort((x, y) => y[1] - x[1]).slice(0, 8).map(([dir, weight]) => ({ dir, weight }));
668
+ }
669
+ diffCache.set(wt.path, { key, value });
670
+ return value;
671
+ }
672
+ const parseTrack = (t) => ({ gone: /gone/.test(t), ahead: Number(t.match(/ahead (\d+)/)?.[1] ?? 0), behind: Number(t.match(/behind (\d+)/)?.[1] ?? 0) });
673
+ const shortSha = (s) => (s ? s.slice(0, 9) : null);
674
+ function hash(s) { let h = 2166136261; for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 16777619); return (h >>> 0).toString(36); }
675
+
676
+ /** `only`: one worktree's path — just its branch, no other branch, remote, drift, history or watcher (collectOne). */
677
+ async function collect(only = null) {
678
+ const now = Date.now(), errors = [];
679
+ const [all, refs, stash] = await Promise.all([listWorktrees(), readRefs(), readStash()]);
680
+ const same = (a, b) => { const n = (x) => path.resolve(x).replace(/\\/g, "/").replace(/\/$/, ""); return process.platform === "win32" ? n(a).toLowerCase() === n(b).toLowerCase() : n(a) === n(b); };
681
+ const worktrees = only ? all.filter((w) => same(w.path, only)) : all;
682
+ if (!only) syncWatchers(worktrees);
683
+ const sha = (ref) => refs.get(ref)?.sha ?? null;
684
+ const baseSha = sha(`refs/heads/${CONFIG.base}`), remoteBaseSha = sha(`refs/remotes/${CONFIG.remote}/${CONFIG.base}`);
685
+ if (!baseSha) errors.push(`base branch ${CONFIG.base} not found`);
686
+ const envs = (await Promise.all(CONFIG.envs.map(resolveEnv))).map((e, i) => ({ ...e, tagPattern: CONFIG.envs[i].tag ?? null }));
687
+ const stages = [["uncommitted", "Uncommitted"], ["local", "Local"], ["pushed", "Pushed"], ["pr", "PR"], ["main", "Merged local"], ["origin", "Merged remote"],
688
+ ...envs.map((e) => [`env:${e.name}`, e.name[0].toUpperCase() + e.name.slice(1)])].map(([key, label]) => ({ key, label }));
689
+ const ctx = { baseSha, remoteBaseSha, envs };
690
+ const staleMs = CONFIG.staleDays * 864e5;
691
+ const wtByBranch = new Map(worktrees.filter((w) => w.branch).map((w) => [w.branch, w]));
692
+ const mainPath = all.find((w) => w.isMain)?.path ?? REPO;
693
+ const labels = ["uncommitted", "local only", "pushed", "in a PR", `in local ${CONFIG.base}`, `in ${CONFIG.remote}/${CONFIG.base}`, ...envs.map((e) => `in ${e.name}`)];
694
+ const stageText = (count, view) => { const parts = view.counts.map((n, i) => (n ? `${n} ${labels[i]}` : null)).filter(Boolean); return `${plural(count, "commit")}${parts.length ? `: ${parts.join(", ")}` : ""}`; };
695
+
696
+ // Every local branch, with or without a worktree.
697
+ const branches = new Map();
698
+ await Promise.all([...refs.values()].filter((r) => r.ref.startsWith("refs/heads/") && (!only || wtByBranch.has(r.ref.slice(11)))).map(async (r) => {
699
+ const name = r.ref.slice(11), up = r.upstream ? refs.get(r.upstream) : null;
700
+ const b = { name, tip: r.sha, at: r.at, subject: r.subject, isBase: name === CONFIG.base, upstream: r.upstream ? r.upstream.replace(/^refs\/remotes\//, "") : null,
701
+ upstreamSha: up?.sha ?? null, track: parseTrack(r.track), pr: prFor(name), a: null, error: null };
702
+ try { b.a = await analyzeBranch(ctx, b); } catch (e) { b.error = e.message; }
703
+ branches.set(name, b);
704
+ }));
705
+
706
+ const cards = [], details = new Map();
707
+ await Promise.all(worktrees.map(async (wt) => {
708
+ const card = { key: wt.key, branch: wt.branch, detached: wt.detached, isMain: wt.isMain, path: wt.path, shortPath: wt.path.split("/").slice(-2).join("/"),
709
+ head: shortSha(wt.head), locked: wt.locked, prunable: wt.prunable, error: null };
710
+ const detail = { errors: [] };
711
+ try {
712
+ let b = wt.branch ? branches.get(wt.branch) : null;
713
+ if (!b) { b = { name: null, tip: wt.head, isBase: false, pr: null, track: { gone: false, ahead: 0, behind: 0 }, upstream: null }; b.a = await analyzeBranch(ctx, b); }
714
+ if (b.error) throw new Error(b.error);
715
+ const a = b.a;
716
+ if (wt.prunable || !fs.existsSync(wt.path)) throw new Error(`folder missing${wt.prunable ? `: ${wt.prunable}` : ""}`);
717
+ const st = await getStatus(wt), s = st.value;
718
+ const dirtyTotal = s.staged.length + s.unstaged.length + s.untracked.length + s.conflicted.length;
719
+ const ref = wt.branch ? refs.get(`refs/heads/${wt.branch}`) : null;
720
+ const last = a.commits[0] ?? (ref ? { sha: ref.sha, subject: ref.subject, at: ref.at, author: null } : null);
721
+ const lastActivityAt = Math.max(last?.at || 0, s.lastFileChange || 0) || null;
722
+ let plan = null;
723
+ try {
724
+ const rel = await findPlan(wt, s, a);
725
+ if (rel) {
726
+ plan = readPlan(wt, rel);
727
+ detail.history = plan.total && !only ? recordHistory(`${REPO}|${wt.path}|${rel}`, plan.pct) : [];
728
+ }
729
+ } catch (e) { detail.errors.push(`plan: ${e.message}`); }
730
+ const items = a.commits.map((c) => c.stage);
731
+ if (dirtyTotal) items.push(0);
732
+ const view = stageView(items, stages.length);
733
+ Object.assign(card, {
734
+ ahead: a.ahead, behind: a.behind,
735
+ upstream: b.upstream ? { name: b.upstream, ...b.track } : null,
736
+ dirty: { staged: s.staged.length, unstaged: s.unstaged.length, untracked: s.untracked.length, conflicted: s.conflicted.length, total: dirtyTotal, oldestAt: s.firstFileChange },
737
+ last: last ? { short: shortSha(last.sha), subject: last.subject, author: last.author, at: last.at } : null,
738
+ lastActivityAt, stale: !!lastActivityAt && now - lastActivityAt > staleMs,
739
+ commits24h: a.commits.filter((c) => now - c.at < 864e5).length, commits7d: a.commits.filter((c) => now - c.at < 7 * 864e5).length,
740
+ unpushed: a.unpushed, unlanded: a.unlanded, merged: a.merged,
741
+ plan: plan ? { path: plan.path, title: plan.title, total: plan.total, done: plan.done, doing: plan.doing, pct: plan.pct, current: plan.current, lastChangeAt: detail.history?.at(-1)?.[0] ?? null } : null,
742
+ stage: { ...view, text: stageText(a.commitCount, view), merged: a.merged },
743
+ pr: b.pr,
744
+ });
745
+ const perDay = Array(30).fill(0);
746
+ for (const c of a.commits) { const d = Math.floor((now - c.at) / 864e5); if (d < 30) perDay[29 - d]++; }
747
+ const cap = (list) => list.slice(0, 300);
748
+ Object.assign(detail, {
749
+ base: CONFIG.base, mergeBase: shortSha(a.mergeBase), start: shortSha(a.start), headFull: wt.head, statusAt: st.at,
750
+ files: { staged: cap(s.staged), unstaged: cap(s.unstaged), untracked: cap(s.untracked), conflicted: cap(s.conflicted) },
751
+ diff: await diffStat(wt, a.mergeBase, st.at).catch((e) => (detail.errors.push(`diff: ${e.message}`), null)),
752
+ commitCount: a.commitCount,
753
+ commits: a.commits.slice(0, 30).map((c) => ({ sha: shortSha(c.sha), subject: c.subject, author: c.author, at: c.at, merge: c.merge, stage: c.stage, in: c.in, eq: shortSha(c.eq), release: c.release, firstTag: c.firstTag ?? null })),
754
+ perDay, stash: stash.filter((x) => x.branch === wt.branch), plan,
755
+ });
756
+ } catch (e) { card.error = e.message; detail.errors.push(e.message); }
757
+ card.hash = hash(JSON.stringify(card) + JSON.stringify({ ...detail, statusAt: 0 }));
758
+ cards.push(card);
759
+ details.set(wt.key, { ...card, ...detail });
760
+ }));
761
+ cards.sort((x, y) => Number(y.isMain) - Number(x.isMain) || x.key.localeCompare(y.key));
762
+
763
+ // The branch table: local branches, and remote ones for the --all toggle.
764
+ const table = [...branches.values()].map((b) => {
765
+ const wt = wtByBranch.get(b.name), a = b.a;
766
+ const items = a ? a.commits.map((c) => c.stage) : [];
767
+ const card = wt ? cards.find((c) => c.key === wt.key) : null;
768
+ if (card?.dirty?.total) items.push(0);
769
+ const view = stageView(items, stages.length), lastActivityAt = card?.lastActivityAt ?? b.at, stale = now - lastActivityAt > staleMs;
770
+ const merged = a?.merged ?? "unknown";
771
+ const cleanup = b.isBase ? [] : [stale && "stale", /^merged/.test(merged) && "merged", b.track.gone && "upstream gone"].filter(Boolean);
772
+ return { name: b.name, remote: false, sha: shortSha(b.tip), head: shortSha(b.tip), at: b.at, lastActivityAt, subject: b.subject, ahead: a?.ahead ?? null, behind: a?.behind ?? null, merged,
773
+ worktree: wt?.key ?? null, upstream: b.upstream, upstreamGone: b.track.gone, stale, cleanup, column: view.column, counts: view.counts,
774
+ commitCount: a?.commitCount ?? 0, unpushed: a?.unpushed ?? null, unlanded: a?.unlanded ?? null, stageText: a ? stageText(a.commitCount, view) : "",
775
+ pr: b.pr, error: b.error };
776
+ });
777
+ for (const r of only ? [] : [...refs.values()].filter((x) => x.ref.startsWith("refs/remotes/") && !x.ref.endsWith("/HEAD"))) {
778
+ let ahead = null, behind = null, merged = "unknown";
779
+ try {
780
+ if (baseSha) [behind, ahead] = await cached(`lr:${baseSha}:${r.sha}`, () => git(["rev-list", "--left-right", "--count", `${baseSha}...${r.sha}`]).then((s) => s.trim().split(/\s+/).map(Number)));
781
+ merged = (baseSha && await isAncestor(r.sha, baseSha)) || (remoteBaseSha && await isAncestor(r.sha, remoteBaseSha)) ? "merged" : "unmerged";
782
+ } catch (e) { errors.push(`${r.ref}: ${e.message}`); }
783
+ const stale = now - r.at > staleMs;
784
+ table.push({ name: r.ref.slice(13), remote: true, sha: shortSha(r.sha), at: r.at, lastActivityAt: r.at, subject: r.subject, ahead, behind, merged, worktree: null, stale,
785
+ cleanup: r.ref.endsWith(`/${CONFIG.base}`) ? [] : [stale && "stale", merged === "merged" && "merged"].filter(Boolean), column: null, counts: [] });
786
+ }
787
+
788
+ const drift = only ? null : await releaseDrift(ctx).catch((e) => (errors.push(`drift: ${e.message}`), null));
789
+ const planned = new Map();
790
+ for (const c of cards) if (c.plan?.total && !(planned.get(c.plan.path)?.done > c.plan.done)) planned.set(c.plan.path, c.plan); // a plan shared by worktrees counts once
791
+ const prodish = [...envs].reverse().find((e) => e.sha);
792
+ const snapshot = {
793
+ repo: REPO, base: CONFIG.base, remote: CONFIG.remote, mainPath, stages, checkedAt: now, generatedAt: now,
794
+ fetch: { ...lastFetch, intervalMs: CONFIG.fetchIntervalMs }, gh: { available: gh.available, error: gh.error, at: gh.at },
795
+ envs: envs.map((e) => ({ ...e, short: shortSha(e.sha), waiting: drift?.envs.find((d) => d.name === e.name)?.behind ?? null })),
796
+ summary: {
797
+ worktrees: cards.length,
798
+ activeBranches: table.filter((b) => !b.remote && now - b.at < 7 * 864e5).length,
799
+ dirty: cards.filter((c) => c.dirty?.total).length,
800
+ conflicts: cards.filter((c) => c.dirty?.conflicted).length,
801
+ stale: cards.filter((c) => c.stale).length,
802
+ openPrs: gh.available ? gh.prs.filter((p) => p.state === "OPEN").length : null,
803
+ waitingForProd: prodish && drift ? drift.envs.find((d) => d.name === prodish.name)?.behind ?? null : null,
804
+ prodName: prodish?.name ?? null,
805
+ planDone: [...planned.values()].reduce((n, p) => n + p.done, 0),
806
+ planTotal: [...planned.values()].reduce((n, p) => n + p.total, 0),
807
+ },
808
+ prompt: CONFIG.actions.prompt + (train() ? ` ${CONFIG.actions.trainPrompt}` : ""),
809
+ worktrees: cards, branches: table, drift, stash, errors,
810
+ hourly: (() => { try { return JSON.parse(fs.readFileSync(path.join(HERE, "reports", "latest.json"), "utf8")); } catch { return null; } })(), // written by the hourly check
811
+ };
812
+ const proposed = proposeActions(snapshot, details, now);
813
+ errors.push(...proposed.errors);
814
+ return { snapshot, details, rawActions: proposed.actions };
815
+ }
816
+
817
+ /**
818
+ * One worktree's detail — what `/api/worktree/<key>` gives the page — with its own actions and the
819
+ * stage names, for `@futuvara/connect report`, which sends it to Hub › Projects › Terminals
820
+ * (docs/plans/2026-11-10-terminals-mcp-sessions.md, 6.1). No absolute path leaves: the folder
821
+ * that holds the worktrees and the home folder are cut out, since they name the person.
822
+ */
823
+ export async function collectOne(dir) {
824
+ REPO = (await git(["rev-parse", "--show-toplevel"], { cwd: dir })).trim();
825
+ const { snapshot, details, rawActions } = await collect(REPO);
826
+ const card = snapshot.worktrees[0];
827
+ if (!card) throw new Error(`${REPO} is not one of this repository's worktrees`);
828
+ const report = { ...details.get(card.key), actions: rawActions.filter((a) => a.target.key === card.key), stages: snapshot.stages, base: CONFIG.base, generatedAt: snapshot.generatedAt };
829
+ let json = JSON.stringify(report);
830
+ const cut = (from, to) => { for (const v of [from.replace(/\\/g, "/"), JSON.stringify(from.replace(/\//g, "\\")).slice(1, -1)]) json = json.split(v).join(to); };
831
+ for (const p of new Set([path.dirname(card.path), path.dirname(snapshot.mainPath)])) {
832
+ cut(p + "/", "");
833
+ cut(p, "");
834
+ }
835
+ cut(os.homedir(), "~");
836
+ return JSON.parse(json);
837
+ }
838
+
839
+ async function releaseDrift({ baseSha, remoteBaseSha, envs }) {
840
+ const count = (from, to) => git(["rev-list", "--count", `${from}..${to}`]).then(Number);
841
+ const groups = async (from, to) => {
842
+ const out = [];
843
+ for (const l of lines(await git(["log", "--first-parent", "--max-count=50", "--format=%H%x1f%P%x1f%ct%x1f%s", `${from}..${to}`]))) {
844
+ const [sha, parents, ct, subject] = l.split("\x1f"), ps = parents.split(" ");
845
+ const g = { sha: shortSha(sha), at: Number(ct) * 1000, subject, label: subject, commits: 1, branches: [] };
846
+ const pr = subject.match(/Merge pull request #(\d+) from (\S+)/), br = subject.match(/Merge branch '([^']+)'/);
847
+ if (pr) g.label = `PR #${pr[1]} (${pr[2]})`; else if (br) g.label = `branch ${br[1]}`;
848
+ if (ps.length > 1) {
849
+ g.commits = await count(ps[0], ps[1]);
850
+ g.branches = lines(await git(["log", "--first-parent", "--merges", "--format=%s", `${ps[0]}..${ps[1]}`])).map((s) => s.match(/Merge branch '([^']+)'/)?.[1]).filter(Boolean);
851
+ }
852
+ out.push(g);
853
+ }
854
+ return out;
855
+ };
856
+ const out = { local: null, envs: [], between: [] };
857
+ if (baseSha && remoteBaseSha) {
858
+ const [behind, ahead] = (await git(["rev-list", "--left-right", "--count", `${remoteBaseSha}...${baseSha}`])).trim().split(/\s+/).map(Number);
859
+ out.local = { ahead, behind };
860
+ }
861
+ for (const e of envs) {
862
+ if (!e.sha || !remoteBaseSha) { out.envs.push({ name: e.name, behind: null, groups: [], hotfixes: [], hotfixCount: 0 }); continue; }
863
+ const hot = lines(await git(["log", "--format=%h%x1f%s", "--max-count=20", `${remoteBaseSha}..${e.sha}`])).map((l) => { const [s, subject] = l.split("\x1f"); return { sha: s, subject }; });
864
+ out.envs.push({ name: e.name, behind: await count(e.sha, remoteBaseSha), groups: await groups(e.sha, remoteBaseSha), hotfixes: hot, hotfixCount: await count(remoteBaseSha, e.sha) });
865
+ }
866
+ const known = envs.filter((e) => e.sha);
867
+ for (let i = 0; i + 1 < known.length; i++) {
868
+ const [from, to] = [known[i], known[i + 1]];
869
+ out.between.push({ from: from.name, to: to.name, ahead: await count(to.sha, from.sha), groups: await groups(to.sha, from.sha) });
870
+ }
871
+ return out;
872
+ }
873
+
874
+ // ---------------------------------------------------------------- live
875
+ let state = null, details = new Map(), rawActions = [], lastJson = "", refreshing = null, again = false, lastError = null;
876
+ const clients = new Set();
877
+ let firstReady;
878
+ const ready = new Promise((r) => { firstReady = r; });
879
+
880
+ /** Applies dismiss/snooze to the last proposals and pushes the snapshot when anything changed. */
881
+ function publish(snapshot) {
882
+ const act = presentActions(rawActions);
883
+ const byTarget = {};
884
+ for (const a of act.all) if (!a.hidden && a.target.type === "worktree") byTarget[a.target.key] = (byTarget[a.target.key] ?? 0) + 1;
885
+ const next = { ...snapshot, actions: act.list, hiddenActions: act.hidden, actionCounts: act.counts, actionsByWorktree: byTarget };
886
+ const json = JSON.stringify({ ...next, checkedAt: 0, generatedAt: 0 });
887
+ if (json !== lastJson) { lastJson = json; state = next; broadcast("snapshot", state); }
888
+ else { state.checkedAt = snapshot.checkedAt; broadcast("tick", { checkedAt: state.checkedAt }); }
889
+ }
890
+ async function refresh() {
891
+ if (refreshing) { again = true; return refreshing; }
892
+ refreshing = (async () => {
893
+ try {
894
+ const out = await collect();
895
+ details = out.details; rawActions = out.rawActions;
896
+ publish(out.snapshot);
897
+ lastError = null;
898
+ } catch (e) { lastError = e.message; console.error("refresh failed:", e.message); }
899
+ firstReady();
900
+ })();
901
+ await refreshing;
902
+ refreshing = null;
903
+ if (again) { again = false; return refresh(); }
904
+ }
905
+ function broadcast(event, data) {
906
+ const msg = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
907
+ for (const res of clients) res.write(msg);
908
+ }
909
+
910
+ const watchers = new Map(); // worktree path → FSWatcher
911
+ const gitdirs = new Map(); // .git/worktrees/<name> → worktree path
912
+ let mainPath = null, ignoreSet = null;
913
+ function syncWatchers(worktrees) {
914
+ mainPath = worktrees.find((w) => w.isMain)?.path ?? mainPath;
915
+ const want = new Set(worktrees.map((w) => w.path));
916
+ for (const [p, w] of watchers) if (!want.has(p)) { w.close(); watchers.delete(p); }
917
+ for (const wt of worktrees) {
918
+ try { const m = fs.readFileSync(path.join(wt.path, ".git"), "utf8").match(/worktrees[\\/]([^\\/\s]+)/); if (m) gitdirs.set(m[1], wt.path); } catch { /* the main worktree has a .git folder */ }
919
+ if (watchers.has(wt.path) || !fs.existsSync(wt.path)) continue;
920
+ try {
921
+ const w = fs.watch(wt.path, { recursive: true }, (_, file) => onFsEvent(wt.path, file));
922
+ w.on("error", () => { w.close(); watchers.delete(wt.path); });
923
+ watchers.set(wt.path, w);
924
+ } catch (e) { console.error(`cannot watch ${wt.path}: ${e.message}`); }
925
+ }
926
+ }
927
+ function onFsEvent(root, file) {
928
+ const rel = String(file ?? "").replace(/\\/g, "/");
929
+ const segs = rel.split("/");
930
+ ignoreSet ??= new Set(CONFIG.watchIgnore);
931
+ if (segs.some((s) => ignoreSet.has(s))) return;
932
+ if (path.join(root, rel) === HISTORY_FILE || path.join(root, rel) === ACTIONS_FILE) return;
933
+ if (segs[0] === ".git") {
934
+ if (segs[1] === "objects" || rel.endsWith(".lock")) return;
935
+ if (segs[1] === "worktrees" && gitdirs.has(segs[2])) marked.add(gitdirs.get(segs[2]));
936
+ else if (segs[1] === "index" || segs[1] === "HEAD") marked.add(mainPath);
937
+ } else marked.add(root);
938
+ schedule();
939
+ }
940
+ let timer = null, firstEventAt = 0;
941
+ function schedule() {
942
+ const now = Date.now();
943
+ if (!timer) firstEventAt = now;
944
+ clearTimeout(timer);
945
+ timer = setTimeout(() => { timer = null; refresh(); }, Math.max(0, Math.min(CONFIG.debounceMs, firstEventAt + CONFIG.debounceMaxMs - now)));
946
+ }
947
+
948
+ async function fetchNow() {
949
+ try { await git(["fetch", "--prune", "--quiet"], { timeout: 90_000 }); lastFetch = { at: Date.now(), ok: true, error: null }; }
950
+ catch (e) { lastFetch = { at: Date.now(), ok: false, error: e.message }; }
951
+ await refreshGh();
952
+ refresh();
953
+ }
954
+
955
+ // ---------------------------------------------------------------- http
956
+ function serve() {
957
+ return http.createServer(async (req, res) => {
958
+ const url = new URL(req.url, "http://localhost");
959
+ const json = (code, body) => { res.writeHead(code, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" }); res.end(JSON.stringify(body)); };
960
+ try {
961
+ const act = url.pathname.match(/^\/api\/actions\/([^/]+)\/(dismiss|snooze|restore)$/);
962
+ if (req.method === "GET" && url.pathname === "/") { res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" }); res.end(PAGE); }
963
+ else if (req.method === "GET" && url.pathname === "/api/state") { await ready; json(state ? 200 : 503, state ?? { error: lastError }); }
964
+ else if (req.method === "GET" && url.pathname === "/api/actions") { await ready; json(200, { actions: state?.actions ?? [], hidden: state?.hiddenActions ?? [], counts: state?.actionCounts ?? {} }); }
965
+ else if (req.method === "POST" && act) {
966
+ await ready;
967
+ const [, rawId, verb] = act, id = decodeURIComponent(rawId);
968
+ const ids = id.endsWith(":*") ? rawActions.filter((a) => `${a.rule}:*` === id).map((a) => a.id) : [id];
969
+ if (!ids.length || ids.some((x) => !rawActions.some((a) => a.id === x) && verb !== "restore")) return json(404, { error: "no such action" });
970
+ const hours = Number(url.searchParams.get("hours") ?? 24);
971
+ if (verb === "snooze" && !(hours > 0)) return json(400, { error: "hours must be a positive number" });
972
+ for (const x of ids) {
973
+ delete actionState.dismissed[x]; delete actionState.snoozed[x];
974
+ if (verb === "dismiss") actionState.dismissed[x] = Date.now();
975
+ if (verb === "snooze") actionState.snoozed[x] = Date.now() + hours * 36e5;
976
+ }
977
+ saveActionState();
978
+ if (state) publish({ ...state, checkedAt: Date.now() });
979
+ json(200, { ok: true, ids, verb });
980
+ } else if (req.method === "GET" && url.pathname.startsWith("/api/worktree/")) {
981
+ await ready;
982
+ const key = decodeURIComponent(url.pathname.slice("/api/worktree/".length)), d = details.get(key);
983
+ if (!d) return json(404, { error: "no such worktree" });
984
+ json(200, { ...d, actions: (state?.actions ?? []).flatMap((a) => (a.grouped ? a.items : [a])).concat(state?.hiddenActions ?? []).filter((a) => a.target.type === "worktree" && a.target.key === key) });
985
+ } else if (req.method === "GET" && url.pathname === "/events") {
986
+ res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-store", connection: "keep-alive" });
987
+ res.write("retry: 2000\n\n");
988
+ clients.add(res);
989
+ req.on("close", () => clients.delete(res));
990
+ await ready;
991
+ if (state) res.write(`event: snapshot\ndata: ${JSON.stringify(state)}\n\n`);
992
+ } else json(404, { error: "not found" });
993
+ } catch (e) { json(500, { error: e.message }); }
994
+ });
995
+ }
996
+
997
+ async function main() {
998
+ const argv = process.argv.slice(2);
999
+ for (let i = 0; i < argv.length; i++) {
1000
+ if (argv[i] === "--port") CONFIG.port = Number(argv[++i]);
1001
+ else if (argv[i] === "--base") CONFIG.base = argv[++i];
1002
+ else if (argv[i] === "--config") {
1003
+ for (const [k, v] of Object.entries(JSON.parse(fs.readFileSync(argv[++i], "utf8")))) {
1004
+ CONFIG[k] = v && typeof v === "object" && !Array.isArray(v) && CONFIG[k] && typeof CONFIG[k] === "object" && !Array.isArray(CONFIG[k]) ? { ...CONFIG[k], ...v } : v;
1005
+ }
1006
+ } else { console.error(`unknown option ${argv[i]}\nusage: node server.mjs [--port 4500] [--base main] [--config extra.json]`); process.exit(2); }
1007
+ }
1008
+ REPO = (await git(["rev-parse", "--show-toplevel"]).catch(() => { console.error("not inside a git repository"); process.exit(1); })).trim();
1009
+ refreshGh().then(refresh);
1010
+ serve().listen(CONFIG.port, CONFIG.host, () => console.log(`Worktree dashboard for ${REPO}\n http://${CONFIG.host}:${CONFIG.port}/`));
1011
+ refresh();
1012
+ setInterval(refresh, CONFIG.refreshIntervalMs);
1013
+ setInterval(() => { for (const res of clients) res.write(": keep-alive\n\n"); }, 20_000);
1014
+ if (CONFIG.fetchIntervalMs > 0) { setTimeout(fetchNow, 5_000); setInterval(fetchNow, CONFIG.fetchIntervalMs); }
1015
+ }
1016
+
1017
+ // ---------------------------------------------------------------- page
1018
+ const PAGE = String.raw`<!doctype html>
1019
+ <html lang="en">
1020
+ <head>
1021
+ <meta charset="utf-8">
1022
+ <meta name="viewport" content="width=device-width,initial-scale=1">
1023
+ <title>Worktrees</title>
1024
+ <style>
1025
+ :root{--bg:#f6f7f9;--card:#fff;--fg:#1b1d21;--dim:#5f6670;--line:#e1e4e9;--band:#eef0f3;--acc:#2563eb;--ok:#15803d;--warn:#b45309;--bad:#c62828;--info:#6d28d9;--part:#93b4f5;--flash:#fff3b0;color-scheme:light}
1026
+ :root[data-theme=dark]{--bg:#121316;--card:#1b1d21;--fg:#e8e9ec;--dim:#9aa1ab;--line:#2c2f35;--band:#23262b;--acc:#6b9bff;--ok:#4ade80;--warn:#f0a94a;--bad:#f87171;--info:#b49cff;--part:#3c5a9a;--flash:#4a4320;color-scheme:dark}
1027
+ @media (prefers-color-scheme:dark){:root:not([data-theme=light]){--bg:#121316;--card:#1b1d21;--fg:#e8e9ec;--dim:#9aa1ab;--line:#2c2f35;--band:#23262b;--acc:#6b9bff;--ok:#4ade80;--warn:#f0a94a;--bad:#f87171;--info:#b49cff;--part:#3c5a9a;--flash:#4a4320;color-scheme:dark}}
1028
+ *{box-sizing:border-box}
1029
+ body{margin:0;background:var(--bg);color:var(--fg);font:13px/1.4 system-ui,-apple-system,"Segoe UI",sans-serif}
1030
+ header{position:sticky;top:0;z-index:5;background:var(--card);border-bottom:1px solid var(--line)}
1031
+ .bar1{display:flex;flex-wrap:wrap;align-items:center;gap:6px 16px;padding:8px 18px}
1032
+ .bar1 h1{font-size:16px;margin:0}
1033
+ nav.tabs,.wtabs{display:flex;gap:2px;padding:0 14px;overflow-x:auto;white-space:nowrap;scrollbar-width:thin}
1034
+ nav.tabs a,.wtabs a{padding:8px 10px;border-bottom:2px solid transparent;color:var(--dim);text-decoration:none;font-weight:600}
1035
+ nav.tabs a[aria-current=page],.wtabs a[aria-current=page]{color:var(--fg);border-color:var(--acc)}
1036
+ main{padding:14px 18px 48px;max-width:1600px;margin:0 auto}
1037
+ h2{font-size:12px;text-transform:uppercase;letter-spacing:.05em;color:var(--dim);margin:22px 0 8px;display:flex;gap:12px;align-items:center;flex-wrap:wrap}
1038
+ h2:first-child{margin-top:4px}
1039
+ h3{font-size:14px;margin:4px 0}
1040
+ code,.mono{font:12px ui-monospace,Consolas,monospace}
1041
+ .dim{color:var(--dim)}
1042
+ a{color:var(--acc)}
1043
+ button,select,input{font:inherit;color:inherit;background:var(--card);border:1px solid var(--line);border-radius:6px;padding:3px 8px}
1044
+ button{cursor:pointer}
1045
+ button[aria-pressed=true]{background:var(--acc);border-color:var(--acc);color:#fff}
1046
+ .live{display:inline-flex;align-items:center;gap:6px}
1047
+ .dot{width:9px;height:9px;border-radius:50%;background:var(--bad)}
1048
+ .dot.on{background:var(--ok)}
1049
+ .grow{flex:1}
1050
+ .count{display:inline-block;min-width:18px;padding:0 5px;border-radius:9px;background:var(--band);color:var(--fg);font-size:11px;text-align:center;margin-left:4px}
1051
+ .tiles{display:grid;grid-template-columns:repeat(auto-fill,minmax(140px,1fr));gap:8px}
1052
+ .tile{background:var(--card);border:1px solid var(--line);border-radius:8px;padding:8px 10px;transition:background 1.2s}
1053
+ .tile b{display:block;font-size:20px}
1054
+ .tile span{color:var(--dim);font-size:12px}
1055
+ .env{grid-column:span 2}
1056
+ .controls{display:flex;flex-wrap:wrap;gap:6px;align-items:center;margin:4px 0 10px}
1057
+ .board{display:grid;grid-auto-flow:column;grid-auto-columns:minmax(150px,1fr);gap:8px;overflow-x:auto;padding-bottom:4px}
1058
+ .col{background:var(--band);border-radius:8px;padding:6px;min-height:60px}
1059
+ .col h3{margin:0 0 6px;font-size:12px;display:flex;justify-content:space-between;color:var(--dim)}
1060
+ .chip{display:block;width:100%;text-align:left;background:var(--card);border:1px solid var(--line);border-radius:6px;padding:4px 6px;margin-bottom:4px;font-size:12px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
1061
+ .split{display:flex;height:4px;border-radius:2px;overflow:hidden;margin-top:3px;background:var(--line)}
1062
+ .split i{display:block;height:100%}
1063
+ .cards{display:grid;grid-template-columns:repeat(auto-fill,minmax(310px,1fr));gap:10px}
1064
+ .cards.compact{grid-template-columns:repeat(auto-fill,minmax(250px,1fr))}
1065
+ .card{position:relative;background:var(--card);border:1px solid var(--line);border-radius:10px;padding:10px 12px;display:flex;flex-direction:column;gap:6px;transition:background 1.2s}
1066
+ .card:hover,.card:focus-within{border-color:var(--acc)}
1067
+ .stretch{color:inherit;text-decoration:none}
1068
+ .stretch::after{content:"";position:absolute;inset:0;border-radius:10px}
1069
+ .card a:not(.stretch){position:relative;z-index:1}
1070
+ .withside{display:grid;grid-template-columns:minmax(0,1fr) minmax(300px,420px);gap:14px;align-items:start}
1071
+ .side{position:sticky;top:96px;display:flex;flex-direction:column;gap:8px}
1072
+ .side textarea{width:100%;min-height:260px;height:calc(100vh - 300px);resize:vertical;font:12px/1.45 ui-monospace,Consolas,monospace;background:var(--band);color:var(--fg);border:1px solid var(--line);border-radius:6px;padding:8px}
1073
+ @media (max-width:900px){.withside{grid-template-columns:1fr}.side{position:static;order:-1}.side textarea{height:220px}}
1074
+ .card .top{display:flex;gap:10px;align-items:center}
1075
+ .card .name{font-weight:600;word-break:break-all}
1076
+ .flash{background:var(--flash)!important;transition:none}
1077
+ .ring{width:44px;height:44px;flex:none}
1078
+ .ring .bg{fill:none;stroke:var(--line);stroke-width:4}
1079
+ .ring .fg{fill:none;stroke:var(--ok);stroke-width:4;stroke-linecap:round}
1080
+ .ring text{font-size:10px;text-anchor:middle;fill:var(--fg);font-weight:600}
1081
+ div.ring{display:grid;place-items:center;border:2px dashed var(--line);border-radius:50%;color:var(--dim);font-size:10px;text-align:center;line-height:1.1}
1082
+ .trk{display:flex;gap:2px}
1083
+ .trk i{flex:1;height:7px;border-radius:2px;background:var(--line)}
1084
+ .trk i.full{background:var(--ok)}
1085
+ .trk i.partial{background:linear-gradient(90deg,var(--ok) 50%,var(--part) 50%)}
1086
+ .trk i.skip{background:repeating-linear-gradient(45deg,var(--ok) 0 3px,var(--line) 3px 6px)}
1087
+ .trk.big i{height:12px}
1088
+ .trk-labels{display:flex;gap:2px;font-size:10px;color:var(--dim)}
1089
+ .trk-labels span{flex:1;text-align:center;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
1090
+ .badges{display:flex;flex-wrap:wrap;gap:4px}
1091
+ .b{font-size:11px;font-weight:600;border-radius:10px;padding:1px 7px;border:1px solid currentColor;white-space:nowrap;text-decoration:none}
1092
+ .ok{color:var(--ok)}.warn{color:var(--warn)}.bad{color:var(--bad)}.info{color:var(--info)}.acc{color:var(--acc)}
1093
+ .p-critical{--p:var(--bad)}.p-high{--p:var(--warn)}.p-medium{--p:var(--acc)}.p-low{--p:var(--dim)}
1094
+ .pri{color:var(--p);border-color:var(--p)}
1095
+ .cur{font-size:12px;border-left:3px solid var(--acc);padding-left:6px;overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical}
1096
+ .last{font-size:12px;color:var(--dim);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
1097
+ .err{color:var(--bad);font-size:12px}
1098
+ table{width:100%;border-collapse:collapse;background:var(--card);border:1px solid var(--line)}
1099
+ th,td{padding:6px 8px;border-bottom:1px solid var(--line);text-align:left;vertical-align:top}
1100
+ th{font-size:12px;color:var(--dim);cursor:pointer;user-select:none;white-space:nowrap}
1101
+ .panel{background:var(--card);border:1px solid var(--line);border-radius:8px;padding:10px 12px}
1102
+ .grid2{display:grid;grid-template-columns:repeat(auto-fill,minmax(340px,1fr));gap:10px}
1103
+ ul.plain{list-style:none;margin:4px 0;padding:0}
1104
+ ul.plain li{padding:2px 0}
1105
+ .action{background:var(--card);border:1px solid var(--line);border-left:4px solid var(--p);border-radius:8px;padding:8px 10px;margin-bottom:6px;display:flex;flex-direction:column;gap:4px}
1106
+ .action.hiddenA{opacity:.6}
1107
+ .action .t{font-weight:600}
1108
+ .cmd{display:flex;gap:6px;align-items:flex-start}
1109
+ .cmd pre{flex:1;margin:0;padding:4px 6px;background:var(--band);border-radius:4px;font:12px ui-monospace,Consolas,monospace;white-space:pre-wrap;word-break:break-all}
1110
+ .arow{display:flex;flex-wrap:wrap;gap:6px;align-items:center;font-size:12px}
1111
+ .wthead{background:var(--card);border:1px solid var(--line);border-radius:10px;padding:10px 14px;display:flex;flex-direction:column;gap:6px;margin-bottom:8px}
1112
+ .wtabs{padding:0;border-bottom:1px solid var(--line);margin-bottom:12px}
1113
+ .bar{height:8px;background:var(--line);border-radius:4px;overflow:hidden}
1114
+ .bar i{display:block;height:100%;background:var(--ok)}
1115
+ .phase{margin:12px 0}
1116
+ .phase h4{margin:0 0 4px;display:flex;justify-content:space-between;gap:8px;font-size:13px}
1117
+ .steps{list-style:none;margin:4px 0;padding-left:0}
1118
+ .steps .steps{padding-left:18px}
1119
+ .steps li{padding:2px 0}
1120
+ .steps li>span::before{display:inline-block;width:18px;font-weight:700}
1121
+ .s-done>span{color:var(--dim)}
1122
+ .s-done>span::before{content:"✓";color:var(--ok)}
1123
+ .s-doing>span::before{content:"◐";color:var(--warn)}
1124
+ .s-todo>span::before{content:"○";color:var(--dim)}
1125
+ .s-current>span{background:var(--flash);border-radius:4px}
1126
+ .kv{display:grid;grid-template-columns:170px 1fr;gap:4px 12px;margin:0}
1127
+ .kv dt{color:var(--dim)}
1128
+ .kv dd{margin:0}
1129
+ .files li{font:12px ui-monospace,Consolas,monospace}
1130
+ .commit{display:flex;gap:8px;align-items:baseline;padding:4px 0;border-bottom:1px solid var(--line)}
1131
+ .commit .msg{flex:1;min-width:0}
1132
+ .attn li{padding:4px 0;border-bottom:1px solid var(--line)}
1133
+ @media (max-width:700px){main{padding:10px}.bar1{padding:8px 10px}.env{grid-column:span 1}.kv{grid-template-columns:1fr}.kv dt{margin-top:6px}}
1134
+ </style>
1135
+ </head>
1136
+ <body>
1137
+ <header>
1138
+ <div class="bar1"><h1>Worktrees</h1><span class="dim mono" id="repo"></span><span class="grow"></span>
1139
+ <span class="dim" id="fetch"></span>
1140
+ <span class="live"><span class="dot" id="dot"></span><span id="ago">connecting…</span></span>
1141
+ <button id="theme" title="Light or dark" aria-label="Switch light or dark">◐</button></div>
1142
+ <nav class="tabs" id="tabs" aria-label="Sections"></nav>
1143
+ </header>
1144
+ <main id="view"><p class="dim">Reading every worktree…</p></main>
1145
+ <script>
1146
+ const $ = (s) => document.querySelector(s);
1147
+ const esc = (v) => String(v ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
1148
+ const TOP = [["overview", "Overview"], ["worktrees", "Worktrees"], ["pipeline", "Pipeline"], ["branches", "Branches"], ["environments", "Environments & Drift"], ["actions", "Actions"]];
1149
+ const WT = [["summary", "Summary"], ["plan", "Plan"], ["delivery", "Delivery"], ["changes", "Changes"], ["commits", "Commits"], ["health", "Health"], ["actions", "Actions"]];
1150
+ const PRI = ["critical", "high", "medium", "low"];
1151
+ const ui = { top: "overview", wt: null, wtab: "summary", sort: "activity", f: new Set(), stage: "", q: "", all: false, bsort: ["lastActivityAt", -1], cat: "", tgt: "", showHidden: false, detail: null, seen: new Map(), shell: "" };
1152
+ let S = null, checkedAt = 0, connected = false;
1153
+
1154
+ function ago(t) { if (!t) return "—"; const s = Math.max(0, Math.round((Date.now() - t) / 1000)); if (s < 60) return s + "s ago"; const m = Math.round(s / 60); if (m < 60) return m + "m ago"; const h = Math.round(m / 60); return h < 48 ? h + "h ago" : Math.round(h / 24) + "d ago"; }
1155
+ const when = (t) => (t ? new Date(t).toLocaleString() : "—");
1156
+ const stageName = (i) => (i == null ? "No changes" : (S.stages[i] || {}).label || "?");
1157
+ const wtLink = (key, tab) => "#wt=" + encodeURIComponent(key) + "&tab=" + (tab || "summary");
1158
+ const COLORS = ["var(--warn)", "var(--dim)", "var(--info)", "var(--info)", "var(--acc)", "var(--acc)", "var(--ok)", "var(--ok)", "var(--ok)"];
1159
+
1160
+ // ---------- routing: #tab=<top> or #wt=<key>&tab=<drill-down tab>
1161
+ function route() {
1162
+ const p = new URLSearchParams(location.hash.slice(1));
1163
+ const wt = p.get("wt"), tab = p.get("tab");
1164
+ if (wt) { ui.wt = wt; ui.wtab = WT.some(([k]) => k === tab) ? tab : "summary"; }
1165
+ else { ui.wt = null; ui.top = TOP.some(([k]) => k === tab) ? tab : "overview"; }
1166
+ const shell = ui.wt ? "wt:" + ui.wt + ":" + ui.wtab : "top:" + ui.top;
1167
+ if (shell !== ui.shell) { ui.shell = shell; ui.detail = null; window.scrollTo(0, 0); drawShell(); }
1168
+ fill();
1169
+ if (ui.wt) loadDetail();
1170
+ }
1171
+ addEventListener("hashchange", route);
1172
+
1173
+ function drawTabs() {
1174
+ const c = S ? S.actionCounts : null, n = c ? c.critical + c.high + c.medium + c.low : 0;
1175
+ $("#tabs").innerHTML = TOP.map(([k, l]) => '<a href="#tab=' + k + '"' + (!ui.wt && ui.top === k ? ' aria-current="page"' : "") + ">" + l +
1176
+ (k === "actions" && n ? '<span class="count" style="' + (c.critical ? "background:var(--bad);color:#fff" : c.high ? "background:var(--warn);color:#fff" : "") + '">' + n + "</span>" : "") +
1177
+ (k === "worktrees" && S ? '<span class="count">' + S.worktrees.length + "</span>" : "") + "</a>").join("");
1178
+ }
1179
+
1180
+ // Static parts of each view (controls) are drawn once per view; fill() redraws the data in place,
1181
+ // so typing, focus, the open view and the scroll position survive live updates.
1182
+ function drawShell() {
1183
+ const v = $("#view");
1184
+ if (ui.wt) { v.innerHTML = '<div id="wthead"></div><nav class="wtabs" id="wtabs"></nav><div id="wtbody"><p class="dim">Loading…</p></div>'; return; }
1185
+ const shells = {
1186
+ overview: '<section class="tiles" id="tiles"></section><h2>Environments</h2><section class="tiles" id="envtiles"></section>' +
1187
+ '<h2>Next up <a href="#tab=actions">all actions</a></h2><div id="nextup"></div><h2>Needs attention</h2><div id="attn"></div><h2>In progress</h2><section class="cards compact" id="inprog"></section>',
1188
+ worktrees: '<div class="controls"><input id="q" type="search" placeholder="Search branch, path, plan, step" size="28" aria-label="Search worktrees">' +
1189
+ '<label>Sort <select id="sort"><option value="activity">Last activity</option><option value="progress">Progress</option><option value="stage">Stage</option><option value="ahead">Ahead</option><option value="name">Name</option></select></label>' +
1190
+ '<button data-f="dirty" aria-pressed="false">Dirty</button><button data-f="stale" aria-pressed="false">Stale</button><button data-f="pr" aria-pressed="false">Has PR</button><button data-f="noplan" aria-pressed="false">No plan</button>' +
1191
+ '<label>Stage <select id="stage"></select></label><span class="dim" id="wcount"></span></div><section class="cards" id="cards"></section>',
1192
+ pipeline: '<h2>Where every branch is</h2><p class="dim">Each branch sits in the furthest stage all its work has reached; the coloured strip shows how its commits are spread.</p><section class="board" id="board"></section>',
1193
+ branches: '<h2>All branches <label class="dim" style="text-transform:none"><input type="checkbox" id="all"> show remote branches</label></h2><div style="overflow-x:auto"><table id="btable"></table></div><h2>Cleanup candidates</h2><div id="cleanup"></div>',
1194
+ environments: '<h2>Environments</h2><div class="grid2" id="envs"></div><h2>Release drift</h2><div class="grid2" id="drift"></div><h2>Warnings</h2><div id="warn"></div>',
1195
+ actions: '<div class="withside"><div><div class="controls"><label>Category <select id="cat"></select></label><label>Target <select id="tgt"></select></label><label><input type="checkbox" id="showhidden"> show hidden</label><span class="dim" id="acount"></span></div><div id="alist"></div></div>' +
1196
+ '<aside class="panel side" aria-labelledby="ptitle"><h3 id="ptitle">Do them all from main</h3><p class="dim" id="phint"></p>' +
1197
+ '<textarea id="prompt" readonly spellcheck="false" aria-labelledby="ptitle"></textarea><div class="arow"><button id="copyall" data-copy="">Copy prompt</button><span class="dim">Paste into Claude Code started in the main worktree.</span></div></aside></div>',
1198
+ };
1199
+ v.innerHTML = shells[ui.top];
1200
+ const restore = { q: ["value", ui.q], sort: ["value", ui.sort], all: ["checked", ui.all], showhidden: ["checked", ui.showHidden] };
1201
+ for (const [id, [prop, val]] of Object.entries(restore)) if ($("#" + id)) $("#" + id)[prop] = val;
1202
+ v.querySelectorAll("[data-f]").forEach((b) => b.setAttribute("aria-pressed", ui.f.has(b.dataset.f)));
1203
+ }
1204
+
1205
+ function fill() {
1206
+ drawTabs();
1207
+ if (!S) return;
1208
+ $("#repo").textContent = S.repo;
1209
+ const f = S.fetch;
1210
+ $("#fetch").textContent = f.at ? "fetched " + ago(f.at) + (f.ok ? "" : " (failed)") : f.intervalMs ? "fetch pending" : "fetch off";
1211
+ $("#fetch").title = f.error || "";
1212
+ if (ui.wt) return fillWorktree();
1213
+ ({ overview: fillOverview, worktrees: fillWorktrees, pipeline: fillPipeline, branches: fillBranches, environments: fillEnvironments, actions: fillActions })[ui.top]();
1214
+ }
1215
+ function flashIf(key, h) { const before = ui.seen.get(key); ui.seen.set(key, h); return before !== undefined && before !== h ? " flash" : ""; }
1216
+
1217
+ // ---------- pieces
1218
+ function tracker(seg, pr, big) {
1219
+ return '<div class="trk' + (big ? " big" : "") + '">' + S.stages.map((st, i) => {
1220
+ let c = (seg && seg[i]) || "none";
1221
+ if (st.key === "pr" && !pr && c !== "none") c = "skip";
1222
+ const word = { full: "all of the work reached it", partial: "some of the work reached it", none: "not reached", skip: "no PR: skipped" }[c];
1223
+ return '<i class="' + c + '" title="' + esc(st.label + ": " + word) + '"></i>';
1224
+ }).join("") + "</div>";
1225
+ }
1226
+ const trackLabels = () => '<div class="trk-labels">' + S.stages.map((s) => "<span>" + esc(s.label) + "</span>").join("") + "</div>";
1227
+ function split(counts) {
1228
+ const total = (counts || []).reduce((a, b) => a + b, 0);
1229
+ if (!total) return "";
1230
+ return '<div class="split" title="' + esc(counts.map((n, i) => (n ? n + " " + S.stages[i].label : "")).filter(Boolean).join(", ")) + '">' +
1231
+ counts.map((n, i) => (n ? '<i style="width:' + (n * 100 / total) + "%;background:" + COLORS[Math.min(i, COLORS.length - 1)] + '"></i>' : "")).join("") + "</div>";
1232
+ }
1233
+ function ring(p) {
1234
+ if (!p || !p.total) return '<div class="ring">No<br>plan</div>';
1235
+ const pct = p.pct || 0;
1236
+ return '<svg class="ring" viewBox="0 0 40 40" role="img" aria-label="' + pct + '% complete"><circle cx="20" cy="20" r="16" class="bg"/><circle cx="20" cy="20" r="16" class="fg" stroke-dasharray="' + (pct * 1.0053).toFixed(1) + ' 100.53" transform="rotate(-90 20 20)"/><text x="20" y="24">' + pct + "%</text></svg>";
1237
+ }
1238
+ function prChip(pr) {
1239
+ if (!pr) return "";
1240
+ const st = pr.state === "MERGED" ? "ok" : pr.state === "CLOSED" || pr.isDraft ? "dim" : "acc";
1241
+ const review = pr.reviewDecision ? " · " + pr.reviewDecision.toLowerCase().replace(/_/g, " ") : "";
1242
+ const ci = pr.ci && pr.ci.total ? ' <span class="b ' + ({ passing: "ok", failing: "bad", pending: "warn" }[pr.ci.state] || "dim") + '">CI ' + pr.ci.passed + "/" + pr.ci.total + "</span>" : "";
1243
+ return '<a class="b ' + st + '" href="' + esc(pr.url) + '" target="_blank" rel="noopener" onclick="event.stopPropagation()">#' + pr.number + " " + (pr.isDraft ? "draft" : pr.state.toLowerCase()) + review + "</a>" + ci;
1244
+ }
1245
+ function badges(w) {
1246
+ const d = w.dirty || {}, out = [], n = (S.actionsByWorktree || {})[w.key];
1247
+ if (n) out.push('<a class="b warn" href="' + wtLink(w.key, "actions") + '" onclick="event.stopPropagation()">' + n + " action" + (n === 1 ? "" : "s") + "</a>");
1248
+ if (w.error) out.push('<span class="b bad" title="' + esc(w.error) + '">error</span>');
1249
+ if (d.conflicted) out.push('<span class="b bad">' + d.conflicted + " conflicted</span>");
1250
+ if (d.total) out.push('<span class="b warn" title="' + esc(d.staged + " staged, " + d.unstaged + " unstaged, " + d.untracked + " untracked; oldest " + ago(d.oldestAt)) + '">' + d.total + " uncommitted</span>");
1251
+ if (w.ahead) out.push('<span class="b acc" title="commits not in ' + esc(S.base) + '">↑' + w.ahead + "</span>");
1252
+ if (w.behind) out.push('<span class="b dim" title="commits in ' + esc(S.base) + ' it lacks">↓' + w.behind + "</span>");
1253
+ if (w.upstream) { if (w.upstream.gone) out.push('<span class="b bad">upstream gone</span>'); else if (w.upstream.ahead || w.upstream.behind) out.push('<span class="b info" title="' + esc("against " + w.upstream.name) + '">⇅ +' + w.upstream.ahead + " −" + w.upstream.behind + "</span>"); }
1254
+ else if (!w.isMain && w.unpushed && w.unpushed.count) out.push('<span class="b dim">never pushed</span>');
1255
+ if (w.locked) out.push('<span class="b info" title="' + esc(w.locked) + '">locked</span>');
1256
+ if (w.prunable) out.push('<span class="b bad" title="' + esc(w.prunable) + '">prunable</span>');
1257
+ if (w.stale) out.push('<span class="b dim">stale</span>');
1258
+ if (w.merged && /^merged/.test(w.merged)) out.push('<span class="b ok">' + esc(w.merged) + "</span>");
1259
+ return out.join("");
1260
+ }
1261
+ function card(w, compact) {
1262
+ const p = w.plan;
1263
+ // One link per card, stretched over it, so the badge and PR links inside are not nested links.
1264
+ return '<div class="card' + flashIf((compact ? "c:" : "card:") + w.key, w.hash) + '">' +
1265
+ '<div class="top">' + ring(p) + '<div style="min-width:0"><div class="name"><a class="stretch" href="' + wtLink(w.key) + '">' + esc(w.branch || w.key) + "</a>" + (w.isMain ? ' <span class="b dim">main worktree</span>' : "") + '</div><div class="dim mono" style="font-size:11px">' + esc(w.shortPath) + "</div>" +
1266
+ (p && p.total ? '<div class="dim">' + p.done + " / " + p.total + " steps</div>" : "") + "</div></div>" +
1267
+ (w.error ? '<div class="err">' + esc(w.error) + "</div>" : "") +
1268
+ (p && p.current ? '<div class="cur" title="' + esc(p.current.text) + '">' + esc(p.current.text) + "</div>" : "") +
1269
+ (w.stage ? tracker(w.stage.segments, w.pr) + '<div class="dim" style="font-size:12px">' + esc(stageName(w.stage.column)) + " · " + esc(w.stage.text) + "</div>" : "") +
1270
+ '<div class="badges">' + badges(w) + prChip(w.pr) + "</div>" +
1271
+ (!compact && w.last ? '<div class="last" title="' + esc(when(w.last.at) + " · " + w.last.subject) + '"><span class="mono">' + esc(w.last.short) + "</span> " + esc(w.last.subject) + " · " + ago(w.last.at) + "</div>" : "") + "</div>";
1272
+ }
1273
+ function actionHtml(a) {
1274
+ const hidden = a.hidden ? '<span class="b dim">' + esc(a.hidden) + (a.snoozedUntil ? " until " + when(a.snoozedUntil) : "") + "</span>" : "";
1275
+ const target = a.target.type === "group" ? '<span class="dim">' + esc(a.target.label) + "</span>" : '<a href="' + a.link + '">' + esc(a.target.label) + "</a>";
1276
+ return '<div class="action p-' + a.priority + (a.hidden ? " hiddenA" : "") + '">' +
1277
+ '<div class="arow"><span class="b pri">' + a.priority + '</span><span class="b dim">' + esc(a.category) + "</span>" + target + (a.since ? '<span class="dim">since ' + ago(a.since) + "</span>" : "") + hidden + "</div>" +
1278
+ '<div class="t">' + esc(a.title) + '</div><div class="dim">' + esc(a.why) + "</div>" +
1279
+ (a.items ? '<details><summary class="dim">' + a.items.length + " items</summary><ul class=\"plain\">" + a.items.map((x) => '<li><a href="' + x.link + '">' + esc(x.target.label) + "</a> — " + esc(x.why) + "</li>").join("") + "</ul></details>" : "") +
1280
+ '<div class="cmd"><pre>' + esc(a.command) + '</pre><button data-copy="' + esc(a.command) + '">Copy</button></div>' +
1281
+ '<div class="arow">' + (a.hidden ? '<button data-act="restore" data-id="' + esc(a.id) + '">Show again</button>' :
1282
+ '<button data-act="dismiss" data-id="' + esc(a.id) + '">Dismiss</button><label>Snooze <select data-snooze="' + esc(a.id) + '"><option value="">…</option><option value="4">4 hours</option><option value="24">1 day</option><option value="72">3 days</option><option value="168">1 week</option></select></label>') + "</div></div>";
1283
+ }
1284
+
1285
+ // ---------- top-level tabs
1286
+ function fillOverview() {
1287
+ const s = S.summary, c = S.actionCounts, pct = s.planTotal ? Math.round((s.planDone * 100) / s.planTotal) : null;
1288
+ const tiles = [["Worktrees", s.worktrees], ["Active branches", s.activeBranches, "a commit in the last 7 days"], ["Dirty", s.dirty], ["Conflicts", s.conflicts], ["Stale", s.stale],
1289
+ ["Open PRs", s.openPrs == null ? "—" : s.openPrs, S.gh.available ? "" : S.gh.error || "gh unavailable"], ["Waiting for " + (s.prodName || "prod"), s.waitingForProd == null ? "unknown" : s.waitingForProd, "commits in " + S.remote + "/" + S.base + " not yet deployed"],
1290
+ ["Last hourly check", S.hourly ? new Date(S.hourly.at).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }) + " · " + S.hourly.status + " · " + S.hourly.openIssues + " open issues" : "never", S.hourly ? "tools/worktree-dashboard/reports/latest.md, " + ago(S.hourly.at) : "no hourly report yet"],
1291
+ ["Plans complete", pct == null ? "—" : pct + "%", s.planDone + " of " + s.planTotal + " steps, weighted by step count"]];
1292
+ $("#tiles").innerHTML = tiles.map(([k, v, t]) => '<div class="tile' + flashIf("tile:" + k, String(v)) + '" title="' + esc(t || "") + '"><b>' + esc(v) + "</b><span>" + esc(k) + "</span></div>").join("") +
1293
+ '<a class="tile" href="#tab=actions" style="text-decoration:none;color:inherit"><b>' + PRI.map((p) => '<span class="p-' + p + '" style="color:var(--p)" title="' + p + '">' + c[p] + "</span>").join(" · ") + "</b><span>Open actions: critical · high · medium · low</span></a>";
1294
+ $("#envtiles").innerHTML = S.envs.map((e) => '<div class="tile env' + flashIf("env:" + e.name, String(e.sha) + e.error) + '"><b class="mono">' + esc(e.short || "unknown") + "</b><span>" + esc(e.name) + "</span>" +
1295
+ '<div class="dim">' + (e.version ? esc(e.version) + " · " : "") + (e.deployedAt ? "deployed " + ago(e.deployedAt) : "deploy time unknown") + "</div>" +
1296
+ "<div>" + (e.sha ? (e.waiting ? '<span class="warn">' + e.waiting + " commits waiting to ship</span>" : '<span class="ok">nothing waiting</span>') : '<span class="bad">' + esc(e.error || "unknown") + "</span>") + "</div></div>").join("") || '<div class="tile dim">No environments configured</div>';
1297
+ $("#nextup").innerHTML = S.actions.slice(0, 5).map(actionHtml).join("") || '<p class="ok">Nothing to do.</p>';
1298
+ const attn = [];
1299
+ for (const w of S.worktrees) {
1300
+ if (w.dirty && w.dirty.conflicted) attn.push(['<span class="b bad">conflicts</span>', w, w.dirty.conflicted + " conflicted files", "changes"]);
1301
+ if (w.pr && w.pr.state === "OPEN" && w.pr.ci && w.pr.ci.failed) attn.push(['<span class="b bad">CI failing</span>', w, "PR #" + w.pr.number + ": " + w.pr.ci.failed + " checks failing", "health"]);
1302
+ if (w.stale && ((w.unlanded && w.unlanded.count) || (w.dirty && w.dirty.total))) attn.push(['<span class="b dim">stale work</span>', w, "quiet " + ago(w.lastActivityAt) + " with unfinished work", "summary"]);
1303
+ if (w.error) attn.push(['<span class="b bad">error</span>', w, w.error, "health"]);
1304
+ }
1305
+ const hot = ((S.drift && S.drift.envs) || []).filter((e) => e.hotfixCount).map((e) => '<li><span class="b bad">hotfix drift</span> <a href="#tab=environments">' + esc(e.name) + "</a> has " + e.hotfixCount + " commits not in " + esc(S.remote + "/" + S.base) + "</li>");
1306
+ $("#attn").innerHTML = attn.length || hot.length ? '<ul class="plain attn">' + hot.join("") + attn.map(([b, w, t, tab]) => "<li>" + b + ' <a href="' + wtLink(w.key, tab) + '">' + esc(w.branch || w.key) + "</a> " + esc(t) + "</li>").join("") + "</ul>" : '<p class="ok">Nothing needs attention.</p>';
1307
+ const busy = S.worktrees.filter((w) => !w.error && w.lastActivityAt && Date.now() - w.lastActivityAt < 7 * 864e5).sort((a, b) => b.lastActivityAt - a.lastActivityAt).slice(0, 9);
1308
+ $("#inprog").innerHTML = busy.map((w) => card(w, true)).join("") || '<p class="dim">No worktree changed in the last 7 days.</p>';
1309
+ }
1310
+
1311
+ function visible() {
1312
+ const q = ui.q.toLowerCase();
1313
+ return S.worktrees.filter((w) => {
1314
+ if (ui.f.has("dirty") && !(w.dirty && w.dirty.total)) return false;
1315
+ if (ui.f.has("stale") && !w.stale) return false;
1316
+ if (ui.f.has("pr") && !w.pr) return false;
1317
+ if (ui.f.has("noplan") && w.plan && w.plan.total) return false;
1318
+ if (ui.stage !== "" && String(w.stage ? w.stage.column : "") !== ui.stage) return false;
1319
+ if (q && ![w.key, w.path, w.plan && w.plan.title, w.plan && w.plan.current && w.plan.current.text].join(" ").toLowerCase().includes(q)) return false;
1320
+ return true;
1321
+ }).sort((a, b) => {
1322
+ const pct = (w) => (w.plan && w.plan.pct != null ? w.plan.pct : -1), col = (w) => (w.stage && w.stage.column != null ? w.stage.column : 99);
1323
+ switch (ui.sort) {
1324
+ case "progress": return pct(b) - pct(a);
1325
+ case "stage": return col(a) - col(b);
1326
+ case "ahead": return (b.ahead || 0) - (a.ahead || 0);
1327
+ case "name": return a.key.localeCompare(b.key);
1328
+ default: return (b.lastActivityAt || 0) - (a.lastActivityAt || 0);
1329
+ }
1330
+ });
1331
+ }
1332
+ function fillWorktrees() {
1333
+ const st = $("#stage");
1334
+ if (st.options.length !== S.stages.length + 1) st.innerHTML = '<option value="">Any</option>' + S.stages.map((x, i) => '<option value="' + i + '">' + esc(x.label) + "</option>").join("");
1335
+ st.value = ui.stage;
1336
+ const list = visible();
1337
+ $("#wcount").textContent = list.length + " of " + S.worktrees.length;
1338
+ $("#cards").innerHTML = list.map((w) => card(w)).join("") || '<p class="dim">No worktree matches.</p>';
1339
+ }
1340
+
1341
+ function fillPipeline() {
1342
+ const cols = S.stages.map(() => []), idle = [];
1343
+ const wtKeys = new Set(S.worktrees.map((w) => w.key));
1344
+ for (const b of S.branches.filter((x) => !x.remote)) (b.column == null ? idle : cols[b.column]).push({ name: b.name, key: b.worktree, counts: b.counts, title: b.stageText });
1345
+ for (const w of S.worktrees.filter((x) => !x.branch)) (w.stage && w.stage.column != null ? cols[w.stage.column] : idle).push({ name: w.key, key: w.key, counts: (w.stage && w.stage.counts) || [], title: "detached HEAD" });
1346
+ const chip = (c) => (c.key && wtKeys.has(c.key) ? '<a class="chip" href="' + wtLink(c.key, "delivery") + '"' : '<a class="chip" href="#tab=branches"') + ' title="' + esc(c.name + " · " + c.title) + '">' + esc(c.name) + split(c.counts) + "</a>";
1347
+ $("#board").innerHTML = S.stages.map((s, i) => '<div class="col"><h3><span>' + esc(s.label) + "</span><span>" + cols[i].length + "</span></h3>" + cols[i].map(chip).join("") + "</div>").join("") +
1348
+ '<div class="col"><h3><span>No own commits</span><span>' + idle.length + "</span></h3>" + idle.map(chip).join("") + "</div>";
1349
+ }
1350
+
1351
+ function fillBranches() {
1352
+ const rows = S.branches.filter((b) => ui.all || !b.remote);
1353
+ const [k, dir] = ui.bsort;
1354
+ const val = (b) => (k === "stage" ? (b.column == null ? 99 : b.column) : k === "cleanup" ? b.cleanup.length : k === "worktree" ? (b.worktree ? 1 : 0) : b[k] == null ? "" : b[k]);
1355
+ rows.sort((a, b) => { const x = val(a), y = val(b); return (x > y ? 1 : x < y ? -1 : 0) * dir; });
1356
+ const cols = [["name", "Branch"], ["stage", "Stage"], ["ahead", "Ahead"], ["behind", "Behind"], ["merged", "Merged"], ["worktree", "Worktree"], ["lastActivityAt", "Last commit"], ["cleanup", "Cleanup"]];
1357
+ $("#btable").innerHTML = "<thead><tr>" + cols.map(([c, l]) => '<th data-sort="' + c + '" scope="col">' + l + (c === k ? (dir > 0 ? " ▲" : " ▼") : "") + "</th>").join("") + "</tr></thead><tbody>" +
1358
+ rows.map((b) => '<tr><td><span class="mono">' + esc(b.name) + "</span>" + (b.remote ? ' <span class="b dim">remote</span>' : "") + (b.pr ? " " + prChip(Object.assign({}, b.pr, { ci: null })) : "") + (b.error ? '<div class="err">' + esc(b.error) + "</div>" : "") + "</td>" +
1359
+ "<td>" + (b.remote ? '<span class="dim">—</span>' : esc(stageName(b.column)) + split(b.counts)) + "</td><td>" + (b.ahead == null ? "—" : b.ahead) + "</td><td>" + (b.behind == null ? "—" : b.behind) + "</td><td>" + esc(b.merged) + "</td>" +
1360
+ "<td>" + (b.worktree ? '<a href="' + wtLink(b.worktree) + '">open</a>' : '<span class="dim">none</span>') + "</td>" +
1361
+ '<td title="' + esc(when(b.at) + " · " + (b.subject || "")) + '">' + ago(b.at) + "</td>" +
1362
+ "<td>" + b.cleanup.map((c) => '<span class="b warn">' + esc(c) + "</span>").join(" ") + "</td></tr>").join("") + "</tbody>";
1363
+ const cand = S.branches.filter((b) => b.cleanup.length && (ui.all || !b.remote));
1364
+ $("#cleanup").innerHTML = cand.length ? '<ul class="plain attn">' + cand.map((b) => '<li><span class="mono">' + esc(b.name) + "</span> " + b.cleanup.map((c) => '<span class="b warn">' + esc(c) + "</span>").join(" ") +
1365
+ (b.worktree ? ' <a href="' + wtLink(b.worktree, "health") + '">worktree</a>' : "") + ' <span class="dim">last commit ' + ago(b.at) + "</span></li>").join("") + "</ul><p class=\"dim\">The Actions tab has the commands.</p>" : '<p class="ok">No cleanup candidates.</p>';
1366
+ }
1367
+
1368
+ function groupsHtml(groups) {
1369
+ return groups.length ? '<ul class="plain">' + groups.map((g) => "<li><b>" + esc(g.label) + '</b> <span class="dim">' + g.commits + " commit" + (g.commits === 1 ? "" : "s") + " · " + ago(g.at) + "</span>" + (g.branches.length ? '<div class="dim">' + esc(g.branches.join(", ")) + "</div>" : "") + "</li>").join("") + "</ul>" : "";
1370
+ }
1371
+ function fillEnvironments() {
1372
+ $("#envs").innerHTML = S.envs.map((e) => '<div class="panel' + flashIf("envp:" + e.name, String(e.sha) + e.error) + '"><h3>' + esc(e.name) + '</h3><dl class="kv">' +
1373
+ "<dt>Deployed commit</dt><dd>" + (e.sha ? '<span class="mono">' + esc(e.short) + "</span>" : '<span class="bad">unknown</span>' + (e.error ? ' <span class="dim">' + esc(e.error) + "</span>" : "")) + "</dd>" +
1374
+ "<dt>Version</dt><dd>" + esc(e.version || "—") + "</dd><dt>Deployed</dt><dd>" + (e.deployedAt ? when(e.deployedAt) : "time unknown") + "</dd>" +
1375
+ "<dt>Verified</dt><dd>" + (e.verified == null ? "—" : e.verified ? "yes" : "no") + "</dd>" +
1376
+ '<dt>Source of truth</dt><dd class="mono">' + esc(e.source) + "</dd>" +
1377
+ "<dt>Waiting to ship</dt><dd>" + (e.waiting == null ? "unknown" : e.waiting) + "</dd></dl></div>").join("") || '<p class="dim">No environments configured.</p>';
1378
+ const d = S.drift, out = [];
1379
+ if (!d) { $("#drift").innerHTML = '<p class="err">Drift could not be read.</p>'; $("#warn").innerHTML = ""; return; }
1380
+ for (const e of d.envs) out.push('<div class="panel"><h3>' + esc(S.remote + "/" + S.base) + " → " + esc(e.name) + "</h3>" + (e.behind == null ? '<p class="dim">Deployed commit unknown, so drift is unknown.</p>' :
1381
+ "<p>" + (e.behind ? '<span class="warn">' + e.behind + " commits not deployed</span>" : '<span class="ok">nothing waiting</span>') + "</p>" + groupsHtml(e.groups)) + "</div>");
1382
+ for (const b of d.between) out.push('<div class="panel"><h3>' + esc(b.from) + " → " + esc(b.to) + "</h3><p>" + (b.ahead ? '<span class="warn">' + b.ahead + " commits in " + esc(b.from) + " not in " + esc(b.to) + "</span>" : '<span class="ok">in step</span>') + "</p>" + groupsHtml(b.groups) + "</div>");
1383
+ $("#drift").innerHTML = out.join("");
1384
+ const w = [];
1385
+ if (d.local) w.push(d.local.ahead || d.local.behind ? '<li><span class="b warn">local ' + esc(S.base) + "</span> " + (d.local.ahead ? d.local.ahead + " ahead of " + esc(S.remote + "/" + S.base) + " (not pushed) " : "") + (d.local.behind ? d.local.behind + " behind" : "") + "</li>" : '<li><span class="b ok">local ' + esc(S.base) + "</span> in step with " + esc(S.remote + "/" + S.base) + "</li>");
1386
+ for (const e of d.envs.filter((x) => x.hotfixCount)) w.push('<li><span class="b bad">hotfix</span> ' + e.hotfixCount + " commits in " + esc(e.name) + " are not in " + esc(S.remote + "/" + S.base) + ': <ul class="plain mono">' + e.hotfixes.map((h) => "<li>" + esc(h.sha + " " + h.subject) + "</li>").join("") + "</ul></li>");
1387
+ $("#warn").innerHTML = '<ul class="plain attn">' + w.join("") + "</ul>";
1388
+ }
1389
+
1390
+ function fillActions() {
1391
+ const all = S.actions.concat(ui.showHidden ? S.hiddenActions : []);
1392
+ const cats = [...new Set(S.actions.concat(S.hiddenActions).map((a) => a.category))].sort();
1393
+ const tgts = [...new Set(S.actions.concat(S.hiddenActions).map((a) => a.target.label))].sort();
1394
+ const setOpts = (sel, list, cur) => { const html = '<option value="">All</option>' + list.map((x) => '<option' + (x === cur ? " selected" : "") + ">" + esc(x) + "</option>").join(""); if (sel.innerHTML !== html) sel.innerHTML = html; };
1395
+ setOpts($("#cat"), cats, ui.cat); setOpts($("#tgt"), tgts, ui.tgt);
1396
+ const list = all.filter((a) => (!ui.cat || a.category === ui.cat) && (!ui.tgt || a.target.label === ui.tgt));
1397
+ $("#acount").textContent = S.actions.length + " open" + (S.hiddenActions.length ? ", " + S.hiddenActions.length + " hidden" : "");
1398
+ $("#alist").innerHTML = PRI.map((p) => { const xs = list.filter((a) => a.priority === p); return xs.length ? '<h2 class="p-' + p + '" style="color:var(--p)">' + p + " (" + xs.length + ")</h2>" + xs.map(actionHtml).join("") : ""; }).join("") || '<p class="ok">No actions.</p>';
1399
+ // The side panel: the open actions in this view (filters applied, hidden ones left out) as one prompt.
1400
+ const open = list.filter((a) => !a.hidden), text = promptFor(open);
1401
+ $("#phint").textContent = open.length ? open.length + " action" + (open.length === 1 ? "" : "s") + " in this view" + (ui.cat || ui.tgt ? " (filtered)" : "") + ", most urgent first. Change the filters to change the prompt." : "No open actions in this view.";
1402
+ if ($("#prompt").value !== text) $("#prompt").value = text;
1403
+ $("#copyall").dataset.copy = text; $("#copyall").disabled = !open.length;
1404
+ }
1405
+ function promptFor(list) {
1406
+ if (!list.length) return "";
1407
+ const steps = list.map((a, i) => (i + 1) + ". [" + a.priority + ", " + a.category + "] " + a.title + "\n Why: " + a.why +
1408
+ (a.items ? "\n Covers: " + a.items.map((x) => x.target.label).join(", ") : "") + "\n Suggested: " + a.command.split("\n").join("\n "));
1409
+ return S.prompt.replace("{main}", S.mainPath).replace("{count}", list.length) + "\n\n" + steps.join("\n\n");
1410
+ }
1411
+
1412
+ // ---------- worktree drill-down
1413
+ async function loadDetail() {
1414
+ const key = ui.wt;
1415
+ try {
1416
+ const r = await fetch("/api/worktree/" + encodeURIComponent(key));
1417
+ if (key !== ui.wt) return;
1418
+ ui.detail = r.ok ? await r.json() : { key: key, error: "This worktree is gone.", errors: [], actions: [] };
1419
+ } catch (e) { ui.detail = { key: key, error: "Could not load: " + e.message, errors: [], actions: [] }; }
1420
+ fillWorktree();
1421
+ }
1422
+ function fillWorktree() {
1423
+ const d = ui.detail;
1424
+ if (!d) return;
1425
+ const p = d.plan, n = (d.actions || []).filter((a) => !a.hidden).length;
1426
+ $("#wthead").innerHTML = '<div class="wthead"><div class="arow"><a href="#tab=' + ui.top + '">← back</a><b style="font-size:15px;word-break:break-all">' + esc(d.branch || d.key) + "</b>" + (n ? '<a class="b warn" href="' + wtLink(d.key, "actions") + '">' + n + " action" + (n === 1 ? "" : "s") + "</a>" : "") + prChip(d.pr) + "</div>" +
1427
+ '<div class="dim mono" style="font-size:12px">' + esc(d.path) + " · base " + esc(d.base || S.base) + " · HEAD " + esc(d.head) + "</div>" +
1428
+ (p && p.total ? '<div><div class="bar"><i style="width:' + (p.pct || 0) + '%"></i></div><div class="dim">' + p.done + " of " + p.total + " steps — " + p.pct + "%</div></div>" : '<div class="dim">No plan</div>') +
1429
+ (d.stage ? tracker(d.stage.segments, d.pr, true) + trackLabels() : "") + (d.error ? '<div class="err">' + esc(d.error) + "</div>" : "") + "</div>";
1430
+ $("#wtabs").innerHTML = WT.map(([k, l]) => '<a href="' + wtLink(d.key, k) + '"' + (ui.wtab === k ? ' aria-current="page"' : "") + ">" + l + (k === "actions" && n ? '<span class="count">' + n + "</span>" : "") + "</a>").join("");
1431
+ $("#wtbody").innerHTML = ({ summary: tabSummary, plan: tabPlan, delivery: tabDelivery, changes: tabChanges, commits: tabCommits, health: tabHealth, actions: tabActions })[ui.wtab](d);
1432
+ }
1433
+ function steps(list, curLine) {
1434
+ return '<ul class="steps">' + list.map((s) => '<li class="s-' + s.state + (s.line === curLine ? " s-current" : "") + '"><span>' + esc(s.text) + "</span>" + (s.steps.length ? steps(s.steps, curLine) : "") + "</li>").join("") + "</ul>";
1435
+ }
1436
+ function sparkline(h) {
1437
+ if (!h || h.length < 2) return '<p class="dim">The line starts with the next change in progress.</p>';
1438
+ const t0 = h[0][0], t1 = Date.now(), w = 300, ht = 40;
1439
+ const pts = h.concat([[t1, h[h.length - 1][1]]]).map(([t, v]) => ((t - t0) / Math.max(1, t1 - t0) * w).toFixed(1) + "," + (ht - (v / 100) * ht).toFixed(1)).join(" ");
1440
+ return '<svg viewBox="0 0 ' + w + " " + ht + '" style="width:100%;max-width:420px;height:50px" role="img" aria-label="progress over time"><polyline fill="none" stroke="var(--ok)" stroke-width="2" points="' + pts + '"/></svg><div class="dim">' + h[0][1] + "% " + ago(t0) + " → " + h[h.length - 1][1] + "% " + ago(h[h.length - 1][0]) + "</div>";
1441
+ }
1442
+ function tabSummary(d) {
1443
+ const p = d.plan, f = d.files || {}, top = (d.actions || []).filter((a) => !a.hidden).slice(0, 3);
1444
+ return '<div class="grid2">' +
1445
+ '<div class="panel"><h3>Plan at a glance</h3>' + (p ? '<dl class="kv"><dt>Plan</dt><dd>' + esc(p.title || p.path) + '</dd><dt>Progress</dt><dd>' + (p.total ? p.done + " of " + p.total + " steps — " + p.pct + "%" : "no checkbox steps") + "</dd><dt>Current step</dt><dd>" + (p.current ? esc(p.current.text) : "—") + '</dd><dt>File</dt><dd class="mono">' + esc(p.path) + "</dd></dl>" : "<p><b>No plan</b></p>") + "</div>" +
1446
+ '<div class="panel"><h3>Delivery at a glance</h3><dl class="kv"><dt>Furthest stage, all work</dt><dd>' + esc(d.stage ? stageName(d.stage.column) : "—") + "</dd><dt>Commits</dt><dd>" + esc(d.stage ? d.stage.text : "—") + "</dd><dt>Merged</dt><dd>" + esc(d.merged || "—") + "</dd><dt>PR</dt><dd>" + (d.pr ? prChip(d.pr) : "none") + "</dd></dl></div>" +
1447
+ '<div class="panel"><h3>Working tree at a glance</h3><dl class="kv"><dt>Uncommitted</dt><dd>' + ((d.dirty && d.dirty.total) || 0) + " files" + (d.dirty && d.dirty.oldestAt ? ", oldest " + ago(d.dirty.oldestAt) : "") + "</dd><dt>Conflicted</dt><dd>" + (f.conflicted || []).length + "</dd><dt>Against " + esc(S.base) + "</dt><dd>" + (d.ahead || 0) + " ahead, " + (d.behind || 0) + " behind</dd><dt>Last activity</dt><dd>" + ago(d.lastActivityAt) + "</dd></dl></div>" +
1448
+ "</div><h2>Top actions</h2>" + (top.map(actionHtml).join("") || '<p class="ok">Nothing to do here.</p>');
1449
+ }
1450
+ function tabPlan(d) {
1451
+ const p = d.plan;
1452
+ if (!p) return '<h2>Plan</h2><p><b>No plan</b></p><p class="dim">No plan file was found in this worktree, so no percentage is shown. The README lists where the dashboard looks.</p>';
1453
+ return "<h2>Plan</h2><h3>" + esc(p.title || p.path) + '</h3><p class="dim mono">' + esc(p.path) + "</p>" + (p.summary ? "<p>" + esc(p.summary) + "</p>" : "") +
1454
+ '<dl class="kv"><dt>Steps</dt><dd>' + p.total + " total · " + p.done + " done · " + p.doing + " in progress · " + p.remaining + " remaining</dd>" +
1455
+ "<dt>Current step</dt><dd>" + (p.current ? esc(p.current.text) + (p.current.phase ? ' <span class="dim">(' + esc(p.current.phase) + ")</span>" : "") : "—") + "</dd></dl>" +
1456
+ "<h2>Progress over time</h2>" + sparkline(d.history) + "<h2>Phases</h2>" +
1457
+ (p.total ? p.phases.map((ph) => '<div class="phase"><h4><span>' + esc(ph.title) + '</span><span class="dim">' + ph.done + "/" + ph.total + " · " + ph.pct + '%</span></h4><div class="bar"><i style="width:' + ph.pct + '%"></i></div>' + steps(ph.steps, p.current && p.current.line) + "</div>").join("") : '<p class="dim">The plan has no checkbox steps.</p>');
1458
+ }
1459
+ function stageBadge(c) {
1460
+ const name = S.stages[c.stage] ? S.stages[c.stage].label : "?";
1461
+ const squash = Object.values(c.in || {}).includes("squash");
1462
+ const cls = c.stage >= 6 ? "ok" : c.stage >= 4 ? "acc" : c.stage >= 2 ? "info" : "warn";
1463
+ return '<span class="b ' + cls + '">' + esc(name) + "</span>" + (squash ? ' <span class="b ok" title="' + esc("equal by patch to " + (c.eq || "a commit")) + '">merged (squash)</span>' : "");
1464
+ }
1465
+ function tabDelivery(d) {
1466
+ if (!d.stage) return '<p class="err">' + esc(d.error || "No delivery data.") + "</p>";
1467
+ return "<h2>Stage</h2>" + tracker(d.stage.segments, d.pr, true) + trackLabels() + "<p><b>" + esc(stageName(d.stage.column)) + "</b> is the furthest stage all of this work has reached. " + esc(d.stage.text) + ".</p>" +
1468
+ "<h2>Pull request</h2>" + (d.pr ? "<p>" + prChip(d.pr) + " " + esc(d.pr.title) + (d.pr.mergedAt ? " · merged " + when(d.pr.mergedAt) : "") + "</p>" : '<p class="dim">No pull request' + (S.gh.available ? "." : " (gh unavailable: " + esc(S.gh.error || "") + ").") + "</p>") +
1469
+ "<h2>Commits since " + esc(d.start || "the merge-base") + " (newest 30 of " + d.commitCount + ")</h2>" +
1470
+ (d.commits.length ? d.commits.map((c) => '<div class="commit"><span class="mono dim">' + esc(c.sha) + '</span><span class="msg">' + esc(c.subject) + '<div class="dim" style="font-size:11px">' + esc(c.author || "") + " · " + ago(c.at) +
1471
+ (c.release ? " · brought in by " + esc(c.release.label) : "") + (c.firstTag ? " · first in " + esc(Object.entries(c.firstTag).map(([e, t]) => e + " " + t).join(", ")) : "") + "</div></span>" + stageBadge(c) + "</div>").join("") : '<p class="dim">No commits of its own yet.</p>');
1472
+ }
1473
+ function fileList(title, list, cls) { return "<h2>" + esc(title) + " (" + (list || []).length + ")</h2>" + (list && list.length ? '<ul class="plain files">' + list.map((f) => '<li><span class="' + cls + '">' + esc(f.code) + "</span> " + esc(f.path) + "</li>").join("") + "</ul>" : '<p class="dim">none</p>'); }
1474
+ function tabChanges(d) {
1475
+ const f = d.files || {}, x = d.diff;
1476
+ return fileList("Conflicted", f.conflicted, "bad") + fileList("Staged", f.staged, "ok") + fileList("Unstaged", f.unstaged, "warn") + fileList("Untracked", f.untracked, "dim") +
1477
+ "<h2>Against the merge-base " + esc(d.mergeBase || "") + "</h2>" + (x ? "<p>" + x.files + " files, +" + x.insertions + " −" + x.deletions + "</p><h2>Top changed folders</h2>" +
1478
+ (x.topDirs.length ? '<ul class="plain">' + x.topDirs.map((t) => '<li><span class="bar" style="width:160px;display:inline-block;vertical-align:middle"><i style="width:' + Math.round(t.weight * 100 / x.topDirs[0].weight) + '%"></i></span> <span class="mono">' + esc(t.dir) + "</span></li>").join("") + "</ul>" : '<p class="dim">none</p>') : '<p class="dim">—</p>');
1479
+ }
1480
+ function tabCommits(d) {
1481
+ const per = d.perDay || [], max = Math.max(1, ...per);
1482
+ const bars = '<svg viewBox="0 0 300 60" style="width:100%;max-width:520px;height:70px" role="img" aria-label="commits per day">' + per.map((n, i) => '<rect x="' + i * 10 + '" y="' + (60 - (n / max) * 56) + '" width="8" height="' + (n / max) * 56 + '" fill="var(--acc)"><title>' + n + " commits, " + (29 - i) + " days ago</title></rect>").join("") + "</svg>";
1483
+ return "<h2>Commits per day, last 30 days</h2>" + bars + "<h2>Timeline since " + esc(d.start || "the merge-base") + "</h2>" +
1484
+ (d.commits && d.commits.length ? '<ul class="plain">' + d.commits.map((c) => '<li><span class="dim">' + when(c.at) + '</span> <span class="mono">' + esc(c.sha) + "</span> " + esc(c.subject) + (c.merge ? ' <span class="b dim">merge</span>' : "") + "</li>").join("") + "</ul>" : '<p class="dim">No commits of its own yet.</p>');
1485
+ }
1486
+ function tabHealth(d) {
1487
+ const u = d.upstream, ci = d.pr && d.pr.ci;
1488
+ return '<h2>Health</h2><dl class="kv"><dt>Against ' + esc(S.base) + "</dt><dd>" + (d.ahead == null ? "—" : d.ahead) + " ahead, " + (d.behind == null ? "—" : d.behind) + " behind</dd>" +
1489
+ "<dt>Upstream</dt><dd>" + (u ? esc(u.name) + (u.gone ? ' <span class="bad">gone</span>' : " · " + u.ahead + " ahead, " + u.behind + " behind") : "none (never pushed)") + "</dd>" +
1490
+ "<dt>Merged</dt><dd>" + esc(d.merged || "—") + "</dd>" +
1491
+ "<dt>Last activity</dt><dd>" + when(d.lastActivityAt) + (d.stale ? ' <span class="b dim">stale</span>' : "") + "</dd>" +
1492
+ "<dt>Commits</dt><dd>" + (d.commits24h || 0) + " in 24 h · " + (d.commits7d || 0) + " in 7 days</dd>" +
1493
+ "<dt>Status read</dt><dd>" + ago(d.statusAt) + "</dd>" +
1494
+ "<dt>Lock</dt><dd>" + (d.locked ? esc(d.locked) : "not locked") + "</dd><dt>Prunable</dt><dd>" + (d.prunable ? esc(d.prunable) : "no") + "</dd>" +
1495
+ "<dt>CI</dt><dd>" + (ci && ci.total ? ci.passed + " passed, " + ci.failed + " failed, " + ci.pending + " pending" : "no checks") + "</dd></dl>" +
1496
+ "<h2>Stash</h2>" + (d.stash && d.stash.length ? '<ul class="plain">' + d.stash.map((s) => '<li><span class="mono">' + esc(s.ref) + "</span> " + esc(s.subject) + ' <span class="dim">' + ago(s.at) + "</span></li>").join("") + "</ul>" : '<p class="dim">none</p>') +
1497
+ "<h2>Collection errors</h2>" + (d.errors && d.errors.length ? '<ul class="plain err">' + d.errors.map((e) => "<li>" + esc(e) + "</li>").join("") + "</ul>" : '<p class="ok">none</p>');
1498
+ }
1499
+ function tabActions(d) {
1500
+ const xs = d.actions || [], open = xs.filter((a) => !a.hidden), hid = xs.filter((a) => a.hidden);
1501
+ return PRI.map((p) => { const ys = open.filter((a) => a.priority === p); return ys.length ? '<h2 class="p-' + p + '" style="color:var(--p)">' + p + "</h2>" + ys.map(actionHtml).join("") : ""; }).join("") +
1502
+ (open.length ? "" : '<p class="ok">Nothing to do here.</p>') + (hid.length ? "<h2>Hidden</h2>" + hid.map(actionHtml).join("") : "");
1503
+ }
1504
+
1505
+ // ---------- events
1506
+ document.addEventListener("click", async (e) => {
1507
+ const t = e.target.closest("[data-sort],[data-f],[data-copy],[data-act],#theme");
1508
+ if (!t) return;
1509
+ if (t.id === "theme") { const cur = document.documentElement.dataset.theme || (matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"); const next = cur === "dark" ? "light" : "dark"; document.documentElement.dataset.theme = next; try { localStorage.setItem("wtd-theme", next); } catch (_) {} }
1510
+ else if (t.dataset.sort) { ui.bsort = [t.dataset.sort, ui.bsort[0] === t.dataset.sort ? -ui.bsort[1] : 1]; fillBranches(); }
1511
+ else if (t.dataset.f) { ui.f.has(t.dataset.f) ? ui.f.delete(t.dataset.f) : ui.f.add(t.dataset.f); t.setAttribute("aria-pressed", ui.f.has(t.dataset.f)); fillWorktrees(); }
1512
+ else if (t.dataset.copy !== undefined) { const was = t.textContent; try { await navigator.clipboard.writeText(t.dataset.copy); t.textContent = "Copied"; } catch (_) { t.textContent = "Select it"; } setTimeout(() => { t.textContent = was; }, 1500); }
1513
+ else if (t.dataset.act) await act(t.dataset.id, t.dataset.act);
1514
+ });
1515
+ document.addEventListener("change", (e) => {
1516
+ const t = e.target;
1517
+ if (t.id === "sort") { ui.sort = t.value; fillWorktrees(); }
1518
+ else if (t.id === "stage") { ui.stage = t.value; fillWorktrees(); }
1519
+ else if (t.id === "all") { ui.all = t.checked; fillBranches(); }
1520
+ else if (t.id === "cat") { ui.cat = t.value; fillActions(); }
1521
+ else if (t.id === "tgt") { ui.tgt = t.value; fillActions(); }
1522
+ else if (t.id === "showhidden") { ui.showHidden = t.checked; fillActions(); }
1523
+ else if (t.dataset.snooze && t.value) act(t.dataset.snooze, "snooze", t.value);
1524
+ });
1525
+ document.addEventListener("input", (e) => { if (e.target.id === "q") { ui.q = e.target.value; fillWorktrees(); } });
1526
+ async function act(id, verb, hours) {
1527
+ await fetch("/api/actions/" + encodeURIComponent(id) + "/" + verb + (hours ? "?hours=" + hours : ""), { method: "POST" });
1528
+ if (ui.wt) loadDetail();
1529
+ }
1530
+ try { const saved = localStorage.getItem("wtd-theme"); if (saved) document.documentElement.dataset.theme = saved; } catch (_) {}
1531
+
1532
+ function setLive(on) { connected = on; $("#dot").classList.toggle("on", on); }
1533
+ setInterval(() => { $("#ago").textContent = connected ? "updated " + ago(checkedAt) : S ? "disconnected, retrying…" : "connecting…"; }, 1000);
1534
+ let backoff = 1000;
1535
+ function connect() {
1536
+ const es = new EventSource("/events");
1537
+ es.addEventListener("snapshot", (e) => {
1538
+ backoff = 1000; setLive(true);
1539
+ const first = !S, prev = S && ui.wt ? (S.worktrees.find((w) => w.key === ui.wt) || {}).hash : null;
1540
+ S = JSON.parse(e.data); checkedAt = S.checkedAt;
1541
+ if (first) { ui.shell = ""; route(); return; }
1542
+ fill();
1543
+ if (ui.wt && (S.worktrees.find((w) => w.key === ui.wt) || {}).hash !== prev) loadDetail();
1544
+ else if (ui.wt) loadDetail();
1545
+ });
1546
+ es.addEventListener("tick", (e) => { backoff = 1000; setLive(true); checkedAt = JSON.parse(e.data).checkedAt; });
1547
+ es.onerror = () => { setLive(false); es.close(); setTimeout(connect, backoff); backoff = Math.min(backoff * 2, 30000); };
1548
+ }
1549
+ connect();
1550
+ </script>
1551
+ </body>
1552
+ </html>`;
1553
+
1554
+ if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) main();