fisi-dock 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/ci.ts ADDED
@@ -0,0 +1,208 @@
1
+ import { printable } from "./odd-detail.ts";
2
+ import type { CiCheck, CiInfo } from "./panel-model.ts";
3
+
4
+ // CI checks of the branch's last pushed commit (S64, artboard 24 option C):
5
+ // pure parsers for `gh run list --json` and `gh run view --json jobs` output.
6
+ // gh's shapes are restated here; anything unexpected reads as "unknown" and
7
+ // keeps what is shown, never a guessed state.
8
+
9
+ export interface CiRun {
10
+ /** gh's databaseId, for `gh run view`; absent when gh gave none. */
11
+ id?: number;
12
+ /** The workflow name, printable and bounded. */
13
+ name: string;
14
+ state: CiCheck["state"];
15
+ /** Epoch ms; absent when gh gave no usable time. */
16
+ createdAt?: number;
17
+ startedAt?: number;
18
+ updatedAt?: number;
19
+ failedJob?: string;
20
+ /** Failed only: `gh run view` answered for this id and updatedAt, so failedJob (absent: none named) is not read again (S66). */
21
+ jobRead?: true;
22
+ }
23
+
24
+ /** One commit's runs, one per workflow. */
25
+ export interface CiRuns {
26
+ sha: string;
27
+ runs: CiRun[];
28
+ /** Epoch ms of the successful list read that gave these runs (S66). */
29
+ readAt?: number;
30
+ }
31
+
32
+ /** Runs one gh command in the session folder; Pi's exec in the extension. */
33
+ export type CiExec = (args: string[]) => Promise<{ stdout: string; code: number }>;
34
+
35
+ const LIST_LIMIT = 20;
36
+ const LIST_FIELDS = "databaseId,workflowName,name,status,conclusion,startedAt,updatedAt,createdAt,headSha";
37
+ /** gh names past this many characters are cut (S64). */
38
+ const NAME_CAP = 80;
39
+ const SHORT_SHA = 7;
40
+ /** Past this long without a successful list read, a running check's time and spinner hold (S66). */
41
+ const STALE_MS = 90_000;
42
+
43
+ export function ciListArgs(branch: string): string[] {
44
+ return ["run", "list", "--branch", branch, "--limit", String(LIST_LIMIT), "--json", LIST_FIELDS];
45
+ }
46
+
47
+ export function ciViewArgs(id: number): string[] {
48
+ return ["run", "view", String(id), "--json", "jobs"];
49
+ }
50
+
51
+ const record = (value: unknown): Record<string, unknown> | undefined =>
52
+ value !== null && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;
53
+
54
+ /** A gh name as one printable, bounded line (S64, like odd-detail S61). */
55
+ function clean(value: unknown): string {
56
+ return typeof value === "string" ? printable(value).replace(/\s+/g, " ").trim().slice(0, NAME_CAP) : "";
57
+ }
58
+
59
+ /** An ISO time from gh as epoch ms; gh's zero time (a run not started) counts as none. */
60
+ function time(value: unknown): number | undefined {
61
+ const ms = typeof value === "string" ? Date.parse(value) : Number.NaN;
62
+ return Number.isFinite(ms) && ms > 0 ? ms : undefined;
63
+ }
64
+
65
+ function parse(stdout: string): unknown {
66
+ try {
67
+ return JSON.parse(stdout);
68
+ } catch {
69
+ return undefined;
70
+ }
71
+ }
72
+
73
+ const PASSED = new Set(["success", "skipped", "neutral"]);
74
+ const FAILED = new Set(["failure", "timed_out", "startup_failure", "action_required"]);
75
+
76
+ /** gh's status and conclusion as one state; a conclusion gh may add later reads as cancelled, never passed or failed. */
77
+ function runState(status: unknown, conclusion: unknown): CiCheck["state"] {
78
+ if (status === "completed") return PASSED.has(conclusion as string) ? "passed" : FAILED.has(conclusion as string) ? "failed" : "cancelled";
79
+ // queued, waiting, requested and pending, and any status gh may add later.
80
+ return status === "in_progress" ? "running" : "queued";
81
+ }
82
+
83
+ /** Newest first by createdAt; a tie or a missing time keeps gh's order (newest first). */
84
+ const newer = (a: number | undefined, b: number | undefined) => (a ?? -Infinity) > (b ?? -Infinity);
85
+
86
+ /**
87
+ * `gh run list --json` to the runs of its newest run's commit, one per
88
+ * workflow (the newest by createdAt). Undefined: not gh's list (keep what is
89
+ * shown); null: no runs (no section).
90
+ */
91
+ export function ciRunsFromList(stdout: string): CiRuns | null | undefined {
92
+ const list = parse(stdout);
93
+ if (!Array.isArray(list)) return undefined;
94
+ const runs = list.flatMap((value) => {
95
+ const entry = record(value);
96
+ const sha = clean(entry?.headSha);
97
+ if (!entry || !sha) return [];
98
+ const id = typeof entry.databaseId === "number" && Number.isSafeInteger(entry.databaseId) && entry.databaseId > 0 ? entry.databaseId : undefined;
99
+ const times = { createdAt: time(entry.createdAt), startedAt: time(entry.startedAt), updatedAt: time(entry.updatedAt) };
100
+ const run: CiRun = { name: clean(entry.workflowName) || clean(entry.name), state: runState(entry.status, entry.conclusion) };
101
+ if (id !== undefined) run.id = id;
102
+ for (const [key, ms] of Object.entries(times)) if (ms !== undefined) run[key as keyof typeof times] = ms;
103
+ return [{ sha, run }];
104
+ });
105
+ if (runs.length === 0) return null;
106
+ const newest = runs.reduce((best, entry) => (newer(entry.run.createdAt, best.run.createdAt) ? entry : best));
107
+ const byWorkflow = new Map<string, CiRun>();
108
+ for (const { sha, run } of runs) {
109
+ if (sha !== newest.sha) continue;
110
+ const known = byWorkflow.get(run.name);
111
+ if (!known || newer(run.createdAt, known.createdAt)) byWorkflow.set(run.name, run);
112
+ }
113
+ return { sha: newest.sha, runs: [...byWorkflow.values()] };
114
+ }
115
+
116
+ /** `gh run view --json jobs` to `<job> · <first failed step>` of its first failed job (the job alone without a failed step). */
117
+ export function failedJob(stdout: string): string | undefined {
118
+ return viewJob(stdout)?.job;
119
+ }
120
+
121
+ /** gh's view as its failed job (absent: none named); undefined when it is not gh's view. */
122
+ function viewJob(stdout: string): { job?: string } | undefined {
123
+ const jobs = record(parse(stdout))?.jobs;
124
+ if (!Array.isArray(jobs)) return undefined;
125
+ const job = jobs.map(record).find((entry) => entry?.conclusion === "failure");
126
+ const name = clean(job?.name);
127
+ if (!name) return {};
128
+ const steps = Array.isArray(job?.steps) ? job.steps : [];
129
+ const step = clean(steps.map(record).find((entry) => entry?.conclusion === "failure")?.name);
130
+ return { job: step ? `${name} · ${step}` : name };
131
+ }
132
+
133
+ async function ghOutput(exec: CiExec, args: string[]): Promise<string | undefined> {
134
+ try {
135
+ const result = await exec(args);
136
+ return result.code === 0 ? result.stdout : undefined;
137
+ } catch {
138
+ return undefined;
139
+ }
140
+ }
141
+
142
+ /**
143
+ * The branch's CI runs, each failed one with its failed job, stamped with
144
+ * `now()` once the list read succeeds. A failed run whose view already
145
+ * answered in `previous` for the same id and updatedAt keeps that answer
146
+ * without another `gh run view`; a failed view is retried (S66). Undefined:
147
+ * the read failed or timed out (keep what is shown); null: no runs.
148
+ */
149
+ export async function readCi(exec: CiExec, branch: string, previous?: CiRuns, now: () => number = Date.now): Promise<CiRuns | null | undefined> {
150
+ const stdout = await ghOutput(exec, ciListArgs(branch));
151
+ const read = stdout === undefined ? undefined : ciRunsFromList(stdout);
152
+ if (!read) return read;
153
+ const readAt = now();
154
+ const runs: CiRun[] = [];
155
+ for (const run of read.runs) {
156
+ if (run.state !== "failed" || run.id === undefined) {
157
+ runs.push(run);
158
+ continue;
159
+ }
160
+ const known = previous?.runs.find((other) => other.id === run.id && other.state === "failed" && other.updatedAt === run.updatedAt && other.jobRead);
161
+ const view = known ? { job: known.failedJob } : viewJob((await ghOutput(exec, ciViewArgs(run.id))) ?? "");
162
+ if (!view) runs.push(run);
163
+ else runs.push({ ...run, ...(view.job !== undefined ? { failedJob: view.job } : {}), jobRead: true });
164
+ }
165
+ return { sha: read.sha, runs, readAt };
166
+ }
167
+
168
+ /** Whole seconds from `from` to `to`; none when either is unknown. */
169
+ const span = (from: number | undefined, to: number | undefined) => (from !== undefined && to !== undefined ? { seconds: Math.max(0, Math.floor((to - from) / 1000)) } : {});
170
+
171
+ /**
172
+ * What the panel draws for `runs` at `now`: sorted by name, the running time
173
+ * to `now`, the others' durations. Over 90 s after the last successful read a
174
+ * running time stays at that read and its spinner holds (S66).
175
+ */
176
+ export function ciView(runs: CiRuns | undefined, now: number): CiInfo | undefined {
177
+ if (!runs?.runs.length) return undefined;
178
+ const stale = runs.readAt !== undefined && now - runs.readAt > STALE_MS;
179
+ const until = stale ? runs.readAt : now;
180
+ const checks = runs.runs
181
+ .map((run): CiCheck => ({
182
+ name: run.name,
183
+ state: run.state,
184
+ ...(run.state === "queued" ? {} : span(run.startedAt, run.state === "running" ? until : run.updatedAt)),
185
+ ...(run.state === "failed" && run.failedJob !== undefined ? { failedJob: run.failedJob } : {}),
186
+ }))
187
+ .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
188
+ const updates = runs.runs.flatMap((run) => (run.updatedAt !== undefined ? [run.updatedAt] : []));
189
+ return { sha: runs.sha.slice(0, SHORT_SHA), checks, ...(updates.length ? { endedAt: Math.max(...updates) } : {}), ...(stale ? { stale: true } : {}) };
190
+ }
191
+
192
+ /** True while a check runs and the last successful read is recent: its spinner turns and its m:ss ticks with the spinner clock. */
193
+ export function ciRunning(info: CiInfo | undefined): boolean {
194
+ return info !== undefined && !info.stale && info.checks.some((check) => check.state === "running");
195
+ }
196
+
197
+ /** True while a check runs or waits: gh is read every 30 s instead of every 3 min. */
198
+ export function ciLive(info: CiInfo | undefined): boolean {
199
+ return info?.checks.some((check) => check.state === "running" || check.state === "queued") ?? false;
200
+ }
201
+
202
+ const PUSH_TOOLS = new Set(["bash", "bash_background"]);
203
+
204
+ /** A bash or bash_background call whose command contains `git push`: CI starts soon after (S64). */
205
+ export function gitPushTool(toolName: string | undefined, args: unknown): boolean {
206
+ const command = record(args)?.command;
207
+ return PUSH_TOOLS.has(toolName ?? "") && typeof command === "string" && /\bgit\s+push\b/.test(command);
208
+ }
@@ -0,0 +1,49 @@
1
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+
4
+ /**
5
+ * Where `/fisi-dock on|off` is remembered across restarts (S95): Pi's agent dir
6
+ * (`PI_CODING_AGENT_DIR`, else `~/.pi/agent`), outside any repository.
7
+ */
8
+ export function dockStatePath(env: Record<string, string | undefined>, home: string): string {
9
+ return join(env.PI_CODING_AGENT_DIR || join(home, ".pi", "agent"), "fisi-dock", "state.json");
10
+ }
11
+
12
+ function readState(path: string): Record<string, unknown> | undefined {
13
+ try {
14
+ const state = JSON.parse(readFileSync(path, "utf8")) as unknown;
15
+ return state && typeof state === "object" && !Array.isArray(state) ? (state as Record<string, unknown>) : undefined;
16
+ } catch {
17
+ return undefined;
18
+ }
19
+ }
20
+
21
+ /** Off only when the file says `"enabled": false`; a missing, unreadable or malformed file means on. */
22
+ export function readDockEnabled(path: string): boolean {
23
+ return readState(path)?.enabled !== false;
24
+ }
25
+
26
+ /** The theme in use before `/fisi-dock on` (S7), for off to put back; undefined unless a non-empty string. */
27
+ export function readDockTheme(path: string): string | undefined {
28
+ const theme = readState(path)?.theme;
29
+ return typeof theme === "string" && theme !== "" ? theme : undefined;
30
+ }
31
+
32
+ /** Whether the first start already applied the Fisi-Dock theme once (T9): only `"themeApplied": true` says so. */
33
+ export function readDockThemeApplied(path: string): boolean {
34
+ return readState(path)?.themeApplied === true;
35
+ }
36
+
37
+ /**
38
+ * Saves `{ "enabled": …, "theme": …, "themeApplied": true }` (no theme key without one, no
39
+ * themeApplied key unless true), creating its folder. False when it could not be written.
40
+ */
41
+ export function writeDockEnabled(path: string, enabled: boolean, theme?: string, themeApplied = false): boolean {
42
+ try {
43
+ mkdirSync(dirname(path), { recursive: true });
44
+ writeFileSync(path, `${JSON.stringify({ enabled, ...(theme ? { theme } : {}), ...(themeApplied ? { themeApplied } : {}) })}\n`);
45
+ return true;
46
+ } catch {
47
+ return false;
48
+ }
49
+ }
@@ -0,0 +1,68 @@
1
+ import { bold, fg, type Rgb } from "./palette.ts";
2
+
3
+ // A new row's entrance (S54), from artboard 16
4
+ // (design/gentle-shell-redesign/16-agents-entrance.html, paint): the row
5
+ // flashes bold in its section color, fading to its own colors over 3 steps,
6
+ // then one white shine crosses it once, one char per step, and it settles into
7
+ // its normal look. Colors only, so the row keeps its width. Steps are 75 ms
8
+ // (SHIMMER_STEP_MS) since the row appeared.
9
+
10
+ export const ENTRANCE_FLASH_STEPS = 3;
11
+ /** Where the shine head is on the first step after the flash. */
12
+ const HEAD_START = -2;
13
+ /** Cells the head travels past the last char before the entrance ends. */
14
+ const HEAD_EXIT = 2;
15
+ /** Head, then its neighbours at distance 1 and 2; same shades as the ODD label shine. */
16
+ const SHINE: readonly Rgb[] = [[0xff, 0xff, 0xff], [0xc8, 0xc8, 0xc8], [0x9a, 0x9a, 0x9a]];
17
+
18
+ /** One styled run of a row's text: its normal color and weight. */
19
+ export interface EntrancePiece {
20
+ text: string;
21
+ color: Rgb;
22
+ bold?: boolean;
23
+ }
24
+
25
+ /** `from` moved `t` of the way to `to`, per channel, rounded like the artboard. */
26
+ export function mixColor(from: Rgb, to: Rgb, t: number): Rgb {
27
+ return from.map((channel, index) => Math.round(channel * (1 - t) + to[index] * t)) as unknown as Rgb;
28
+ }
29
+
30
+ /** Steps the entrance of `text` lasts: the flash, then the head from -2 to 2 past the end. */
31
+ export function entranceSteps(text: string): number {
32
+ return ENTRANCE_FLASH_STEPS + Array.from(text).length + HEAD_EXIT - HEAD_START + 1;
33
+ }
34
+
35
+ /** True during the flash, when the row's glyph wears the section color too. */
36
+ export function entranceFlash(step: number | undefined): boolean {
37
+ return step !== undefined && Number.isFinite(step) && step >= 0 && step < ENTRANCE_FLASH_STEPS;
38
+ }
39
+
40
+ /** `pieces` at entrance `step`; undefined without a step or once it is over, and the caller draws the normal row. */
41
+ export function entranceText(pieces: readonly EntrancePiece[], sectionColor: Rgb, step: number | undefined): string | undefined {
42
+ if (step === undefined || !Number.isFinite(step) || step < 0) return undefined;
43
+ const at = Math.floor(step);
44
+ const chars = pieces.flatMap((piece) => Array.from(piece.text).map((char) => ({ char, color: piece.color, bold: piece.bold === true })));
45
+ if (at >= entranceSteps(chars.map((entry) => entry.char).join(""))) return undefined;
46
+ const flash = at < ENTRANCE_FLASH_STEPS;
47
+ const head = at - ENTRANCE_FLASH_STEPS + HEAD_START;
48
+ let out = "";
49
+ let run = "";
50
+ let runColor: Rgb | undefined;
51
+ let runBold = false;
52
+ const flush = () => {
53
+ if (run && runColor) out += runBold ? bold(fg(runColor, run)) : fg(runColor, run);
54
+ run = "";
55
+ };
56
+ chars.forEach((entry, index) => {
57
+ const color = flash ? mixColor(sectionColor, entry.color, at / ENTRANCE_FLASH_STEPS) : (SHINE[Math.abs(index - head)] ?? entry.color);
58
+ const heavy = flash || entry.bold;
59
+ if (!runColor || color.join() !== runColor.join() || heavy !== runBold) {
60
+ flush();
61
+ runColor = color;
62
+ runBold = heavy;
63
+ }
64
+ run += entry.char;
65
+ });
66
+ flush();
67
+ return out;
68
+ }
package/lib/header.ts ADDED
@@ -0,0 +1,86 @@
1
+ import { bold, fg, palette, type Rgb } from "./palette.ts";
2
+ import type { McpServerInfo, PanelModel } from "./panel-model.ts";
3
+ import { contextColor, usageParts } from "./panel.ts";
4
+ import { ellipsize, truncateToWidth, visibleWidth } from "./text.ts";
5
+
6
+ // Design 07's top row carries only the project path. Model and effort live on
7
+ // the prompt line, context and cost in the panel, so nothing repeats (S8).
8
+
9
+ const ELLIPSIS = "…";
10
+
11
+ /** The session cwd as Gentle Shell's header shows it: home shortened to ~. */
12
+ export function headerPath(cwd: string, home: string | undefined): string {
13
+ if (home && cwd.startsWith(home)) return `~${cwd.slice(home.length)}`;
14
+ return cwd;
15
+ }
16
+
17
+ /** The last `width` columns of plain text. */
18
+ function takeEnd(text: string, width: number): string {
19
+ const points = [...text];
20
+ let out = "";
21
+ for (let index = points.length - 1; index >= 0; index--) {
22
+ if (visibleWidth(points[index] + out) > width) break;
23
+ out = points[index] + out;
24
+ }
25
+ return out;
26
+ }
27
+
28
+ /** Fit a path into `width` columns, cutting the middle so the start and the last folder stay. */
29
+ export function fitPath(path: string, width: number): string {
30
+ if (visibleWidth(path) <= width) return path;
31
+ if (width <= 0) return "";
32
+ const cut = Math.max(path.lastIndexOf("\\"), path.lastIndexOf("/"));
33
+ const last = cut > 0 ? path.slice(cut) : path;
34
+ const head = width - 1 - visibleWidth(last);
35
+ if (head >= 1) return truncateToWidth(path, head) + ELLIPSIS + last;
36
+ return ELLIPSIS + takeEnd(path, width - 1);
37
+ }
38
+
39
+ const METER_CELLS = 4;
40
+ const GAP = " ";
41
+ const MCP_DOT: Record<McpServerInfo["state"], Rgb> = { connected: palette.green, failing: palette.red, unknown: palette.faint };
42
+
43
+ /**
44
+ * The top row while the rail is hidden (S33): Gentle Shell's narrow header
45
+ * showed model, context and cost; ours shows project · branch, a short context
46
+ * meter, cost and MCP dots. The model and effort are on the prompt frame (S8).
47
+ * Segments drop from the right to fit; the project is cut last.
48
+ */
49
+ export function renderNarrowHeader(model: PanelModel, width: number): string[] {
50
+ const columns = Math.max(0, Math.floor(width));
51
+ if (columns === 0) return [];
52
+ const { session } = model;
53
+ const pad = columns >= 2 ? " " : "";
54
+ const project = bold(fg(palette.text, session.project));
55
+ const segments: string[] = [];
56
+ if (session.branch) segments.push(fg(palette.faint, " · ") + fg(palette.green, session.branch));
57
+ if (session.contextPercent !== undefined) {
58
+ const percent = Math.max(0, Math.min(100, session.contextPercent));
59
+ const on = percent > 0 ? Math.max(1, Math.round((percent / 100) * METER_CELLS)) : 0;
60
+ const bar = fg(contextColor(percent), "▰".repeat(on)) + fg(palette.faint, "▱".repeat(METER_CELLS - on));
61
+ segments.push(`${GAP}${bar} ${fg(palette.text, `${Math.round(percent)}%`)}`);
62
+ }
63
+ if (model.footer) {
64
+ const dollars = Number.isFinite(model.footer.cost) ? model.footer.cost : 0;
65
+ // A subscription records tokens but cost 0: tokens and the ≈ estimate instead (S37).
66
+ segments.push(GAP + fg(palette.muted, usageParts(model.footer)?.join("") ?? `$${dollars.toFixed(3)}`));
67
+ }
68
+ if (session.mcp?.length) segments.push(GAP + session.mcp.map((server) => fg(MCP_DOT[server.state] ?? palette.faint, "●")).join(""));
69
+ // S36: a full-width rule in the panel frame gray keeps the conversation below from blending in.
70
+ const rule = fg(palette.frame, "─".repeat(columns));
71
+ for (let count = segments.length; count > 0; count--) {
72
+ const line = pad + project + segments.slice(0, count).join("");
73
+ if (visibleWidth(line) <= columns) return [line, rule];
74
+ }
75
+ return [pad + ellipsize(project, columns - pad.length), rule];
76
+ }
77
+
78
+ /** One muted line with the path, or no line for an empty path or zero width. */
79
+ export function renderHeaderLine(path: string, width: number): string[] {
80
+ const columns = Math.max(0, Math.floor(width));
81
+ if (!path || columns === 0) return [];
82
+ // One column of left padding, like the header text start in Gentle Shell's
83
+ // float style; dropped when the width leaves no room for it.
84
+ const pad = columns >= 2 ? " " : "";
85
+ return [pad + fg(palette.muted, fitPath(path, columns - pad.length))];
86
+ }
@@ -0,0 +1,223 @@
1
+ import { readdir, readFile, stat } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import type { GitExec } from "./live-store.ts";
4
+ import type { HeadsUpWarning } from "./panel-model.ts";
5
+
6
+ // Heads-up (S14): things left open in the project. Pure parsers for git output
7
+ // and ODD feature documents, plus failure-tolerant readers: a source that
8
+ // cannot be read is simply absent, it never raises.
9
+
10
+ // --- worktrees ---------------------------------------------------------------
11
+
12
+ /** Forward slashes, no trailing slash; Windows drive paths compare case-insensitively. */
13
+ function normalizePath(path: string): string {
14
+ const slashed = path.trim().replaceAll("\\", "/").replace(/\/+$/, "");
15
+ return /^[a-z]:\//i.test(slashed) ? slashed.toLowerCase() : slashed;
16
+ }
17
+
18
+ /**
19
+ * `git worktree list --porcelain` to the worktrees other than the session's:
20
+ * bare and prunable entries are skipped, and the session's own worktree is
21
+ * the one with the longest path containing `cwd`.
22
+ */
23
+ export function otherWorktrees(porcelain: string | undefined, cwd: string): string[] {
24
+ const entries: { path: string; usable: boolean }[] = [];
25
+ for (const block of (porcelain ?? "").split(/\r?\n\r?\n/)) {
26
+ const lines = block.split(/\r?\n/);
27
+ const path = lines.find((line) => line.startsWith("worktree "))?.slice("worktree ".length);
28
+ if (!path) continue;
29
+ const usable = !lines.some((line) => line === "bare" || line === "prunable" || line.startsWith("prunable "));
30
+ entries.push({ path, usable });
31
+ }
32
+ const here = normalizePath(cwd);
33
+ const contains = (path: string) => here === normalizePath(path) || here.startsWith(`${normalizePath(path)}/`);
34
+ const current = entries
35
+ .filter((entry) => contains(entry.path))
36
+ .toSorted((a, b) => normalizePath(b.path).length - normalizePath(a.path).length)[0];
37
+ return entries.filter((entry) => entry.usable && entry !== current).map((entry) => entry.path);
38
+ }
39
+
40
+ // --- branches ----------------------------------------------------------------
41
+
42
+ /** `git branch --format=%(refname:short)` lines, without the current branch and detached entries. */
43
+ export function parseBranchList(stdout: string | undefined, current: string | undefined): string[] {
44
+ return (stdout ?? "")
45
+ .split(/\r?\n/)
46
+ .map((line) => line.trim())
47
+ .filter((name) => name && !name.startsWith("(") && name !== current);
48
+ }
49
+
50
+ /** origin/HEAD's branch (`refs/remotes/origin/main` → `main`), else main, else master. */
51
+ export function defaultBranchFrom(symbolicRef: string | undefined, hasMain: boolean, hasMaster: boolean): string | undefined {
52
+ const remote = symbolicRef?.trim().replace(/^refs\/remotes\//, "").replace(/^origin\//, "");
53
+ if (remote) return remote;
54
+ if (hasMain) return "main";
55
+ return hasMaster ? "master" : undefined;
56
+ }
57
+
58
+ // --- ODD feature documents -----------------------------------------------------
59
+
60
+ /*
61
+ * Detection rule for unfinished ODD plans (checked against this repo's
62
+ * odd/tasks/fisi-dock.md and Gentle Shell's own odd/tasks/*.md):
63
+ *
64
+ * - The plan is the `## Tasks…` section (a level-2 heading starting with
65
+ * "Tasks", e.g. "## Tasks" or "## Tasks and routing"), up to the next
66
+ * level-1 or level-2 heading. A file without it is ignored.
67
+ * - A task is a top-level list item (no indentation) that is a checkbox
68
+ * (`- [ ] …`, `- [x] …`) or starts with a task ID (`- T3 …`). Indented
69
+ * sub-steps and other lists (e.g. `- C1 …` commit units) are not tasks.
70
+ * - Checkbox tasks: `[x]` is done, `[ ]` is open, whatever the text says.
71
+ * - Other tasks, first match wins: a done word (done, complete, completed,
72
+ * dropped, cancelled) means done; a pending word (pending, in progress,
73
+ * blocked, reopened) means open, so "Commit: pending" is open; a recorded
74
+ * commit hash ("Commit: 4620955", "commit `bb9b3a258`") means done.
75
+ * Anything else is open.
76
+ * - A section with no task lines at all is ignored too.
77
+ */
78
+
79
+ const TASK_SECTION = /^##\s+tasks\b/i;
80
+ const NEXT_SECTION = /^#{1,2}\s/;
81
+ const CHECKBOX = /^[-*]\s+\[([ xX])\]/;
82
+ const TASK_ID = /^[-*]\s+T\d+[a-z]?\b/;
83
+ const DONE_WORD = /\b(done|complete|completed|dropped|cancell?ed)\b/i;
84
+ const PENDING_WORD = /\b(pending|in[_ ]progress|blocked|reopened)\b/i;
85
+ const COMMIT_HASH = /\bcommits?\b[:\s`(]*[0-9a-f]{7,40}\b/i;
86
+
87
+ /** "done" or "open" for a task line of a `## Tasks` section; undefined when the line is not a task. */
88
+ export function classifyTaskLine(line: string): "done" | "open" | undefined {
89
+ const box = CHECKBOX.exec(line);
90
+ if (box) return box[1] === " " ? "open" : "done";
91
+ if (!TASK_ID.test(line)) return undefined;
92
+ if (DONE_WORD.test(line)) return "done";
93
+ if (PENDING_WORD.test(line)) return "open";
94
+ return COMMIT_HASH.test(line) ? "done" : "open";
95
+ }
96
+
97
+ /** Open tasks of one feature document; undefined when it has no recognizable tasks. */
98
+ export function countOpenTasks(markdown: string): number | undefined {
99
+ let inTasks = false;
100
+ let tasks = 0;
101
+ let open = 0;
102
+ for (const line of markdown.split(/\r?\n/)) {
103
+ if (TASK_SECTION.test(line)) {
104
+ inTasks = true;
105
+ continue;
106
+ }
107
+ if (NEXT_SECTION.test(line)) inTasks = false;
108
+ if (!inTasks) continue;
109
+ const state = classifyTaskLine(line);
110
+ if (!state) continue;
111
+ tasks++;
112
+ if (state === "open") open++;
113
+ }
114
+ return tasks > 0 ? open : undefined;
115
+ }
116
+
117
+ export interface PlanInfo {
118
+ /** Feature document name without `.md`. */
119
+ name: string;
120
+ open: number;
121
+ }
122
+
123
+ /** Read-only file access for the plan scan; the default reads the disk. */
124
+ export interface PlanFiles {
125
+ list(dir: string): Promise<string[]>;
126
+ size(path: string): Promise<number>;
127
+ read(path: string): Promise<string>;
128
+ }
129
+
130
+ const diskFiles: PlanFiles = {
131
+ list: (dir) => readdir(dir),
132
+ size: async (path) => (await stat(path)).size,
133
+ read: (path) => readFile(path, "utf8"),
134
+ };
135
+
136
+ const MAX_PLAN_BYTES = 200 * 1024;
137
+
138
+ /** Plans in `<cwd>/odd/tasks` with open tasks, by name; undefined when there is no such folder. */
139
+ export async function readOddPlans(cwd: string, files: PlanFiles = diskFiles): Promise<PlanInfo[] | undefined> {
140
+ if (!cwd) return undefined;
141
+ const dir = join(cwd, "odd", "tasks");
142
+ let names: string[];
143
+ try {
144
+ names = await files.list(dir);
145
+ } catch {
146
+ return undefined;
147
+ }
148
+ const plans: PlanInfo[] = [];
149
+ for (const name of names.filter((entry) => entry.endsWith(".md")).toSorted()) {
150
+ try {
151
+ const path = join(dir, name);
152
+ if ((await files.size(path)) > MAX_PLAN_BYTES) continue;
153
+ const open = countOpenTasks(await files.read(path));
154
+ if (open) plans.push({ name: name.slice(0, -".md".length), open });
155
+ } catch {
156
+ // An unreadable file is left out.
157
+ }
158
+ }
159
+ return plans;
160
+ }
161
+
162
+ // --- git reader --------------------------------------------------------------
163
+
164
+ async function gitOutput(exec: GitExec, args: string[]): Promise<string | undefined> {
165
+ try {
166
+ const result = await exec(args);
167
+ return result.code === 0 ? result.stdout : undefined;
168
+ } catch {
169
+ return undefined;
170
+ }
171
+ }
172
+
173
+ /** Other worktrees and local branches not merged into the default branch; each omitted when unreadable. */
174
+ export async function readHeadsUpGit(exec: GitExec, cwd: string, branch: string | undefined): Promise<{ worktrees?: string[]; unmerged?: string[] }> {
175
+ const porcelain = await gitOutput(exec, ["worktree", "list", "--porcelain"]);
176
+ // Not a repository (or no git): skip the rest.
177
+ if (porcelain === undefined) return { worktrees: undefined, unmerged: undefined };
178
+ const worktrees = otherWorktrees(porcelain, cwd);
179
+ const exists = async (ref: string) => (await gitOutput(exec, ["rev-parse", "--verify", "--quiet", ref])) !== undefined;
180
+ const symbolicRef = await gitOutput(exec, ["symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"]);
181
+ let target = defaultBranchFrom(symbolicRef, false, false);
182
+ if (target === undefined) {
183
+ const hasMain = await exists("refs/heads/main");
184
+ target = defaultBranchFrom(undefined, hasMain, !hasMain && (await exists("refs/heads/master")));
185
+ }
186
+ const list = target === undefined ? undefined : await gitOutput(exec, ["branch", "--format=%(refname:short)", "--no-merged", target]);
187
+ return { worktrees, unmerged: list === undefined ? undefined : parseBranchList(list, branch) };
188
+ }
189
+
190
+ // --- warnings ----------------------------------------------------------------
191
+
192
+ export interface HeadsUpInput {
193
+ worktrees?: string[];
194
+ /** Open todo tasks once the run settled; 0 while a run is going. */
195
+ todoLeft?: number;
196
+ ahead?: number;
197
+ unmerged?: string[];
198
+ plans?: PlanInfo[];
199
+ }
200
+
201
+ const folderName = (path: string) => path.split(/[\\/]+/).filter(Boolean).at(-1) ?? path;
202
+ const plural = (count: number, one: string, many: string) => `${count} ${count === 1 ? one : many}`;
203
+
204
+ /**
205
+ * The heads-up rows, counts first. Plans come last: there can be many, and the
206
+ * renderer collapses whatever passes its cap, so the unpushed warning (which
207
+ * replaces the session row's ↑N, S8) always stays visible.
208
+ */
209
+ export function headsUpWarnings(input: HeadsUpInput): HeadsUpWarning[] {
210
+ const warnings: HeadsUpWarning[] = [];
211
+ const worktrees = input.worktrees ?? [];
212
+ if (worktrees.length === 1) warnings.push({ kind: "worktrees", text: `worktree open: ${folderName(worktrees[0])}` });
213
+ else if (worktrees.length > 1) warnings.push({ kind: "worktrees", text: `${worktrees.length} worktrees open` });
214
+ if (input.todoLeft && input.todoLeft > 0) warnings.push({ kind: "todo", text: `${plural(input.todoLeft, "todo task", "todo tasks")} left` });
215
+ if (input.ahead && input.ahead > 0) warnings.push({ kind: "unpushed", text: `${plural(input.ahead, "commit", "commits")} not pushed` });
216
+ const unmerged = input.unmerged ?? [];
217
+ if (unmerged.length === 1) warnings.push({ kind: "branches", text: `branch not merged: ${unmerged[0]}` });
218
+ else if (unmerged.length > 1) warnings.push({ kind: "branches", text: `${unmerged.length} branches not merged` });
219
+ for (const plan of input.plans ?? []) {
220
+ if (plan.open > 0) warnings.push({ kind: "plan", text: `ODD plan ${plan.name}: ${plan.open} open` });
221
+ }
222
+ return warnings;
223
+ }