@mrciphersmith/roomyx 0.6.2 → 0.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,152 @@
1
+ import { BoxRenderable, TextRenderable } from "@opentui/core";
2
+ import type { RenderContext } from "@opentui/core";
3
+ import type { RoomHistoryRow } from "../../installer/history";
4
+ import { clip } from "../clip";
5
+
6
+ /**
7
+ * The picker for closed rooms: one row per room, newest first, Enter opens the
8
+ * selected one read-only.
9
+ *
10
+ * It lists an *index*, not a folder of archived copies — the log each row points
11
+ * at is the original, wherever the operator put it. That is why a row can say
12
+ * the log is gone: this screen knows a room existed and where its transcript was
13
+ * without owning the transcript. Saying so is the whole reason the distinction
14
+ * is worth having; a shadow copy would have shown text that no longer matches
15
+ * the file the operator thinks they are reading.
16
+ */
17
+
18
+ const WHEN_WIDTH = 16;
19
+ const DATE_WIDTH = 10;
20
+
21
+ /**
22
+ * Terminal width at or above which a row has room for the time of day as well
23
+ * as the date. Below it those six columns are worth more to the goal statement,
24
+ * which at 60 columns was down to about eighteen characters — the same
25
+ * reasoning, and the same kind of breakpoint, as the roster's.
26
+ */
27
+ const TIME_OF_DAY_BREAKPOINT = 80;
28
+
29
+ /** `2026-09-09 18:04`, or just `2026-09-09` on a narrow pane. */
30
+ function when(iso: string, width: number): string {
31
+ const target = width >= TIME_OF_DAY_BREAKPOINT ? WHEN_WIDTH : DATE_WIDTH;
32
+ return iso.slice(0, target).replace("T", " ").padEnd(target);
33
+ }
34
+
35
+ const COUNTS_WIDTH = 20;
36
+
37
+ /**
38
+ * Exactly `width` columns, whichever way the content misses.
39
+ *
40
+ * `padEnd` alone only fixes the short case, and the long case is the one that
41
+ * happens: `99999 msg 3 here` is 17 columns against a 16-column pad, so a room
42
+ * with five-digit traffic pushed the goal column right and every row below it
43
+ * stopped lining up. Found by sweeping counts rather than by reading — the
44
+ * fixture had two digits.
45
+ */
46
+ function fixed(text: string, width: number): string {
47
+ return text.length > width ? clip(text, width) : text.padEnd(width);
48
+ }
49
+
50
+ /**
51
+ * One row's text. Exported and pure so the column arithmetic can be tested at a
52
+ * dozen widths without a renderer — the defects this client shipped in list rows
53
+ * were all width-dependent and all invisible to a test that renders one width.
54
+ */
55
+ export function archiveRow(room: RoomHistoryRow, width: number, selected: boolean): string {
56
+ const marker = selected ? "> " : " ";
57
+ const counts = fixed(`${room.messages} msg ${room.participants} here`, COUNTS_WIDTH);
58
+ // A two-column sigil at the very front, not a phrase further along the row.
59
+ //
60
+ // This is the one fact that decides whether Enter will do anything, and both
61
+ // wordier placements lose it exactly when it matters: trailing the row, a
62
+ // 60-column pane ate it; moved ahead of the goal, a 40-column pane ate it
63
+ // too, because the date and counts ahead of it already spend 34 columns. Put
64
+ // at the front it cannot be truncated by anything that leaves the row visible
65
+ // at all. The list's hint line carries the legend, and only when some row
66
+ // actually needs it.
67
+ const gone = room.logExists ? " " : "! ";
68
+ const goal = room.goal === "" ? "(goal unavailable)" : room.goal;
69
+ // Clipped as a whole line, not by giving the goal the leftover budget after a
70
+ // fixed-width head. The head alone is 36 columns, so budgeting that way went
71
+ // negative below a 37-column pane and returned a row wider than the box that
72
+ // holds it — which is how the roster came to draw a name into the message
73
+ // stream. One column kept clear on the right so a full-width goal cannot abut
74
+ // the frame with no separating gap.
75
+ return clip(`${marker}${gone}${when(room.closedAt, width)} ${counts}${goal}`, Math.max(0, width - 1));
76
+ }
77
+
78
+ export class ArchiveList {
79
+ readonly node: BoxRenderable;
80
+ private readonly rows: TextRenderable[];
81
+ private selectedIndex = 0;
82
+
83
+ constructor(
84
+ ctx: RenderContext,
85
+ private readonly rooms: RoomHistoryRow[],
86
+ private readonly options: { width: number; height: number; unreadable: number },
87
+ ) {
88
+ this.node = new BoxRenderable(ctx, {
89
+ width: options.width,
90
+ height: options.height,
91
+ flexDirection: "column",
92
+ border: true,
93
+ title: ` closed rooms (${rooms.length}) `,
94
+ });
95
+
96
+ if (rooms.length === 0) {
97
+ this.rows = [];
98
+ this.node.add(
99
+ new TextRenderable(ctx, {
100
+ content:
101
+ " No closed rooms recorded yet.\n\n" +
102
+ " A room is recorded here when `roomyx serve` shuts down, and\n" +
103
+ " when a crashed room is noticed missing by `roomyx rooms list`.",
104
+ wrapMode: "word",
105
+ }),
106
+ );
107
+ } else {
108
+ this.rows = rooms.map((room, index) => {
109
+ const row = new TextRenderable(ctx, {
110
+ content: archiveRow(room, options.width - 2, index === this.selectedIndex),
111
+ height: 1,
112
+ // Explicit rather than relying on `height: 1` to hide a wrap. That
113
+ // reliance is what turned an overflow into a vanished row in the
114
+ // roster; see ../clip.
115
+ wrapMode: "none",
116
+ });
117
+ this.node.add(row);
118
+ return row;
119
+ });
120
+ }
121
+
122
+ const hints = ["", " ↑/↓ or j/k move · Enter opens read-only · q quits"];
123
+ // Only when a row actually carries it. A legend for a symbol nothing on
124
+ // screen is using is a line of noise on every other visit.
125
+ if (rooms.some((room) => !room.logExists)) {
126
+ hints.push(" ! the log is no longer at the path the room recorded");
127
+ }
128
+ if (options.unreadable > 0) {
129
+ hints.push(` ${options.unreadable} history line(s) unreadable and skipped`);
130
+ }
131
+ this.node.add(new TextRenderable(ctx, { content: hints.join("\n"), wrapMode: "word" }));
132
+ }
133
+
134
+ moveSelection(delta: 1 | -1): void {
135
+ if (this.rooms.length === 0) return;
136
+ this.selectedIndex = (this.selectedIndex + delta + this.rooms.length) % this.rooms.length;
137
+ this.rows.forEach((row, index) => {
138
+ const room = this.rooms[index];
139
+ if (room) row.content = archiveRow(room, this.options.width - 2, index === this.selectedIndex);
140
+ });
141
+ }
142
+
143
+ /** The highlighted room, or null when there are none. */
144
+ selected(): RoomHistoryRow | null {
145
+ return this.rooms[this.selectedIndex] ?? null;
146
+ }
147
+
148
+ /** `remove()` unlinks without freeing, and the native renderable pool is finite. */
149
+ destroy(): void {
150
+ this.node.destroyRecursively();
151
+ }
152
+ }
@@ -7,8 +7,9 @@ import { Footer } from "../components/footer";
7
7
  import { HelpOverlay } from "../components/help-overlay";
8
8
  import { createMessageRow } from "../components/message-row";
9
9
  import { Transcript } from "../transcript";
10
+ import type { Action } from "../keymap";
10
11
  import type { Entry } from "../transcript";
11
- import type { ConnectionStatus } from "../mcp-client";
12
+ import type { DisplayStatus } from "../components/status-bar";
12
13
 
13
14
  /**
14
15
  * Terminal width at or above which the roster gets its 24 columns. Below it,
@@ -39,7 +40,16 @@ export class ChatView {
39
40
  private rows: Renderable[] = [];
40
41
  private readonly rosterVisible: boolean;
41
42
 
42
- constructor(ctx: RenderContext, options: { width: number; height: number; onSelectAgent?: (agent: RosterEntry) => void }) {
43
+ constructor(
44
+ ctx: RenderContext,
45
+ options: {
46
+ width: number;
47
+ height: number;
48
+ onSelectAgent?: (agent: RosterEntry) => void;
49
+ /** Keys the footer must not advertise on this surface, e.g. the owner command in a closed room. */
50
+ hideBindings?: readonly Action[];
51
+ },
52
+ ) {
43
53
  this.ctx = ctx;
44
54
  this.node = new BoxRenderable(ctx, { width: options.width, height: options.height, flexDirection: "column" });
45
55
  this.statusBar = new StatusBar(ctx);
@@ -80,14 +90,14 @@ export class ChatView {
80
90
  });
81
91
  body.add(this.scroll);
82
92
 
83
- this.footer = new Footer(ctx, { width: options.width });
93
+ this.footer = new Footer(ctx, { width: options.width, hideBindings: options.hideBindings });
84
94
  this.node.add(this.footer.node);
85
95
 
86
96
  this.help = new HelpOverlay(ctx, { width: options.width, height: options.height });
87
97
  this.node.add(this.help.node);
88
98
  }
89
99
 
90
- setConnectionStatus(status: ConnectionStatus): void {
100
+ setConnectionStatus(status: DisplayStatus): void {
91
101
  this.statusBar.setConnectionStatus(status);
92
102
  }
93
103
 
@@ -0,0 +1,231 @@
1
+ import { existsSync, writeFileSync } from "node:fs";
2
+ import type { CliRenderer, ParsedKey } from "@opentui/core";
3
+ import { ChatView } from "./screens/chat-view";
4
+ import type { RosterEntry } from "../log/types";
5
+ import { resolveAction } from "./keymap";
6
+ import type { Action } from "./keymap";
7
+ import { exportBaseName, nextFreeExportPath } from "./export-name";
8
+ import { CLOSED, opened, searchPromptLine, stepSearchPrompt } from "./search-prompt";
9
+ import type { SearchPromptState } from "./search-prompt";
10
+
11
+ /**
12
+ * Everything the reader does that does not depend on the room being live:
13
+ * scrolling, filtering by participant, searching, exporting, help, quitting.
14
+ *
15
+ * Extracted when the archive viewer arrived, because the alternative was two
16
+ * copies of a 90-line keypress handler that would drift — and the specific way
17
+ * it would drift is that a fix found while reading a live room would not reach
18
+ * the screen people reread closed rooms on, which is the screen a fix is most
19
+ * likely to be *found* on. The live client keeps only what is genuinely about
20
+ * being connected: the poll loop, the owner prompt, the liveness line.
21
+ *
22
+ * The two things that differ are injected rather than branched on: `status`
23
+ * supplies the tail of the footer, and `onOwnerPrompt` is what `o` does — a
24
+ * closed room has nobody to send a command to, so it says so instead.
25
+ */
26
+
27
+ export interface ViewerOptions {
28
+ renderer: CliRenderer;
29
+ /** Called for `q` and Ctrl-C. */
30
+ quit: () => void;
31
+ /** The right-hand end of the footer. Recomputed on every refresh. */
32
+ status: () => string;
33
+ /** What `o` does. Defaults to a notice explaining why it does nothing. */
34
+ onOwnerPrompt?: () => void;
35
+ /**
36
+ * First refusal on every key. The owner prompt owns the keyboard while it is
37
+ * open — otherwise typing "q" into a veto would quit the client. Returns true
38
+ * when it has consumed the key.
39
+ */
40
+ beforeKey?: (event: ParsedKey) => boolean;
41
+ }
42
+
43
+ export class Viewer {
44
+ readonly chatView: ChatView;
45
+ private filtered: RosterEntry | null = null;
46
+ private matchCursor = -1;
47
+ private participants = 0;
48
+ private search: SearchPromptState = CLOSED;
49
+ private readonly options: ViewerOptions;
50
+
51
+ constructor(options: ViewerOptions) {
52
+ this.options = options;
53
+ const { renderer } = options;
54
+
55
+ // Selecting a participant filters the stream in place instead of opening a
56
+ // window over it. The modal this replaces could not be scrolled, did not
57
+ // compose with search, cost a keypress to leave, and was pinned at
58
+ // hardcoded coordinates across the roster it had been opened from.
59
+ this.chatView = new ChatView(renderer, {
60
+ width: renderer.terminalWidth,
61
+ height: renderer.terminalHeight,
62
+ onSelectAgent: (agent: RosterEntry) => this.applyFilter(agent),
63
+ // A closed room has nobody to send a command to, so the footer must not
64
+ // print the key for one. The help overlay still lists it and says why.
65
+ hideBindings: options.onOwnerPrompt ? [] : (["owner.prompt"] as const),
66
+ });
67
+ renderer.root.add(this.chatView.node);
68
+ }
69
+
70
+ /** How many people the footer should say are here. */
71
+ setParticipants(count: number): void {
72
+ this.participants = count;
73
+ }
74
+
75
+ applyFilter(agent: RosterEntry | null): void {
76
+ this.filtered = agent;
77
+ this.chatView.setFilter(agent?.id ?? null);
78
+ this.matchCursor = -1;
79
+ this.chatView.scrollToBottom();
80
+ this.refreshFooter();
81
+ }
82
+
83
+ refreshFooter(): void {
84
+ // On a terminal too narrow for the roster, the footer is the only place
85
+ // that still says how many people are in the room.
86
+ const here = this.chatView.isRosterVisible() || this.participants === 0 ? "" : `${this.participants} here · `;
87
+ // A filter or a search that is on but invisible is the worst of both: the
88
+ // pane looks like a quiet room. `less` prints a single `&` for the same
89
+ // reason, and k9s puts the live filter in the view title.
90
+ const filterNote = this.filtered === null ? "" : `filter: ${this.filtered.name} · `;
91
+ const query = this.chatView.transcript.currentQuery();
92
+ const total = this.chatView.transcript.matches().length;
93
+ // `matchCursor` is -1 until a match has been jumped to, and `applyFilter`
94
+ // resets it — so this printed "0/2", a match number that does not exist.
95
+ // Before a position is known, say how many there are.
96
+ const position = this.matchCursor >= 0 ? `${this.matchCursor + 1}/${total}` : `${total} matches`;
97
+ const searchNote = query === "" ? "" : `/${query} ${total === 0 ? "no matches" : position} · `;
98
+ this.chatView.footer.setLiveness(`${filterNote}${searchNote}${here}${this.options.status()}`);
99
+ // Only say something when the reader is *not* where new messages land —
100
+ // a permanent "at bottom" would be another word that always says the same
101
+ // thing, which is the habit this footer exists to break.
102
+ this.chatView.footer.setScrollNote(this.chatView.isAtBottom() ? null : "scrolled up · G to follow");
103
+ }
104
+
105
+ handleKey(event: ParsedKey): void {
106
+ // The help overlay swallows the keyboard, so a key pressed at a screen
107
+ // explaining the keys does not also fire the thing it explains.
108
+ if (this.chatView.help.isVisible()) {
109
+ if (event.name === "escape" || event.sequence === "?") this.chatView.help.hide();
110
+ return;
111
+ }
112
+
113
+ if (this.options.beforeKey?.(event) === true) return;
114
+
115
+ if (this.search.open) {
116
+ const stepped = stepSearchPrompt(this.search, event);
117
+ this.search = stepped.state;
118
+ this.chatView.statusBar.setNotice(searchPromptLine(this.search));
119
+ if (stepped.action.type === "search") {
120
+ this.chatView.setQuery(stepped.action.query);
121
+ this.chatView.statusBar.setNotice(null);
122
+ if (stepped.action.query !== "") this.jumpTo(this.chatView.transcript.nextMatch(-1));
123
+ else this.refreshFooter();
124
+ } else if (stepped.action.type === "cancel") {
125
+ this.chatView.statusBar.setNotice(null);
126
+ }
127
+ return;
128
+ }
129
+
130
+ // Any other key clears a leftover result line and falls through.
131
+ this.chatView.statusBar.setNotice(null);
132
+
133
+ const action = resolveAction(event);
134
+ if (action === null) return;
135
+
136
+ // One row per action rather than a chain of conditions, so the set of
137
+ // things a key can do is a list you can read, and adding one cannot
138
+ // accidentally shadow an earlier branch.
139
+ const chat = this.chatView;
140
+ const half = Math.max(1, Math.floor(chat.pageSize() / 2));
141
+ const handlers: Record<Action, () => void> = {
142
+ "scroll.lineUp": () => chat.scrollByLines(-1),
143
+ "scroll.lineDown": () => chat.scrollByLines(1),
144
+ "scroll.pageUp": () => chat.scrollByLines(-chat.pageSize()),
145
+ "scroll.pageDown": () => chat.scrollByLines(chat.pageSize()),
146
+ "scroll.halfUp": () => chat.scrollByLines(-half),
147
+ "scroll.halfDown": () => chat.scrollByLines(half),
148
+ "scroll.top": () => chat.scrollToTop(),
149
+ "scroll.bottom": () => chat.scrollToBottom(),
150
+ "roster.prev": () => chat.roster.moveSelection(-1),
151
+ "roster.next": () => chat.roster.moveSelection(1),
152
+ "roster.open": () => chat.roster.confirmSelection(),
153
+ "filter.clear": () => this.applyFilter(null),
154
+ "search.open": () => {
155
+ this.search = opened();
156
+ chat.statusBar.setNotice(searchPromptLine(this.search));
157
+ },
158
+ "search.next": () => this.jumpTo(chat.transcript.nextMatch(this.currentEntryIndex())),
159
+ "search.previous": () => this.jumpTo(chat.transcript.previousMatch(this.currentEntryIndex())),
160
+ "owner.prompt": () =>
161
+ this.options.onOwnerPrompt
162
+ ? this.options.onOwnerPrompt()
163
+ : chat.statusBar.setNotice("this room is closed — nothing to send a command to"),
164
+ "transcript.export": () => this.exportTranscript(),
165
+ "help.toggle": () => chat.help.toggle(),
166
+ "app.quit": () => this.options.quit(),
167
+ };
168
+ handlers[action]();
169
+ this.refreshFooter();
170
+ }
171
+
172
+ private jumpTo(index: number | null): void {
173
+ if (index === null) {
174
+ this.chatView.statusBar.setNotice(`no match for "${this.chatView.transcript.currentQuery()}"`);
175
+ this.matchCursor = -1;
176
+ } else {
177
+ this.matchCursor = this.chatView.transcript.matches().indexOf(index);
178
+ this.chatView.scrollToEntry(index);
179
+ this.chatView.statusBar.setNotice(null);
180
+ }
181
+ this.refreshFooter();
182
+ }
183
+
184
+ /**
185
+ * Where `n` and `N` start counting from: the match cursor if a search is
186
+ * already underway, otherwise the end of the transcript, so the first `n`
187
+ * after a fresh `/` wraps to the earliest match rather than jumping from
188
+ * wherever the last search happened to leave off.
189
+ */
190
+ private currentEntryIndex(): number {
191
+ return this.chatView.transcript.matches()[this.matchCursor] ?? -1;
192
+ }
193
+
194
+ /**
195
+ * Writes what is on screen to a file and names the path.
196
+ *
197
+ * Claude Code's transcript viewer dumps into the terminal's own scrollback so
198
+ * tmux copy-mode and the terminal's find can reach it. roomyx cannot leave
199
+ * the alternate screen safely while the room is still streaming into it, so
200
+ * it writes a file instead — same purpose, which is to get the text somewhere
201
+ * the reader's existing tools already work.
202
+ *
203
+ * It never overwrites: `wx` fails if the path exists and the loop takes the
204
+ * next free suffix. Silently replacing an export someone took a minute ago is
205
+ * exactly the kind of small theft a keystroke should not be able to commit.
206
+ */
207
+ private exportTranscript(): void {
208
+ const base = exportBaseName(this.filtered?.id ?? null);
209
+ const target = nextFreeExportPath(process.cwd(), base, existsSync);
210
+ if (!target.ok) {
211
+ this.chatView.statusBar.setNotice(
212
+ target.reason === "exhausted"
213
+ ? `${base}.txt and 99 numbered siblings all exist — nothing written`
214
+ : "refusing to write outside the working directory",
215
+ );
216
+ return;
217
+ }
218
+ try {
219
+ // `wx` creates or fails; it never truncates.
220
+ writeFileSync(target.path, `${this.chatView.transcript.toText()}\n`, { encoding: "utf8", flag: "wx" });
221
+ // The name, not the absolute path: the status bar is one line and
222
+ // truncates, and an absolute path under a deep working directory gets cut
223
+ // exactly where the filename would have been.
224
+ this.chatView.statusBar.setNotice(`written to ./${target.name}`);
225
+ } catch (error) {
226
+ this.chatView.statusBar.setNotice(
227
+ `could not write ./${target.name} — ${error instanceof Error ? error.message : String(error)}`,
228
+ );
229
+ }
230
+ }
231
+ }
@@ -0,0 +1,154 @@
1
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { z } from "zod";
4
+ import { loadRoomLog } from "../log/store";
5
+
6
+ /**
7
+ * The record of rooms that have closed.
8
+ *
9
+ * **It is an index, not an archive of copies.** The obvious shape for "save
10
+ * closed rooms" is a folder under `.roomyx/` that the log gets copied into when
11
+ * the room ends. That is the wrong shape here for one specific reason: the room
12
+ * log is append-only and is the single source of truth for what was said
13
+ * (D-01a). Copying it makes a second one. The moment a copy exists, an append
14
+ * to the original — which `roomyx room append --force` still permits, and which
15
+ * a dispatcher does routinely if the room is reopened — leaves two files that
16
+ * disagree, with nothing recording which is current. A reader would have no way
17
+ * to tell, and the wrong answer is silent.
18
+ *
19
+ * So what gets written here is *what the room was*: its id, where its log lives,
20
+ * its goal, how many people and messages it had, when it started and closed.
21
+ * The transcript itself stays exactly where the operator put it, still the only
22
+ * copy. If they move or delete it, the entry says so rather than quietly
23
+ * serving stale text from a shadow copy.
24
+ *
25
+ * Append-only JSONL, like the room log and for the same reason: a closing room
26
+ * appends one line under no lock, and a concurrent reader sees whole lines.
27
+ */
28
+
29
+ const historyEntrySchema = z.object({
30
+ type: z.literal("room"),
31
+ id: z.string().min(1),
32
+ logPath: z.string().min(1),
33
+ goal: z.string(),
34
+ participants: z.number().int().min(0),
35
+ messages: z.number().int().min(0),
36
+ startedAt: z.string().min(1),
37
+ closedAt: z.string().min(1),
38
+ });
39
+
40
+ export type RoomHistoryEntry = z.infer<typeof historyEntrySchema>;
41
+
42
+ /** A history entry plus whether the transcript it points at is still there. */
43
+ export interface RoomHistoryRow extends RoomHistoryEntry {
44
+ logExists: boolean;
45
+ }
46
+
47
+ /** Sits next to the registry, because the two describe the same rooms at different times. */
48
+ export function defaultHistoryPath(registryPath: string): string {
49
+ return join(dirname(registryPath), "history.jsonl");
50
+ }
51
+
52
+ /**
53
+ * What a closed room's log says about itself. Never throws: this runs inside a
54
+ * shutdown handler, and a room that cannot be summarised is still a room worth
55
+ * recording. A log that has been deleted, or that has a malformed line, yields
56
+ * an entry with an empty goal and zero counts rather than an exception that
57
+ * takes the deregistration with it.
58
+ */
59
+ function summarize(logPath: string): { goal: string; participants: number; messages: number } {
60
+ try {
61
+ const { state, messages } = loadRoomLog(logPath);
62
+ return {
63
+ goal: state.goal_contract.goal_statement,
64
+ participants: state.roster.length,
65
+ messages: messages.length,
66
+ };
67
+ } catch {
68
+ return { goal: "", participants: 0, messages: 0 };
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Records that a room has ended. Called from the shutdown path and from the
74
+ * registry's prune, so a room that crashed without deregistering is still
75
+ * remembered — the prune is the only moment anything notices it is gone.
76
+ *
77
+ * Both paths can fire for the same id (a slow shutdown pruned by a concurrent
78
+ * `rooms list`), so `readHistory` deduplicates rather than this refusing to
79
+ * append. Appending twice is cheap; taking a lock on a shutdown path to prevent
80
+ * it is not.
81
+ *
82
+ * Swallows its own errors for the same reason `summarize` does. Failing to
83
+ * write a convenience index must not be able to abort a shutdown that still has
84
+ * a port to release and a registry entry to remove.
85
+ */
86
+ export function archiveRoom(
87
+ historyPath: string,
88
+ room: { id: string; logPath: string; startedAt: string },
89
+ closedAt: string = new Date().toISOString(),
90
+ ): void {
91
+ try {
92
+ mkdirSync(dirname(historyPath), { recursive: true });
93
+ const entry: RoomHistoryEntry = {
94
+ type: "room",
95
+ id: room.id,
96
+ logPath: room.logPath,
97
+ startedAt: room.startedAt,
98
+ closedAt,
99
+ ...summarize(room.logPath),
100
+ };
101
+ appendFileSync(historyPath, `${JSON.stringify(entry)}\n`, "utf8");
102
+ } catch {
103
+ // Deliberately silent. See above.
104
+ }
105
+ }
106
+
107
+ export interface History {
108
+ rooms: RoomHistoryRow[];
109
+ /** Lines that did not parse. Reported rather than thrown — see below. */
110
+ unreadable: number;
111
+ }
112
+
113
+ /**
114
+ * Every closed room, newest first, with duplicates collapsed.
115
+ *
116
+ * **A malformed line is skipped, not raised.** This is the opposite of what
117
+ * `loadRoomLog` does with the room log, and the difference is deliberate: the
118
+ * room log is the transcript, where a line that will not parse means the record
119
+ * is damaged and reading past it would silently drop something someone said.
120
+ * This file is an index that can be rebuilt from nothing, and one bad line here
121
+ * must not be able to hide fifty good rooms. The count is returned so the
122
+ * surfaces can say the file has damage rather than pretending it is clean.
123
+ */
124
+ export function readHistory(historyPath: string, exists: (path: string) => boolean = existsSync): History {
125
+ if (!existsSync(historyPath)) return { rooms: [], unreadable: 0 };
126
+
127
+ const byId = new Map<string, RoomHistoryEntry>();
128
+ let unreadable = 0;
129
+
130
+ for (const line of readFileSync(historyPath, "utf8").replace(/^/, "").split("\n")) {
131
+ if (line.trim() === "") continue;
132
+ let parsed: unknown;
133
+ try {
134
+ parsed = JSON.parse(line);
135
+ } catch {
136
+ unreadable += 1;
137
+ continue;
138
+ }
139
+ const entry = historyEntrySchema.safeParse(parsed);
140
+ if (!entry.success) {
141
+ unreadable += 1;
142
+ continue;
143
+ }
144
+ // Last write wins: the prune path and the shutdown path can both record the
145
+ // same room, and the later one saw more of it.
146
+ byId.set(entry.data.id, entry.data);
147
+ }
148
+
149
+ const rooms = [...byId.values()]
150
+ .sort((a, b) => b.closedAt.localeCompare(a.closedAt))
151
+ .map((room) => ({ ...room, logExists: exists(room.logPath) }));
152
+
153
+ return { rooms, unreadable };
154
+ }
@@ -4,6 +4,7 @@ import { z } from "zod";
4
4
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
5
5
  import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
6
6
  import { withLock } from "../lockfile";
7
+ import { archiveRoom, defaultHistoryPath } from "./history";
7
8
 
8
9
  /** Re-exported: the registry's own tests reach for it, and it lives in ../lockfile now. */
9
10
  export { releaseLockIfOwned } from "../lockfile";
@@ -115,9 +116,10 @@ export function listRooms(registryPath: string): RoomRegistryEntry[] {
115
116
  */
116
117
  export async function listLiveRooms(
117
118
  registryPath: string,
118
- options: { prune?: boolean } = {},
119
+ options: { prune?: boolean; historyPath?: string } = {},
119
120
  ): Promise<RoomRegistryEntry[]> {
120
121
  const prune = options.prune ?? true;
122
+ const historyPath = options.historyPath ?? defaultHistoryPath(registryPath);
121
123
  if (hasNoRegistry(registryPath)) return [];
122
124
  const rooms = withLock(registryPath, () => readRegistryUnlocked(registryPath).rooms);
123
125
  const checks = await Promise.all(
@@ -138,14 +140,24 @@ export async function listLiveRooms(
138
140
  // flight. Re-read under the lock and only remove entries this pass
139
141
  // actually confirmed dead, instead of blindly overwriting with the
140
142
  // stale `live` list computed before the re-read.
143
+ const dead = checks.filter((c) => !c.alive).map((c) => c.room);
141
144
  withLock(registryPath, () => {
142
145
  const current = readRegistryUnlocked(registryPath).rooms;
143
- const deadIds = new Set(checks.filter((c) => !c.alive).map((c) => c.room.id));
146
+ const deadIds = new Set(dead.map((r) => r.id));
144
147
  writeRegistryUnlocked(
145
148
  registryPath,
146
149
  current.filter((r) => !deadIds.has(r.id)),
147
150
  );
148
151
  });
152
+ // A room pruned here died without deregistering — crashed, or was killed
153
+ // with a signal no handler runs for. This is the only moment anything
154
+ // observes that it ended, so it is the only place its history entry can be
155
+ // written. Without it the rooms that are most worth being able to reread
156
+ // are exactly the ones that leave no trace.
157
+ //
158
+ // `closedAt` is now, not the moment it actually died, which is unknowable
159
+ // — the entry records when it was found gone.
160
+ for (const room of dead) archiveRoom(historyPath, room);
149
161
  }
150
162
  return live;
151
163
  }