repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

feat(bak): search remote sessions by name or path

e1f54f8297bf7391d6c7a0035b8766e0885e5b6c

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (5)

extensions/bak/README.md

Modified
39 39 /bak backup
40 40 /bak restore <alias>/<session-id-prefix> [path]
41 41 /bak restore all [path]
42 +/bak search <name or path>
42 43 /bak refresh
43 44 /bak status
46 47 `/bak backup` uploads all locally discoverable sessions.
47 48 Completed agent runs back up their current session asynchronously.
48 49 Restore defaults to the current configured session directory and never silently overwrites differing files.
50 +Run `/bak search <name or path>` on the receiving host to find remote sessions by case-insensitive name or working-directory substring, then restore using a displayed `<alias>/<id-prefix>`.
51 +Search reads only catalog metadata: it uses the local cache when available, refreshes once if absent, and displays at most 10 newest matches.
52 +Use `/bak refresh` to update an existing cache before searching.
50 54 ## Tests

extensions/bak/__e2e__/commands.test.ts

Modified
199 199 expect(ids.sort()).toEqual([first.id, second.id].sort());
202 + it("searches remote names from the cached catalog", async () => {
203 + const alias = aliases.at(-1) as string;
204 + notes = [];
205 + await run("refresh");
206 + await run("search COMMAND SESSION");
207 + expect(lastNote().message).toContain(`${alias}/`);
208 + expect(lastNote().message).toContain("command session");
209 + });
202 211 it("refreshes the catalog and restores by alias prefix", async () => {
203 212 const alias = aliases.at(-1) as string;
204 213 notes = [];

extensions/bak/__tests__/search.test.ts

Added
new file mode 100644
1 +import { describe, expect, it } from "vitest";
2 +import { searchRecords } from "../implementation.js";
3 +import type { CatalogCache, SessionRecord } from "../state.js";
5 +const hostId = "12345678-1234-1234-1234-123456789abc";
6 +const id = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
8 +function record(
9 + id: string,
10 + name: string | undefined,
11 + created: string,
12 +): SessionRecord {
13 + return {
14 + id,
15 + key: `sessions/${hostId}/${id}.jsonl`,
16 + ...(name ? { name } : {}),
17 + cwd: "/projects/pi-ext",
18 + created,
19 + };
22 +function cache(sessions: SessionRecord[]): CatalogCache {
23 + return {
24 + refreshedAt: "2026-01-01T00:00:00.000Z",
25 + catalog: { version: 1, hosts: [{ hostId, alias: "laptop" }] },
26 + indexes: [{ version: 1, hostId, alias: "laptop", sessions }],
27 + };
30 +describe("bak catalog search", () => {
31 + it("matches names and paths without reading sessions, newest first", () => {
32 + const older = record(id, "Design Notes", "2025-01-01T00:00:00.000Z");
33 + const newer = record(
34 + "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb",
35 + undefined,
36 + "2026-01-01T00:00:00.000Z",
37 + );
38 + const catalog = cache([older, newer]);
39 + expect(
40 + searchRecords(catalog, "DESIGN").map(({ record }) => record.id),
41 + ).toEqual([id]);
42 + expect(
43 + searchRecords(catalog, "PI-EXT").map(({ record }) => record.id),
44 + ).toEqual([newer.id, older.id]);
45 + expect(searchRecords(catalog, " ")).toEqual([]);
46 + });
48 + it("limits output and uses unambiguous restore prefixes", () => {
49 + const records = Array.from({ length: 12 }, (_, index) =>
50 + record(
51 + `aaaaaaaa-aaaa-aaaa-aaaa-${index.toString().padStart(12, "0")}`,
52 + "common",
53 + new Date(Date.UTC(2025, 0, index + 1)).toISOString(),
54 + ),
55 + );
56 + const matches = searchRecords(cache(records), "common");
57 + expect(matches).toHaveLength(10);
58 + expect(matches[0]?.record.id).toBe(records[11]?.id);
59 + expect(
60 + matches.every(({ prefix, record }) => record.id.startsWith(prefix)),
61 + ).toBe(true);
62 + expect(new Set(matches.map(({ prefix }) => prefix)).size).toBe(10);
63 + expect(matches.every(({ prefix }) => prefix.length > 8)).toBe(true);
64 + });
65 +});

extensions/bak/implementation.ts

Modified
19 19 const ICON = "󰁯";
20 20 const STATUS_KEY = "bak";
21 21 const SHUTDOWN_DRAIN_MS = 2_000;
22 -const SUBCOMMANDS = ["init", "backup", "restore", "refresh", "status"];
22 +const SUBCOMMANDS = [
23 + "init",
24 + "backup",
25 + "restore",
26 + "search",
27 + "refresh",
28 + "status",
29 +];
30 +const SEARCH_LIMIT = 10;
24 32 type ArchiveModule = typeof import("./archive.js");
80 88 .filter((record) => record.id.startsWith(prefix));
91 +export function searchRecords(
92 + cache: CatalogCache,
93 + query: string,
94 +): { alias: string; record: SessionRecord; prefix: string }[] {
95 + const needle = query.trim().toLowerCase();
96 + if (!needle) return [];
97 + const matches: { alias: string; record: SessionRecord; ids: string[] }[] = [];
98 + for (const index of cache.indexes) {
99 + const ids = index.sessions.map((record) => record.id);
100 + for (const record of index.sessions) {
101 + if (
102 + !record.name?.toLowerCase().includes(needle) &&
103 + !record.cwd.toLowerCase().includes(needle)
105 + continue;
106 + matches.push({ alias: index.alias, record, ids });
109 + matches.sort((a, b) => b.record.created.localeCompare(a.record.created));
110 + return matches.slice(0, SEARCH_LIMIT).map(({ alias, record, ids }) => ({
111 + alias,
112 + record,
113 + prefix: uniquePrefix(record.id, ids),
114 + }));
83 117 function uniquePrefix(id: string, ids: string[]): string {
84 118 for (let length = Math.min(8, id.length); length < id.length; length++) {
85 119 const prefix = id.slice(0, length);
499 533 return;
535 + if (command === "search") {
536 + const query = rest.join(" ").trim();
537 + if (!query) throw new Error("Usage: /bak search <name or path>");
538 + if (!cache) {
539 + setProgress(ctx, "refreshing");
540 + cache = await runSerial(() =>
541 + client.refresh(lifecycleController?.signal),
542 + );
544 + const results = searchRecords(cache, query);
545 + notify(
546 + ctx,
547 + results.length
548 + ? results
549 + .map(
550 + ({ alias, record, prefix }) =>
551 + `${alias}/${prefix} ${record.name ?? record.cwd} (${record.created.slice(0, 10)})`,
553 + .join("\n") +
554 + (results.length === SEARCH_LIMIT
555 + ? "\nShowing first 10; narrow query for more"
556 + : "")
557 + : `no sessions match ${query}`,
558 + );
559 + return;
501 561 if (command === "restore") {
502 562 const parsed = destinationArgs(rest.join(" "));
503 563 if (!parsed.target)
530 590 return;
532 592 throw new Error(
533 - "Usage: /bak init <alias> | backup | restore <alias>/<id-prefix>|all [path] | refresh | status",
593 + "Usage: /bak init <alias> | backup | restore <alias>/<id-prefix>|all [path] | search <name or path> | refresh | status",
535 595 } catch (error) {
536 596 lastError = errorText(error);

extensions/bak/index.ts

Modified
4 4 import type {
5 5 ExtensionAPI,
6 6 ExtensionContext,
7 7 } from "@earendil-works/pi-coding-agent";
8 8 import { s3Config } from "./config.js";
10 -const SUBCOMMANDS = ["init", "backup", "restore", "refresh", "status"];
10 +const SUBCOMMANDS = [
11 + "init",
12 + "backup",
13 + "restore",
14 + "search",
15 + "refresh",
16 + "status",
17 +];
12 19 type BakRuntime = ReturnType<
13 20 typeof import("./implementation.js")["createBakRuntime"]