my-durable 0.0.72 → 0.0.74

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.
Files changed (28) hide show
  1. package/README.md +2 -2
  2. package/apps/dpi-backend/API.md +1 -0
  3. package/apps/dpi-backend/src/backup.ts +18 -0
  4. package/apps/dpi-backend/src/notify-sinks.ts +104 -2
  5. package/apps/dpi-backend/src/routes.ts +10 -1
  6. package/apps/dpi-backend/src/store.ts +170 -7
  7. package/apps/dpi-backend/src/telegram.ts +176 -2
  8. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-BmxTF5DB.js +82 -0
  9. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-h81haD43.css +1 -0
  10. package/apps/dpi-playground/apps/dpi-playground-fe/dist/index.html +2 -2
  11. package/apps/dpi-playground/apps/dpi-playground-fe/src/components/NetworkSidebar.vue +43 -4
  12. package/apps/dpi-playground/apps/dpi-playground-hub/src/audit.ts +75 -42
  13. package/apps/dpi-playground/apps/dpi-playground-hub/src/monitor.ts +6 -2
  14. package/apps/dpi-playground/apps/dpi-playground-hub/src/mux.ts +6 -2
  15. package/apps/dpi-playground/apps/dpi-playground-hub/src/transport.ts +12 -0
  16. package/apps/dpi-playground/apps/dpi-playground-hub/src/tunnel-transport.ts +1 -1
  17. package/apps/dpi-sdk/src/api.ts +13 -1
  18. package/apps/dpi-sdk/src/client.ts +12 -5
  19. package/apps/dpi-sdk/src/models.ts +45 -2
  20. package/apps/dpi-sdk/src/node/config.ts +13 -2
  21. package/apps/dpi-sdk/src/node/drivers.ts +4 -0
  22. package/apps/dpi-tui/src/commands.ts +64 -2
  23. package/apps/dpi-tui/src/pairing.ts +2 -2
  24. package/apps/dpi-tui/src/views.ts +1 -1
  25. package/docs/host-project-checklist.md +1 -1
  26. package/package.json +1 -1
  27. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-CpNu1wqa.js +0 -81
  28. package/apps/dpi-playground/apps/dpi-playground-fe/dist/assets/index-DSU1QhGO.css +0 -1
package/README.md CHANGED
@@ -167,13 +167,13 @@ Fork any agent at any entry, from the transcript or with `/fork`. The fork copie
167
167
  <img src="images/15_web_client.png" alt="The web client: the network tree with five devices, the inspector's Session tab with the context bar, and an agent's transcript on a cloud VM" width="800">
168
168
  </p>
169
169
 
170
- The web client has three columns: the **network tree** (device → session → agent), the **inspector** and the **agent**. The inspector tabs are Session (model, thinking, context bar, usage), State, Tasks, Tools and Extend. The composer sends a follow-up, a steer (it joins after the current tool round) or a reject-if-busy, and `/` opens the slash commands. The browser never sees a token. It holds one SSE connection to the hub, and the hub opens the authenticated upstreams.
170
+ The web client has three columns: the **network tree** (device → session → agent), the **inspector** and the **agent**. The inspector tabs are Session (model, thinking, context bar, usage), State, Tasks, Tools and Extend. The composer sends a follow-up, a steer (it joins after the current tool round) or a reject-if-busy, and `/` opens the slash commands. The sidebar's search box matches session names, folders and models — and, across every online device, the text inside their transcripts, so one word finds the session where an agent said it. The browser never sees a token. It holds one SSE connection to the hub, and the hub opens the authenticated upstreams.
171
171
 
172
172
  <p align="center">
173
173
  <img src="images/16_terminal_client.svg" alt="dpi-tui attached to vm-1:release-notes: the device, workspace and agent header, write and bash tool rows with results, and the model, context and cost footer" width="780">
174
174
  </p>
175
175
 
176
- `dpi-tui` is pi's look and keys over the network API. Enter sends or steers, Alt+Enter queues a follow-up, Esc interrupts, and Ctrl+C on an empty prompt exits with the command to reattach. **The agent keeps running.**
176
+ `dpi-tui` is pi's look and keys over the network API. Enter sends or steers, Alt+Enter queues a follow-up, Esc interrupts, and Ctrl+C on an empty prompt exits with the command to reattach. **The agent keeps running.** `/find <text>` searches every session's transcript on the device and shows the agent, entry and snippet of each hit.
177
177
 
178
178
  ```bash
179
179
  just tui attach <device> # pick or create a session on a device
@@ -22,6 +22,7 @@ The contract every Durable Agent Network client uses: the web hub, `dpi-tui`, sc
22
22
  | `GET /v1/fs/dirs` | `?path=` (empty = start dirs) | `{path, parent, dirs[]}`, one level, directories only |
23
23
  | `GET /v1/docs/app.shared-state` | | `{kind, value, revision}` |
24
24
  | `GET /v1/sessions` | | `SessionSummary[]` |
25
+ | `GET /v1/sessions/search` | `?q=` (`&scope=all` for transcripts) | metadata matches (`name`/`cwd`/`model`, cap 50). `scope=all` also scans stored history, newest sessions first, with budgets (100 sessions, 4000 entries per agent, 50k entries total): matches gain `where:[…,"transcript"]` and up to 3 `hits:[{agent, entry, kind, text}]` per agent, plus `scanned:{sessions, entries, truncated}`. A session that cannot open is skipped, never fails the search |
25
26
  | `POST /v1/sessions` | `{name, cwd, model?:{provider,modelId}, thinkingLevel?}` — model is optional: explicit → the project's default → the device default (`DeviceInfo.defaultModel`) | `201 SessionSummary` |
26
27
  | `GET / PATCH / DELETE /v1/sessions/:s` | PATCH `{name}` | summary (with its `compaction` thresholds); DELETE aborts all work, moves the files to `archive/` and returns `{archived}` |
27
28
  | `GET / PATCH /v1/sessions/:s/compaction` | PATCH `{enabled?, reserveTokens?, backgroundTokens?, keepRecentTokens?}` | the session's automatic compaction thresholds, read by pi-durable at its next request. Values are margins: the blocking summary starts at the model's context window minus `reserveTokens`, and the background one `backgroundTokens` earlier (0 turns it off). Default: a background summary at 200k tokens and a blocking one at 250k, or pi-durable's margins on smaller windows. Switching an agent to a window the thresholds do not fit refits them |
@@ -433,6 +433,24 @@ export function readZipEntries(data: Uint8Array): ZipArchiveEntry[] {
433
433
 
434
434
  /** Read + parse a backup file; restore and the CLI's plan share the `not_found` mapping. */
435
435
  export async function readBackupEntries(io: BackupIo, zipPath: string): Promise<ZipArchiveEntry[]> {
436
+ // R18 (run-4 h2): refuse by physical size BEFORE reading. The file is a
437
+ // 1:1 operator-own artifact, but a typed refusal beats a linear RAM spike
438
+ // into the CLI process (slack covers zip structure overhead: entries +
439
+ // central directory + any comment).
440
+ const PHYSICAL_SLACK_BYTES = 16 * 1024 * 1024;
441
+ try {
442
+ const size = (await io.stat(zipPath)).size;
443
+ if (size > MAX_BACKUP_BYTES + PHYSICAL_SLACK_BYTES) {
444
+ const mbSize = (n: number) => `${(n / (1024 * 1024)).toFixed(1)} MiB`;
445
+ throw new BackupError(
446
+ "invalid",
447
+ `backup ${zipPath} is ${mbSize(size)} on disk — over the ${mbSize(MAX_BACKUP_BYTES)} restore ceiling; refusing to load it`,
448
+ );
449
+ }
450
+ } catch (error) {
451
+ if (error instanceof BackupError) throw error;
452
+ throw new BackupError("not_found", `cannot read backup ${zipPath}: ${describeError(error)}`);
453
+ }
436
454
  let data: Uint8Array;
437
455
  try {
438
456
  data = await io.readFile(resolve(zipPath));
@@ -158,6 +158,8 @@ export type FetchLike = (
158
158
  headers: Record<string, string>;
159
159
  body: string;
160
160
  signal?: AbortSignal;
161
+ /** R19 (run-5 h7, leader-confirmed): redirects are refused — see attempt(). */
162
+ redirect?: "error" | "follow" | "manual";
161
163
  },
162
164
  ) => Promise<FetchResponseLike>;
163
165
 
@@ -229,21 +231,115 @@ const nonEmptyString = (value: unknown): string | undefined =>
229
231
  * the check — the flag exists to stop the obvious cases, not to be a firewall.
230
232
  */
231
233
  export function isPrivateHost(hostname: string): boolean {
232
- const host = hostname.trim().toLowerCase().replace(/^\[|\]$/g, "");
234
+ // R19 cold-review: a trailing dot is an FQDN root and resolves identically
235
+ // ("localhost." → ::1), so strip it before every name check.
236
+ const host = hostname.trim().toLowerCase().replace(/^\[|\]$/g, "").replace(/\.+$/, "");
233
237
  if (!host) return true;
234
238
  if (host === "localhost" || host.endsWith(".localhost")) return true;
239
+ // R19 cold-review MAJOR 2: the resolver is inet_aton-shaped, so a lone number
240
+ // is not the only alternate spelling — `0177.0.0.1` (octal) and `0x7f.0.0.1`
241
+ // (hex) both reach 127.0.0.1 through getaddrinfo. Canonicalise first.
235
242
  if (/^\d+$/.test(host)) return true; // decimal-encoded IPv4 (2130706433 → 127.0.0.1)
243
+ const canonical = canonicalIPv4(host);
244
+ if (canonical !== null && isPrivateIPv4(canonical)) return true;
236
245
  if (isPrivateIPv4(host)) return true;
237
246
  if (host.includes(":")) {
238
247
  if (host === "::" || host === "::1") return true;
239
248
  if (/^f[cd][0-9a-f]{2}:/.test(host)) return true; // fc00::/7 unique-local
240
249
  if (/^fe[89ab][0-9a-f]:/.test(host)) return true; // fe80::/10 link-local
241
- if (host.startsWith("::ffff:")) return isPrivateIPv4(host.slice("::ffff:".length));
250
+ if (host.startsWith("::ffff:")) {
251
+ const mapped = host.slice("::ffff:".length);
252
+ if (isPrivateIPv4(mapped)) return true; // dotted-quad mapped form
253
+ // R19 (run-5 h7, leader-confirmed): hex-group mapped spellings
254
+ // ("::ffff:7f00:1" = 127.0.0.1, "::ffff:a9fe:a9fe" = 169.254.169.254)
255
+ // classify as PUBLIC unless decoded here — WHATWG URL keeps the hex
256
+ // groups and the kernel maps the literal's low 32 bits to the IPv4
257
+ // destination. Decode by the LAST two groups (the kernel-mapped half).
258
+ const groups = mapped.split(":").filter(Boolean);
259
+ if (groups.length >= 1 && groups.every((g) => /^[0-9a-f]{1,4}$/i.test(g))) {
260
+ const value = ipv4FromLastGroups(groups);
261
+ if (value !== null && isPrivateIPv4(value)) return true;
262
+ }
263
+ return false;
264
+ }
265
+ // IPv4-compatible ::/96 spellings ("::7f00:1") — deprecated but connectable.
266
+ if (/^::[0-9a-f:]+$/.test(host) && host.includes(":")) {
267
+ const groups = host.slice(2).split(":").filter(Boolean);
268
+ if (groups.length >= 1 && groups.every((g) => /^[0-9a-f]{1,4}$/i.test(g))) {
269
+ const value = ipv4FromLastGroups(groups);
270
+ if (value !== null && isPrivateIPv4(value)) return true;
271
+ }
272
+ }
273
+ // R19 cold-review MAJOR 2: prefixes that CARRY an IPv4 destination.
274
+ // NAT64 64:ff9b::/96 (+ the 64:ff9b:1::/48 local-use block) → low 32 bits
275
+ // 6to4 2002::/16 → bits 16..48
276
+ // Teredo (2001::/32) obfuscates the client address (bitwise NOT) and its
277
+ // server address is attacker-chosen, so classify it as private outright.
278
+ if (/^64:ff9b(:|::)/.test(host)) {
279
+ const groups = host.slice(host.indexOf(":") + 1).split(":").filter(Boolean);
280
+ if (groups.every((g) => /^[0-9a-f]{1,4}$/.test(g))) {
281
+ if (groups.length < 3) return true; // 64:ff9b:1::/48 local-use block
282
+ const value = ipv4FromLastGroups(groups);
283
+ if (value === null || isPrivateIPv4(value)) return true;
284
+ }
285
+ return false;
286
+ }
287
+ if (/^2002:/.test(host)) {
288
+ const groups = host.split(":").filter(Boolean);
289
+ const hi = parseInt(groups[1] ?? "", 16);
290
+ const lo = parseInt(groups[2] ?? "", 16);
291
+ if (Number.isInteger(hi) && Number.isInteger(lo)) {
292
+ const v4 = `${(hi >>> 8) & 255}.${hi & 255}.${(lo >>> 8) & 255}.${lo & 255}`;
293
+ return isPrivateIPv4(v4);
294
+ }
295
+ return false;
296
+ }
297
+ if (/^2001:(?:0{1,4}|):/.test(host)) return true; // Teredo 2001:0000::/32, incl. the "2001::" compression
242
298
  return false;
243
299
  }
244
300
  return false;
245
301
  }
246
302
 
303
+ /**
304
+ * R19 cold-review MAJOR 2: inet_aton-compatible canonicalisation of a dotted
305
+ * IPv4 literal, so octal (`0177.0.0.1`) and hex (`0x7f.0.0.1`) octets cannot
306
+ * slip past the range checks. Returns dotted-quad, or null when the host is not
307
+ * an IPv4 literal at all.
308
+ */
309
+ function canonicalIPv4(host: string): string | null {
310
+ const parts = host.split(".");
311
+ if (parts.length < 1 || parts.length > 4) return null;
312
+ const octets: number[] = [];
313
+ for (const part of parts) {
314
+ if (!part) return null;
315
+ let n: number;
316
+ if (/^0x[0-9a-f]*$/.test(part)) n = part.length > 2 ? parseInt(part.slice(2), 16) : Number.NaN;
317
+ else if (/^0[0-7]+$/.test(part)) n = parseInt(part.slice(1), 8);
318
+ else if (/^\d+$/.test(part)) n = Number(part);
319
+ else return null;
320
+ if (!Number.isInteger(n) || n < 0) return null;
321
+ octets.push(n);
322
+ }
323
+ // inet_aton: the last part fills the remaining bytes (a.b.c.d, a.b.c, a.b, a).
324
+ const last = octets.pop()!;
325
+ const limit = 256 ** (4 - octets.length);
326
+ if (last >= limit) return null;
327
+ if (octets.some((n) => n > 255)) return null;
328
+ const value = octets.reduce((acc, n) => (acc << 8) | n, 0) * limit + last;
329
+ if (!Number.isSafeInteger(value) || value > 0xffffffff) return null;
330
+ return `${(value >>> 24) & 255}.${(value >>> 16) & 255}.${(value >>> 8) & 255}.${value & 255}`;
331
+ }
332
+
333
+ /** R19: decode the low 32 bits of a hex-group IPv6 tail into dotted-quad (null on overflow). */
334
+ function ipv4FromLastGroups(groups: string[]): string | null {
335
+ const last = groups[groups.length - 1]!;
336
+ const prev = groups[groups.length - 2];
337
+ const hi = prev !== undefined ? parseInt(prev, 16) : 0;
338
+ const lo = parseInt(last, 16);
339
+ const value = ((hi & 0xffff) << 16) | (lo & 0xffff);
340
+ return `${(value >>> 24) & 255}.${(value >>> 16) & 255}.${(value >>> 8) & 255}.${value & 255}`;
341
+ }
342
+
247
343
  function isPrivateIPv4(host: string): boolean {
248
344
  const parts = host.split(".");
249
345
  if (parts.length !== 4) return false;
@@ -794,6 +890,12 @@ export class NotifySinks {
794
890
  headers: request.headers,
795
891
  body: request.body,
796
892
  signal: AbortSignal.timeout(this.timeoutMs),
893
+ // R19 (run-5 h7, leader-confirmed): without this, a sink host's 3xx
894
+ // re-aims the daemon's POST at any loopback/LAN/metadata host the
895
+ // create-time private-host guard refuses — the redirect target is
896
+ // never re-validated. Refuse redirects like every other egress fetch
897
+ // in this repo (tunnel, pairing, jev, hub transport).
898
+ redirect: "error",
797
899
  });
798
900
  const ms = Date.now() - startedAt;
799
901
  const status = typeof response?.status === "number" ? response.status : 0;
@@ -350,7 +350,16 @@ export function v1(
350
350
  r.post("/sessions", create, route(async (req, res) => res.status(201).json(await store.create(req.body ?? {}))));
351
351
  // Literal route, so it must precede `/sessions/:s` (Express matches in order).
352
352
  // Names/cwds/models only — transcript search needs an FTS index, not a LIKE scan.
353
- r.get("/sessions/search", route(async (req, res) => res.json(store.searchSessions(String(req.query.q ?? "")))));
353
+ r.get(
354
+ "/sessions/search",
355
+ route(async (req, res) => {
356
+ const q = String(req.query.q ?? "");
357
+ // scope=all adds the bounded transcript scan (R18); default stays metadata-only
358
+ // so existing callers see the same shape and cost as before.
359
+ if (String(req.query.scope ?? "") === "all") return res.json(await store.searchSessionsAll(q));
360
+ return res.json(store.searchSessions(q));
361
+ }),
362
+ );
354
363
  r.get("/sessions/:s", route(async (_req, res) => res.json(await store.sessionSummary(L(res).row))));
355
364
  r.patch("/sessions/:s", route(async (req, res) => res.json(await store.rename(L(res).row, req.body?.name))));
356
365
  r.get("/sessions/:s/compaction", route(async (_req, res) => res.json(store.compactionOf(L(res).row.id))));
@@ -25,6 +25,7 @@ import type {
25
25
  TaskNode,
26
26
  TaskOutcome,
27
27
  ThinkingLevel,
28
+ TranscriptSearchHit,
28
29
  UsageTotals,
29
30
  WhenBusy,
30
31
  WireEntry,
@@ -45,6 +46,7 @@ import {
45
46
  type UsageSummary,
46
47
  } from "../../dpi-sdk/src/transcript.js";
47
48
  import { ApiFault, invalid, isStorageBusy, isUnreadableStorage, notFound, storageBusyFault } from "./errors.js";
49
+ import { searchHistory } from "./history.js";
48
50
  import { git, gitDirtyMarks, gitStatus, onGitDirty } from "./git.js";
49
51
  import { DatabaseSync } from "node:sqlite";
50
52
  import { mkdir, readdir, realpath, rename as renamePath, stat } from "node:fs/promises";
@@ -71,6 +73,7 @@ import {
71
73
  import {
72
74
  listArchived,
73
75
  findBundle,
76
+ readArchiveManifest,
74
77
  archivedTranscript,
75
78
  restoreArchive,
76
79
  writeArchiveManifest,
@@ -198,6 +201,16 @@ const CODE_DIR = resolve(import.meta.dirname, "../../..");
198
201
  /** Session search result cap: one screen of matches, not a transcript dump. */
199
202
  const SEARCH_LIMIT = 50;
200
203
 
204
+ /** Transcript-search budgets (scope=all): newest-first across sessions, bounded work. */
205
+ const TRANSCRIPT_SESSION_LIMIT = 100;
206
+ const TRANSCRIPT_AGENT_ENTRY_LIMIT = 4000;
207
+ const TRANSCRIPT_ENTRY_BUDGET = 50_000;
208
+ const TRANSCRIPT_HITS_PER_AGENT = 3;
209
+ /** R19 (run-5 h1): per-SESSION hit cap — hits accumulate 3×matching conversations
210
+ * (fork/subagent), so without this the per-agent cap says nothing about a match's
211
+ * total cardinality (leader-probe: 2 conversations → 5 hits, linear in forks). */
212
+ const TRANSCRIPT_HITS_PER_SESSION = 12;
213
+
201
214
  /** Scheduler granularity. Schedules are minute-granular, so 30 s is enough and
202
215
  * the timer is unref'd: it never holds the process open. */
203
216
  const SCHEDULE_TICK_MS = 30_000;
@@ -1522,6 +1535,7 @@ export class Store {
1522
1535
 
1523
1536
  /** Stop all work, close the harness and move its files to archive/. Nothing is deleted. */
1524
1537
  async archive(row: SessionRow) {
1538
+ this.salvageFailedSessions.delete(row.id); // R19: the bundle left this process's view
1525
1539
  const opened = this.opened.get(row.id);
1526
1540
  if (opened) {
1527
1541
  for (const record of await this.scanAll(opened.harness)) {
@@ -1584,18 +1598,50 @@ export class Store {
1584
1598
  }
1585
1599
 
1586
1600
  async restoreArchivedSession(sessionId: string): Promise<SessionSummary> {
1601
+ // R19 (run-5 h4 hardening): normalize ONCE — the live-check used to be
1602
+ // case-sensitive while the pin was case-normalized and the move target
1603
+ // raw, so an uppercase-hex id could bypass the live-session refusal and
1604
+ // strand the bundle. Every check below now sees the same canonical value.
1605
+ sessionId = sessionId.toLowerCase();
1606
+ this.salvageFailedSessions.delete(sessionId); // R19: the bundle came back — judge it fresh
1587
1607
  if (this.list().some((r) => r.id === sessionId))
1588
1608
  throw invalid("a live session with this id already exists");
1609
+ // R18 (run-4 h1): restore is a session-placement writer, so it enforces
1610
+ // the SAME choke point as create — a planted archive manifest must not
1611
+ // root a restored session (and its tool environment) outside the start
1612
+ // dirs. Leader-probe confirmed the verbatim insert bypassed it. The
1613
+ // validation runs BEFORE restoreArchive moves the bundle, so a refusal
1614
+ // leaves the archive untouched (restorable once the manifest is fixed).
1615
+ const bundleDir = findBundle(this.archiveDir, sessionId);
1616
+ if (!bundleDir) throw notFound(`no archived session ${sessionId}`);
1617
+ const pre = readArchiveManifest(bundleDir);
1618
+ if (pre && pre.sessionId !== sessionId)
1619
+ throw invalid(`archive manifest claims session ${pre.sessionId}, not ${sessionId} — refusing to restore under a foreign id`);
1620
+ const candidateCwd = pre?.cwd ?? "";
1621
+ if (!candidateCwd.trim())
1622
+ throw invalid(`archive manifest has no usable cwd — restore needs the bundle's session.json to name a start-dir folder`);
1623
+ let restoredCwd: string;
1624
+ try {
1625
+ restoredCwd = await realpath(resolve(candidateCwd));
1626
+ if (!(await stat(restoredCwd)).isDirectory()) throw Error();
1627
+ } catch {
1628
+ throw invalid(`archived cwd is not an existing folder on ${this.name}: ${candidateCwd}`);
1629
+ }
1630
+ await this.assertSessionCwdAllowed(restoredCwd);
1589
1631
  const manifest = await restoreArchive(this.archiveDir, this.options.dataDir, sessionId).catch(() => undefined);
1590
1632
  if (!manifest) throw notFound(`no archived session ${sessionId}`);
1633
+ // R19 (run-5 h4/h11 hardening): the catalog row is built from the
1634
+ // VALIDATED pre-move manifest, not restoreArchive's second, unpinned
1635
+ // re-read — a manifest swapped in during the move can no longer skew
1636
+ // id/dbPath (cwd stays the validated realpath either way).
1591
1637
  const row: SessionRow = {
1592
- id: manifest.sessionId,
1593
- name: manifest.name || "Untitled session",
1594
- cwd: manifest.cwd,
1595
- dbPath: join(this.sessionsDir, manifest.sessionId, "agent.sqlite"),
1596
- createdAt: manifest.createdAt,
1597
- model: manifest.model,
1598
- provider: manifest.provider,
1638
+ id: sessionId,
1639
+ name: pre?.name || manifest.name || "Untitled session",
1640
+ cwd: restoredCwd,
1641
+ dbPath: join(this.sessionsDir, sessionId, "agent.sqlite"),
1642
+ createdAt: pre?.createdAt ?? manifest.createdAt,
1643
+ model: pre?.model ?? manifest.model,
1644
+ provider: pre?.provider ?? manifest.provider,
1599
1645
  };
1600
1646
  this.catalog.exec("BEGIN");
1601
1647
  try {
@@ -1667,6 +1713,10 @@ export class Store {
1667
1713
  this.salvageInFlight.set(row.id, inFlight);
1668
1714
  const outcome = await inFlight;
1669
1715
  if (!outcome.recovered) {
1716
+ // R19 (run-5 h1): attempt-once — a failed salvage is memoized for the
1717
+ // process lifetime so every later open (and every scope=all query's
1718
+ // reopen) fails fast instead of re-copying the corrupt database.
1719
+ this.salvageFailedSessions.add(row.id);
1670
1720
  const note = salvageFailureNote(outcome);
1671
1721
  const previous = this.errors.get(row.id);
1672
1722
  this.errors.set(row.id, note); // rides the session summary and every later fault
@@ -2556,6 +2606,106 @@ export class Store {
2556
2606
  return { query, matches: matches.slice(0, SEARCH_LIMIT) };
2557
2607
  }
2558
2608
 
2609
+ /**
2610
+ * R18 transcript search (scope=all): the metadata pass above, PLUS a
2611
+ * bounded newest-first scan of every session's stored history — the answer
2612
+ * to "which session did the agent say X in?". One broken session (storage
2613
+ * busy, unopenable) is skipped, never fails the search. Budgets: newest
2614
+ * TRANSCRIPT_SESSION_LIMIT sessions, TRANSCRIPT_AGENT_ENTRY_LIMIT entries per
2615
+ * agent, TRANSCRIPT_ENTRY_BUDGET entries total (truncated=true past that).
2616
+ */
2617
+ async searchSessionsAll(rawQuery: string): Promise<SessionSearchResult> {
2618
+ const query = String(rawQuery ?? "").trim();
2619
+ const result = this.searchSessions(query);
2620
+ if (query.length < 2) return result;
2621
+ const byId = new Map(
2622
+ result.matches.map((m) => [m.id, { ...m, hits: [] as TranscriptSearchHit[] }] as const),
2623
+ );
2624
+ let entriesScanned = 0;
2625
+ let sessionsScanned = 0;
2626
+ let truncated = false;
2627
+ for (const row of this.list()) {
2628
+ // R19 (run-5 h1, leader-probed): a session whose salvage already FAILED
2629
+ // never re-opens — the reopen used to re-run the whole-DB copy +
2630
+ // integrity_check on EVERY query (262 MB corrupt db: 5.0 s per query,
2631
+ // memoization-free), and the FE fires scope=all per keystroke.
2632
+ if (this.salvageFailedSessions.has(row.id)) continue;
2633
+ if (sessionsScanned >= TRANSCRIPT_SESSION_LIMIT || entriesScanned >= TRANSCRIPT_ENTRY_BUDGET) {
2634
+ truncated = true;
2635
+ break;
2636
+ }
2637
+ sessionsScanned += 1;
2638
+ let h: Harness;
2639
+ try {
2640
+ try {
2641
+ h = this.harness(row);
2642
+ } catch {
2643
+ h = await this.reopenOnce(row);
2644
+ }
2645
+ } catch {
2646
+ continue; // a session that cannot open does not block the search
2647
+ }
2648
+ try {
2649
+ let marked = false;
2650
+ const names = this.names(row.id);
2651
+ for (const record of await this.scanAll(h)) {
2652
+ // The TOTAL budget binds inside the conversation loop too: a
2653
+ // fork-heavy session (a flagship feature) has many conversations,
2654
+ // and per-agent caps alone let one session scan past 50k entries
2655
+ // (cold-review major 2 — API.md promises a total budget).
2656
+ if (entriesScanned >= TRANSCRIPT_ENTRY_BUDGET) {
2657
+ truncated = true;
2658
+ break;
2659
+ }
2660
+ const c = await h.conversation(record.id as ConversationId, ctx);
2661
+ if (!c) continue;
2662
+ const entries: WireEntry[] = [];
2663
+ let cursor: string | undefined;
2664
+ do {
2665
+ const page = await c.entries({}, 2000, decodeCursor(cursor), ctx);
2666
+ entries.push(...(page.items as unknown as WireEntry[]));
2667
+ cursor = encodeCursor(page.next);
2668
+ } while (cursor && entries.length < TRANSCRIPT_AGENT_ENTRY_LIMIT);
2669
+ entriesScanned += entries.length;
2670
+ const hits = searchHistory(entries, { query, order: "newest", limit: TRANSCRIPT_HITS_PER_AGENT }, {}).results;
2671
+ if (!hits.length) continue;
2672
+ const ref = this.agentRef(record, names);
2673
+ const base = byId.get(row.id) ?? {
2674
+ ...this.sessionSummaryBase(row),
2675
+ where: [],
2676
+ hits: [] as TranscriptSearchHit[],
2677
+ };
2678
+ if (!marked) {
2679
+ base.where.push("transcript");
2680
+ marked = true;
2681
+ }
2682
+ for (const hit of hits) {
2683
+ if (base.hits!.length >= TRANSCRIPT_HITS_PER_SESSION) break;
2684
+ base.hits!.push({ agent: ref.name, entry: hit.entry, kind: hit.kind, text: hit.text });
2685
+ }
2686
+ byId.set(row.id, base);
2687
+ }
2688
+ } catch {
2689
+ continue; // one session's read failure never fails the search
2690
+ }
2691
+ }
2692
+ // Name hits first, then transcript hits, then the newest — same intent as the metadata pass.
2693
+ const matches = [...byId.values()]
2694
+ .filter((m) => m.where.length)
2695
+ .sort(
2696
+ (a, b) =>
2697
+ Number(b.where.includes("name")) - Number(a.where.includes("name")) ||
2698
+ Number(b.where.includes("transcript")) - Number(a.where.includes("transcript")) ||
2699
+ b.createdAt - a.createdAt,
2700
+ )
2701
+ .slice(0, SEARCH_LIMIT);
2702
+ return {
2703
+ query,
2704
+ matches,
2705
+ scanned: { sessions: sessionsScanned, entries: entriesScanned, truncated },
2706
+ };
2707
+ }
2708
+
2559
2709
  /**
2560
2710
  * One downloadable archive of a session: manifest, session record, and every
2561
2711
  * agent's transcript + config (paseo `exports.ts` shape). Text only, zipped by
@@ -2733,6 +2883,19 @@ export class Store {
2733
2883
  /** R10 5.2: per-session salvage single-flight — concurrent openers of one
2734
2884
  * corrupt session share ONE bounded attempt instead of racing scratch files. */
2735
2885
  private salvageInFlight = new Map<string, Promise<import("./salvage.js").SalvageOutcome>>();
2886
+ /** R19 (run-5 h1): sessions whose salvage already failed — searched cheaply skipped, salvage never re-run. */
2887
+ private salvageFailedSessions = new Set<string>();
2888
+
2889
+ /**
2890
+ * R19 (run-5 h1): the salvage memo is per-process so a corrupt session is not
2891
+ * re-copied on every scope=all query. It must NOT outlive the session's
2892
+ * lifecycle: archiving, restoring or deleting a session calls this so a
2893
+ * repaired database becomes searchable again in the same process.
2894
+ */
2895
+ clearSalvageMemo(sessionId?: string): void {
2896
+ if (sessionId === undefined) this.salvageFailedSessions.clear();
2897
+ else this.salvageFailedSessions.delete(sessionId);
2898
+ }
2736
2899
 
2737
2900
  /** R8 schedule budgets (StoreOptions-overridable so tests simulate wedged
2738
2901
  * dispatches in milliseconds instead of minutes). */