@pi-chamber/web 0.3.3 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/README.md +1 -0
  2. package/bin/lib/cli-startup.js +1 -0
  3. package/dist/assets/CommitSection-0zl1puqf.js +1 -0
  4. package/dist/assets/DiagramEditor-CFV_TjE2.js +1 -0
  5. package/dist/assets/DiagramView-0I4PZUpw.js +1 -0
  6. package/dist/assets/{DiffView-DGD9DMS7.js → DiffView-BoTz2Zqe.js} +2 -2
  7. package/dist/assets/{FilesView-DB5VI7EN.js → FilesView-CVMNE9Pr.js} +6 -6
  8. package/dist/assets/GitView-DnsbCAWl.js +6 -0
  9. package/dist/assets/JsonTreeView-Cn1Mk0Wf.js +1 -0
  10. package/dist/assets/{MarkdownRendererImpl-V1HMFCjr.js → MarkdownRendererImpl-DJKD8tNq.js} +2 -2
  11. package/dist/assets/PatchDiff-GdGq3IlM.js +1 -0
  12. package/dist/assets/PierreDiffViewer-CdkAUt-S.js +136 -0
  13. package/dist/assets/SessionSwitcherContent-BTzVmIop.js +1 -0
  14. package/dist/assets/SessionSwitcherDropdown-DuPmnk3k.js +2 -0
  15. package/dist/assets/SessionUnreadDot-ogHL0INY.js +1 -0
  16. package/dist/assets/SettingsView-SHhVrRdh.js +4 -0
  17. package/dist/assets/SettingsWindow-D_D1qqLF.js +1 -0
  18. package/dist/assets/{ToolOutputDialog-2zKUdGYL.js → ToolOutputDialog-BHaf293m.js} +6 -6
  19. package/dist/assets/ToolPartDiffPreview-BTMXNcqG.js +8 -0
  20. package/dist/assets/{VirtualizedFileDiff-UMgLcO4Q.js → VirtualizedFileDiff-CRVvv23V.js} +4 -4
  21. package/dist/assets/{SessionSwitcherDropdown-o1RjhCfF.js → WindowsWindowControls-CTtxXnD1.js} +172 -123
  22. package/dist/assets/collapsible-BO4qEdib.js +1 -0
  23. package/dist/assets/computeVirtualFileMetrics-D1I8YrPV.js +3 -0
  24. package/dist/assets/contextFileOpenGuard-w5xG9Qz2.js +1 -0
  25. package/dist/assets/index-3zee2IYy.css +1 -0
  26. package/dist/assets/{index-BAqpUCjs.js → index-CI-cd-mw.js} +6 -6
  27. package/dist/assets/index-DbghctxK.js +1 -0
  28. package/dist/assets/isDiffPlainText-BK9bF1l5.js +1 -0
  29. package/dist/assets/isFilePlainText-Cua0RCRz.js +1 -0
  30. package/dist/assets/main-BNJQ6mSF.js +2 -0
  31. package/dist/assets/{main-CmkRaMOR.js → main-CoA--JT-.js} +6 -6
  32. package/dist/assets/markdownCore-BGlLZrb8.js +3 -0
  33. package/dist/assets/miniChat-DU2jFhXq.js +2 -0
  34. package/dist/assets/mobile-B3lJ_CJR.js +2 -0
  35. package/dist/assets/renderElectronMiniChatApp-BfXYv3zl.js +2 -0
  36. package/dist/assets/renderMobileApp-Cd_F7yMe.js +14 -0
  37. package/dist/assets/{runtimeSurface-CkHYYg0E.js → runtimeSurface-UriLeO95.js} +1 -1
  38. package/dist/assets/{useInlineCommentController-DD31jQNC.js → useInlineCommentController-5XANmO1k.js} +2 -2
  39. package/dist/assets/usePanelSlide-CBZw2Cjo.js +56 -0
  40. package/dist/assets/useSwitcherItems-Cc6Tx-LO.js +1 -0
  41. package/dist/assets/{useWindowTitle-DoHrUC5r.js → useWindowTitle-Bf8ZNN_R.js} +1 -1
  42. package/dist/assets/{vendor-codemirror-language-data-Dp_Z-0GD.js → vendor-codemirror-language-data-DxpwplIe.js} +2 -2
  43. package/dist/assets/{vendor-katex-CHD9BdDO.js → vendor-katex-CNckGUMB.js} +1 -1
  44. package/dist/assets/{vendor-marked-i_gIkIP3.js → vendor-marked-CX41MkDF.js} +1 -1
  45. package/dist/assets/{web-components-Cct1r-wn.js → web-components-g7DKkne_.js} +4 -4
  46. package/dist/index.html +5 -5
  47. package/dist/mini-chat.html +4 -4
  48. package/dist/mobile.html +4 -4
  49. package/dist/sw.js +1 -1
  50. package/package.json +1 -1
  51. package/server/index.js +27 -5
  52. package/server/lib/fs/routes.js +0 -21
  53. package/server/lib/git/DOCUMENTATION.md +13 -3
  54. package/server/lib/git/routes.js +80 -4
  55. package/server/lib/git/routes.test.js +135 -0
  56. package/server/lib/git/service.js +130 -31
  57. package/server/lib/git/service.test.js +146 -0
  58. package/server/lib/pi/routes.js +67 -2
  59. package/server/lib/pi/routes.test.js +43 -3
  60. package/server/lib/pi/session-daemon/DOCUMENTATION.md +4 -4
  61. package/server/lib/pi/session-daemon/message-entry-aliases.js +53 -13
  62. package/server/lib/pi/session-daemon/message-entry-aliases.test.js +110 -0
  63. package/server/lib/pi/session-daemon/session-daemon.js +181 -22
  64. package/server/lib/pi/session-daemon/session-daemon.test.js +123 -3
  65. package/server/lib/pi/session-daemon/session-retry-limits.js +55 -0
  66. package/server/lib/pi/session-daemon/session-retry-limits.test.js +53 -0
  67. package/server/lib/pi/session-daemon/skill-read-classifier.js +39 -0
  68. package/server/lib/pi/session-daemon/skill-read-classifier.test.js +41 -0
  69. package/server/lib/pi/session-daemon/supervisor.js +3 -0
  70. package/server/lib/pi/small-model-generation.js +104 -0
  71. package/server/lib/pi/small-model-generation.test.js +66 -0
  72. package/server/lib/preview/proxy-runtime.js +11 -1
  73. package/server/lib/preview/proxy-runtime.test.js +3 -0
  74. package/server/lib/relay/tunnel-host.js +1 -0
  75. package/server/lib/stt/DOCUMENTATION.md +38 -0
  76. package/server/lib/stt/audio.js +47 -0
  77. package/server/lib/stt/config-store.js +81 -0
  78. package/server/lib/stt/config-store.test.js +36 -0
  79. package/server/lib/stt/local/model-catalog.js +57 -0
  80. package/server/lib/stt/local/model-downloader.js +127 -0
  81. package/server/lib/stt/local/recognizer.js +64 -0
  82. package/server/lib/stt/local/sherpa-loader.js +43 -0
  83. package/server/lib/stt/local/worker-client.js +115 -0
  84. package/server/lib/stt/local/worker-process.js +64 -0
  85. package/server/lib/stt/protocol.js +38 -0
  86. package/server/lib/stt/protocol.test.js +17 -0
  87. package/server/lib/stt/providers/local-worker-provider.js +11 -0
  88. package/server/lib/stt/providers/openai-compatible-provider.js +31 -0
  89. package/server/lib/stt/providers/openai-compatible-provider.test.js +31 -0
  90. package/server/lib/stt/runtime.js +111 -0
  91. package/server/lib/stt/service.js +106 -0
  92. package/server/lib/stt/stream-manager.js +188 -0
  93. package/server/lib/stt/stream-manager.test.js +64 -0
  94. package/server/lib/ui-auth/DOCUMENTATION.md +1 -1
  95. package/server/lib/ui-auth/ui-auth.js +8 -3
  96. package/server/lib/ui-auth/ui-auth.test.js +8 -0
  97. package/server/lib/workspace/host.js +18 -2
  98. package/dist/assets/CommitSection-BAYzLtBf.js +0 -1
  99. package/dist/assets/DiagramEditor-D1yc4joK.js +0 -1
  100. package/dist/assets/DiagramView-CAlJiG11.js +0 -1
  101. package/dist/assets/GitView-CFlPcSn9.js +0 -6
  102. package/dist/assets/JsonTreeView-CoX1ZscV.js +0 -1
  103. package/dist/assets/PatchDiff-D6Gs7K5B.js +0 -1
  104. package/dist/assets/PierreDiffViewer-COYd5Qr-.js +0 -136
  105. package/dist/assets/SettingsView-BYqvfMTS.js +0 -4
  106. package/dist/assets/SettingsWindow-CtNS0tQn.js +0 -1
  107. package/dist/assets/ToolPartDiffPreview-CBFC9min.js +0 -8
  108. package/dist/assets/collapsible-Kx4bmsQM.js +0 -1
  109. package/dist/assets/computeVirtualFileMetrics-DdOCbMyK.js +0 -3
  110. package/dist/assets/contextFileOpenGuard-BRldMp0d.js +0 -1
  111. package/dist/assets/index-CuSNEV7s.js +0 -1
  112. package/dist/assets/index-riABQmQ_.css +0 -1
  113. package/dist/assets/isDiffPlainText-CGIf0q8p.js +0 -1
  114. package/dist/assets/isFilePlainText-D4hgTRxT.js +0 -1
  115. package/dist/assets/main-By_pvk90.js +0 -2
  116. package/dist/assets/markdownCore-CAVCyFnI.js +0 -2
  117. package/dist/assets/miniChat-_XK2gGZE.js +0 -2
  118. package/dist/assets/mobile-B4E4JqAf.js +0 -2
  119. package/dist/assets/renderElectronMiniChatApp-Ca4hZgIz.js +0 -1
  120. package/dist/assets/renderMobileApp-ClA5Cnmw.js +0 -14
  121. package/dist/assets/usePanelSlide-a4c67FIY.js +0 -56
@@ -100,6 +100,37 @@ describe('Pi runtime route', () => {
100
100
  await expect((await fetch(`${base}/api/pi/update-check`)).json()).resolves.toEqual({ available: false, currentVersion: '1.0.0' });
101
101
  });
102
102
 
103
+ it('generates a task name with the configured small model without exposing model details', async () => {
104
+ const calls = [];
105
+ const app = express();
106
+ app.use(express.json());
107
+ registerPiRuntimeRoutes(app, {
108
+ getPiSessionDaemonRuntime: () => null,
109
+ settingsStore: {
110
+ read: async () => ({ smallModel: { providerId: 'provider', modelId: 'small' } }),
111
+ },
112
+ smallModelGenerator: async (input) => {
113
+ calls.push(input);
114
+ return { text: 'fix-auth-timeout' };
115
+ },
116
+ });
117
+ server = await listen(app);
118
+ const response = await fetch(`http://127.0.0.1:${server.address().port}/api/pi/small-model/generate`, {
119
+ method: 'POST',
120
+ headers: { 'Content-Type': 'application/json' },
121
+ body: JSON.stringify({ directory: '/repo', prompt: 'Fix the authentication timeout' }),
122
+ });
123
+
124
+ expect(response.status).toBe(200);
125
+ await expect(response.json()).resolves.toEqual({ text: 'fix-auth-timeout' });
126
+ expect(calls).toHaveLength(1);
127
+ expect(calls[0]).toMatchObject({
128
+ directory: '/repo',
129
+ model: { providerId: 'provider', modelId: 'small' },
130
+ });
131
+ expect(calls[0].prompt).toContain('Fix the authentication timeout');
132
+ });
133
+
103
134
  it('lists and selects only daemon-owned projects', async () => {
104
135
  const calls = [];
105
136
  const runtime = {
@@ -497,6 +528,7 @@ describe('Pi runtime route', () => {
497
528
  if (command === 'sessions.tree') return { rootId: 'pi-session-7', nodes: [{ entryId: 'entry-7', updatedAt: 2, children: [], privatePath: '/private' }] };
498
529
  if (command === 'sessions.list') return { sessions: [{ session: detail.session, updatedAt: 2 }] };
499
530
  if (['sessions.prompt', 'sessions.steer', 'sessions.followUp'].includes(command)) return { accepted: true, messageId: 'message-1' };
531
+ if (command === 'sessions.compact') return { accepted: true };
500
532
  return {};
501
533
  },
502
534
  };
@@ -515,9 +547,10 @@ describe('Pi runtime route', () => {
515
547
  for (const suffix of ['prompt', 'steer', 'follow-up']) {
516
548
  expect((await fetch(`${base}/${suffix}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ sessionId: 'other', text: 'hello' }) })).status).toBe(202);
517
549
  }
518
- for (const [suffix, body] of [['abort', {}], ['model', { model: { providerId: 'test', modelId: 'model' } }], ['thinking', { thinking: 'high' }], ['compact', { thinking: 'low' }]]) {
550
+ for (const [suffix, body] of [['abort', {}], ['model', { model: { providerId: 'test', modelId: 'model' } }], ['thinking', { thinking: 'high' }]]) {
519
551
  expect((await fetch(`${base}/${suffix}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ sessionId: 'other', ...body }) })).status).toBe(204);
520
552
  }
553
+ expect((await fetch(`${base}/compact`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ sessionId: 'other', thinking: 'low' }) })).status).toBe(202);
521
554
  const callsBeforeArchive = calls.length;
522
555
  expect((await fetch(`${base}/archive`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ archived: false }) })).status).toBe(204);
523
556
  expect(calls).toContainEqual({ command: 'archive.set', payload: ['pi-session-7', false] });
@@ -543,11 +576,13 @@ describe('Pi runtime route', () => {
543
576
  const runtime = {
544
577
  health: async () => ({ state: 'ready', protocolVersion: 1, capabilities: [] }),
545
578
  subscribe: async ({ onEvent }) => {
546
- onEvent({ protocolVersion: 1, kind: 'event', event: 'session.snapshot', sequence: 4, payload: { sessionId: 'pi-session-5', directory: '/workspace', isStreaming: true, lifecycle: 'retry', retry: { attempt: 1, next: 4_000, message: 'provider request timed out' }, queue: { steering: 0, followUp: 0 }, lastSequence: 4, endpoint: '/private/socket' } });
579
+ onEvent({ protocolVersion: 1, kind: 'event', event: 'session.snapshot', sequence: 4, payload: { sessionId: 'pi-session-5', directory: '/workspace', isStreaming: true, lifecycle: 'retry', retry: { attempt: 1, next: 4_000, message: 'provider request timed out' }, compaction: { phase: 'running', reason: 'overflow', startedAt: 3_000 }, queue: { steering: 0, followUp: 0 }, lastSequence: 4, endpoint: '/private/socket' } });
547
580
  onEvent({ protocolVersion: 1, kind: 'event', event: 'assistant.message.start', sequence: 5, payload: { sessionId: 'pi-session-5', directory: '/workspace', messageId: 'assistant-1', parentId: 'user-1', role: 'assistant', startedAt: 1 } });
548
581
  onEvent({ protocolVersion: 1, kind: 'event', event: 'assistant.message.end', sequence: 6, payload: { sessionId: 'pi-session-5', directory: '/workspace', messageId: 'assistant-1', durationMs: 42, continuing: true, error: { code: 'ASSISTANT_ERROR', message: 'provider request timed out' } } });
549
582
  onEvent({ protocolVersion: 1, kind: 'event', event: 'session.lifecycle', sequence: 7, payload: { sessionId: 'pi-session-5', directory: '/workspace', state: 'retry', attempt: 2, next: 8_000, message: 'provider request timed out' } });
550
583
  onEvent({ protocolVersion: 1, kind: 'event', event: 'session.error', sequence: 8, payload: { sessionId: 'pi-session-5', directory: '/workspace', code: 'ASSISTANT_ERROR', message: 'provider request timed out' } });
584
+ onEvent({ protocolVersion: 1, kind: 'event', event: 'session.tool.start', sequence: 9, payload: { sessionId: 'pi-session-5', directory: '/workspace', toolCallId: 'skill-read', partId: 'assistant-1:tool:skill-read', messageId: 'assistant-1', name: 'read', state: 'running', metadata: { pichamber: { skill: { name: 'review' } } }, privatePath: '/private/skill/SKILL.md' } });
585
+ onEvent({ protocolVersion: 1, kind: 'event', event: 'session.compaction', sequence: 10, payload: { sessionId: 'pi-session-5', directory: '/workspace', phase: 'completed', reason: 'overflow', startedAt: 3_000, completedAt: 9_000, tokensBefore: 120_000, estimatedTokensAfter: 24_000, willRetry: true, privateResult: 'hidden' } });
551
586
  return () => {};
552
587
  },
553
588
  };
@@ -558,7 +593,7 @@ describe('Pi runtime route', () => {
558
593
  const reader = response.body.getReader();
559
594
  const first = await reader.read();
560
595
  let text = new TextDecoder().decode(first.value);
561
- while (!text.includes('"state":"retry"')) {
596
+ while (!text.includes('"phase":"completed"')) {
562
597
  const next = await reader.read();
563
598
  if (next.done) break;
564
599
  text += new TextDecoder().decode(next.value);
@@ -567,11 +602,16 @@ describe('Pi runtime route', () => {
567
602
  expect(text).toContain('"name":"session.snapshot"');
568
603
  expect(text).toContain('"lastSequence":4');
569
604
  expect(text).toContain('"retry":{"attempt":1,"next":4000,"message":"provider request timed out"}');
605
+ expect(text).toContain('"compaction":{"phase":"running","reason":"overflow","startedAt":3000}');
570
606
  expect(text).toContain('"parentId":"user-1"');
571
607
  expect(text).toContain('"durationMs":42');
572
608
  expect(text).toContain('"continuing":true');
573
609
  expect(text).toContain('"state":"retry","attempt":2,"next":8000,"message":"provider request timed out"');
574
610
  expect(text).toContain('"message":"provider request timed out"');
611
+ expect(text).toContain('"metadata":{"pichamber":{"skill":{"name":"review"}}}');
612
+ expect(text).toContain('"phase":"completed","reason":"overflow","startedAt":3000,"completedAt":9000,"tokensBefore":120000,"estimatedTokensAfter":24000,"willRetry":true');
613
+ expect(text).not.toContain('privatePath');
614
+ expect(text).not.toContain('privateResult');
575
615
  expect(text).not.toContain('/private/socket');
576
616
  });
577
617
 
@@ -14,7 +14,7 @@ This module is the Pi-owned session-daemon foundation. A detached local daemon p
14
14
  - `runtime-registry.js` owns active runtime identities and session-local subscriptions. It rebinds the subscription after an SDK session replacement, rejects identity conflicts rather than displacing another runtime, and attempts every tracked disposal even when another disposal fails.
15
15
  - `session-jsonl.js` validates cwd-scoped Pi JSONL before discovery. List, create, and daemon startup require a valid session header per file; they do not read whole transcripts. `sessions.list` uses `listPiSessionJsonlDirectory` (header, first user prompt, latest rename from the file tail). Full-file validation remains on open of a specific session so a malformed body still fails that chat. Pi's SDK list is not the production list path because it scans every line of every log. Directory names match Pi's SessionManager encoding, including Windows drive letters and Git Bash/MSYS/Cygwin/WSL `/c/...` paths so PiChamber and the Pi CLI share the same JSONL sessions.
16
16
  - `supervisor.js` resolves server-only overrides, creates the credential, serializes start/reuse/stop through an owner-only lock, validates daemon identity through `runtime.health`, forwards server-owned commands only after that identity check, and starts or stops the detached process. Reuse requires the ready-state sidecar `entrypoint` to match this checkout's `daemon-process.js`; a healthy daemon from another install (or an older daemon that never recorded an entrypoint) is stopped and replaced so local `bun run dev` cannot keep answering `getSession` without the live-turn overlay. When the parent is Electron, the child is spawned with `ELECTRON_RUN_AS_NODE=1` so packaged Windows/macOS/Linux apps run the daemon as Node instead of a hidden second Electron GUI process.
17
- - `../routes.js` registers authenticated public adapters before the generic proxy. It exposes only whitelisted runtime, project, session, provider-auth/configuration, settings, resource, and SSE event shapes; no browser response contains daemon paths, credentials, PIDs, headers, or socket framing. Session actions are path-selected, so an identity supplied in a request body cannot redirect a mutation. `archive-store.js` persists PiChamber-only opaque session archive metadata atomically beneath the PiChamber data root and never edits Pi JSONL. `settings-store.js` keeps PiChamber new-session defaults separate from Pi settings.json. `GET /api/pi/settings` copies leftover UI/desktop `defaultModel` / small / walkthrough strings into that sidecar when those sidecar fields are unset, then Sessions settings is the only editor. Sidecar `defaultThinkingByModel` is the per-model thinking map (`provider/model` keys). A stored global `defaultThinking` with a default model is copied onto that map key and dropped; global thinking without a default model remains a clamp-only fallback. `ui-settings-store.js` atomically owns shared PiChamber UI preferences at the data-root `settings.json`; it is exposed as `/api/pi/ui-settings`, not through removed `/api/config/*` aliases. `session-folders-store.js` validates and atomically persists the restored sidebar's folder snapshot at `/api/pi/session-folders`; a missing snapshot is distinct from an empty one. `custom-themes.js` serves validated custom-theme candidates from `/api/pi/themes` with per-file partial-failure isolation. `model-config-store.js` atomically updates Pi's credential-blind `models.json`; literal keys continue through Pi auth and headers are write-only. `providers.config.get` returns `config: null` for a provider that is not in `models.json` (built-in catalog entries) and fails only when that file is present but malformed.
17
+ - `../routes.js` registers authenticated public adapters before the generic proxy. It exposes only whitelisted runtime, project, session, provider-auth/configuration, settings, resource, small-model utility, and SSE event shapes; no browser response contains daemon paths, credentials, PIDs, headers, or socket framing. Session actions are path-selected, so an identity supplied in a request body cannot redirect a mutation. `archive-store.js` persists PiChamber-only opaque session archive metadata atomically beneath the PiChamber data root and never edits Pi JSONL. `settings-store.js` keeps PiChamber new-session defaults separate from Pi settings.json. `/api/pi/small-model/generate` reads that sidecar and runs a bounded in-memory no-tools Pi session, so utility generation creates no visible or persisted session and exposes no model or credential details. `GET /api/pi/settings` copies leftover UI/desktop `defaultModel` / small / walkthrough strings into that sidecar when those sidecar fields are unset, then Sessions settings is the only editor. Sidecar `defaultThinkingByModel` is the per-model thinking map (`provider/model` keys). A stored global `defaultThinking` with a default model is copied onto that map key and dropped; global thinking without a default model remains a clamp-only fallback. `ui-settings-store.js` atomically owns shared PiChamber UI preferences at the data-root `settings.json`; it is exposed as `/api/pi/ui-settings`, not through removed `/api/config/*` aliases. `session-folders-store.js` validates and atomically persists the restored sidebar's folder snapshot at `/api/pi/session-folders`; a missing snapshot is distinct from an empty one. `custom-themes.js` serves validated custom-theme candidates from `/api/pi/themes` with per-file partial-failure isolation. `model-config-store.js` atomically updates Pi's credential-blind `models.json`; literal keys continue through Pi auth and headers are write-only. `providers.config.get` returns `config: null` for a provider that is not in `models.json` (built-in catalog entries) and fails only when that file is present but malformed.
18
18
  - `*.test.js` uses temporary cwd, agent, data, and runtime directories; it never loads a developer's Pi home, credentials, or sessions. On Windows the private endpoint is a named pipe, not a `.sock` file, and POSIX mode-bit assertions are skipped.
19
19
 
20
20
  ## Protocol and security invariants
@@ -25,12 +25,12 @@ This module is the Pi-owned session-daemon foundation. A detached local daemon p
25
25
  - The public health route deliberately whitelists its response fields. It never returns a daemon endpoint, credential, PID, cwd, agent directory, or transcript data. Public transcript and event projections preserve daemon-redacted assistant error messages so the UI can distinguish provider/runtime failures instead of reducing every failure to `ASSISTANT_ERROR`.
26
26
  - A client must send an `authenticate` frame carrying the host-private daemon credential before it can issue a request. Credentials are never logged or returned.
27
27
  - Frames are LF-delimited JSON. They have a 1 MiB maximum buffered size. A malformed, oversized, unauthenticated, or invalid request closes the connection.
28
- - The private core commands are `runtime.health`, `projects.list/select`, `providers.list/config.get/models.set/status/login/login.respond/login.status/logout`, `settings.get/set`, `resources.list/update/prompts.create/prompts.delete`, and session list/create/open/rename/delete/tree/navigate/fork/clone/prompt/steer/followUp/abort/model/thinking/compact operations. Resource lists use opaque IDs and never disclose server paths. Only top-level Pi prompt templates and applicable AGENTS.md sources are editable; package/path resources and skills are browse-only. Resource writes are rejected while a session streams, use an atomic replace, then recreate the idle runtime. Project trust changes are persisted in Pi trust.json and likewise recreate an idle runtime; extensions remain disabled regardless of trust. Provider login submits API keys only across authenticated private IPC or brokers Pi's OAuth/device/manual-code interaction; public projections contain only opaque login IDs, prompts, URLs/device codes, model catalog/configuration, and stable states, never credentials or write-only headers. `providers.models.set` is rejected while a session streams, atomically persists Pi's `models.json`, then rehydrates the idle runtime so the catalog is authoritative immediately. `providers.list` projects only catalog and authentication-status metadata, including Pi-supported `thinkingLevels` (`null` map entries hidden, `xhigh`/`max` opt-in). Session thinking overrides are clamped to the live model's supported levels. `sessions.list` checks each cwd JSONL header (not the full transcript) so a project with large session logs cannot spend tens of seconds on startup. SDK `SessionManager.list` is not used for that path; `listPiSessionJsonlDirectory` reads a header, a bounded prefix for the first user prompt, and a tail for the latest rename. Concurrent lists of the same directory share one in-flight result. Concurrent `sessions.open` of the same id share one in-flight runtime create; a duplicate that finishes later disposes itself and returns the registered runtime instead of `SESSION_RUNTIME_CONFLICT`. Full-file JSONL validation stays on open of a chosen session. The browser explicitly selects an existing user-chosen project directory before listing it; the daemon's startup cwd is an internal fallback, not a user-visible default project. Unnamed persisted sessions use their first prompt as a readable list title when available. `sessions.open` and `getSession` project the last assistant `provider`/`model`/`thinkingLevel` onto the session record so reopening a chat keeps that cache identity. Session selection validates a persisted JSONL path before Pi opens it; inactive mutations are never directed by a browser-supplied path. `sessions.open` resolves an id by Pi's `timestamp_<id>.jsonl` filename first so a missing deep link 404s without listing or fully reading every transcript in every cwd; SDK list and header scan remain the fallback for non-standard names. Directory-wide JSONL checks on list/create/startup are header-only; full-file validation stays on open of a chosen transcript. Attachment paths originate in the server-local upload map and cross only private IPC into Pi's tool context. Pi may persist or echo those paths in its authoritative JSONL transcript, so every public projection redacts them recursively: session titles/previews, user and assistant text/thinking, tool arguments, errors, snapshots, and live message events never expose the server-local path. Persisted projection first checks for the attachment marker, then redacts matching tokens with a delimiter scan whose work stays linear for large encoded strings and tool payloads. The daemon maps Pi message lifecycle, deltas, tools, queue changes, model/thinking, compaction, interruption state, and session title updates (`session.updated` on create-with-title, first-prompt auto-title, and rename) to canonical events. Tool events carry redacted input arguments, cumulative partial-output snapshots, final output, error text, renderer metadata (edit diffs, truncation notes), and start/end timestamps. Persisted `toolResult` entries merge into their assistant `toolCall` parts as output/error/end time so hydrated sessions render complete tool cards; tool-result entries never surface as standalone messages. Assistant message projections and start events carry the owning user-message id so the restored turn renderer can group and display replies; all assistant entries in a tool loop and every retry/compaction continuation remain attached to the latest user turn until `agent_settled` closes the run. Assistant message projections also pass through Pi's per-turn `Usage` (input, output, cacheRead, cacheWrite, totalTokens, and the same five numeric cost fields). The daemon sanitizes the raw payload through `projectUsage` before publication: every numeric must be finite and non-negative, the whole object is omitted when any field is missing or wrong type, and unknown keys are never copied. The `assistant.message.end` event carries the same sanitized usage so the last turn updates without waiting for a full `getSession` refetch. The public route whitelist re-applies the same sanitizer on each projection so a stale or malformed payload from a different daemon version cannot surface as `NaN` or `Infinity` in the reducer.
28
+ - The private core commands are `runtime.health`, `projects.list/select`, `providers.list/config.get/models.set/status/login/login.respond/login.status/logout`, `settings.get/set`, `resources.list/update/prompts.create/prompts.delete`, and session list/create/open/rename/delete/tree/navigate/fork/clone/prompt/steer/followUp/abort/model/thinking/compact operations. Resource lists use opaque IDs and never disclose server paths. Only top-level Pi prompt templates and applicable AGENTS.md sources are editable; package/path resources and skills are browse-only. Resource writes are rejected while a session streams, use an atomic replace, then recreate the idle runtime. Project trust changes are persisted in Pi trust.json and likewise recreate an idle runtime; extensions remain disabled regardless of trust. Provider login submits API keys only across authenticated private IPC or brokers Pi's OAuth/device/manual-code interaction; public projections contain only opaque login IDs, prompts, URLs/device codes, model catalog/configuration, and stable states, never credentials or write-only headers. `providers.models.set` is rejected while a session streams, atomically persists Pi's `models.json`, then rehydrates the idle runtime so the catalog is authoritative immediately. `providers.list` projects only catalog and authentication-status metadata, including Pi-supported `thinkingLevels` (`null` map entries hidden, `xhigh`/`max` opt-in). Session thinking overrides are clamped to the live model's supported levels. `sessions.list` checks each cwd JSONL header (not the full transcript) so a project with large session logs cannot spend tens of seconds on startup. SDK `SessionManager.list` is not used for that path; `listPiSessionJsonlDirectory` reads a header, a bounded prefix for the first user prompt, and a tail for the latest rename. Concurrent lists of the same directory share one in-flight result. Concurrent `sessions.open` of the same id share one in-flight runtime create; a duplicate that finishes later disposes itself and returns the registered runtime instead of `SESSION_RUNTIME_CONFLICT`. Full-file JSONL validation stays on open of a chosen session. The browser explicitly selects an existing user-chosen project directory before listing it; the daemon's startup cwd is an internal fallback, not a user-visible default project. Unnamed persisted sessions use their first prompt as a readable list title when available. `sessions.open` and `getSession` project the last assistant `provider`/`model`/`thinkingLevel` onto the session record so reopening a chat keeps that cache identity. Session selection validates a persisted JSONL path before Pi opens it; inactive mutations are never directed by a browser-supplied path. `sessions.open` resolves an id by Pi's `timestamp_<id>.jsonl` filename first so a missing deep link 404s without listing or fully reading every transcript in every cwd; SDK list and header scan remain the fallback for non-standard names. Directory-wide JSONL checks on list/create/startup are header-only; full-file validation stays on open of a chosen transcript. Attachment paths originate in the server-local upload map and cross only private IPC into Pi's tool context. Pi may persist or echo those paths in its authoritative JSONL transcript, so every public projection redacts them recursively: session titles/previews, user and assistant text/thinking, tool arguments, errors, snapshots, and live message events never expose the server-local path. Persisted projection first checks for the attachment marker, then redacts matching tokens with a delimiter scan whose work stays linear for large encoded strings and tool payloads. The daemon maps Pi message lifecycle, deltas, tools, queue changes, model/thinking, compaction, interruption state, and session title updates (`session.updated` on create-with-title, first-prompt auto-title, and rename) to canonical events. Compaction events preserve Pi's manual/threshold/overflow reason, active/retrying/terminal phase, retry timing, redacted failure, compact-and-retry intent, and pre/post token estimates. The latest state is included in `getSession` and reconnect snapshots; after daemon restart, the latest persisted Pi `CompactionEntry` restores completed feedback without treating history as live work. Tool events carry redacted input arguments, cumulative partial-output snapshots, final output, error text, renderer metadata (edit diffs, truncation notes), and start/end timestamps. Pi loads skills with the ordinary `read` tool. The daemon matches those read paths against the active runtime's authoritative `resourceLoader.getSkills()` catalog and adds path-free `metadata.pichamber.skill.name` for live events, hydrated history, and reconnect snapshots. PiChamber uses that metadata for its compact Skill row and Settings navigation; an arbitrary file named `SKILL.md` remains a normal read. Persisted `toolResult` entries merge into their assistant `toolCall` parts as output/error/end time so hydrated sessions render complete tool cards; tool-result entries never surface as standalone messages. Assistant message projections and start events carry the owning user-message id so the restored turn renderer can group and display replies; all assistant entries in a tool loop and every retry/compaction continuation remain attached to the latest user turn until `agent_settled` closes the run. Assistant message projections also pass through Pi's per-turn `Usage` (input, output, cacheRead, cacheWrite, totalTokens, and the same five numeric cost fields). The daemon sanitizes the raw payload through `projectUsage` before publication: every numeric must be finite and non-negative, the whole object is omitted when any field is missing or wrong type, and unknown keys are never copied. The `assistant.message.end` event carries the same sanitized usage so the last turn updates without waiting for a full `getSession` refetch. The public route whitelist re-applies the same sanitizer on each projection so a stale or malformed payload from a different daemon version cannot surface as `NaN` or `Infinity` in the reducer.
29
29
  - Live `message_start` events use daemon-generated browser message IDs because Pi has not appended the corresponding session entry yet. Pi agent-core emits streaming assistant starts as shallow copies, not as the finalized object it later persists. At `message_end`, `message-entry-aliases.js` therefore rebinds the synthetic ID to the finalized event object, then maps that object by identity to Pi's appended entry in a microtask. `sessions.navigate` and `sessions.fork` resolve the mapping after stripping any part suffix. Alias keys include cwd and session ID, survive idle runtime disposal, and clear only on explicit session deletion or daemon shutdown. Hydrated message projections continue to use the Pi entry ID directly.
30
30
  - Each event and reconnect snapshot has a monotonic sequence. A reconnect receives a bounded contiguous replay after its cursor when available, otherwise an authoritative `session.snapshot`; unavailable runtimes are not represented as empty sessions.
31
- - Prompt, steer, and follow-up requests acknowledge acceptance immediately after Pi accepts the call; the daemon owns the still-running send promise and publishes any asynchronous rejection as `session.error`. A later prompt on the same session invalidates that rejection so it cannot error the new turn. If the rejected send left Pi streaming, the daemon aborts it. Steer/follow-up against an idle session starts a new prompt instead of `SESSION_NOT_RUNNING`. Agent completion is never held behind the 30-second public/private request budgets. Pi retryable provider failures remain live: an `agent_end` with `willRetry` does not publish terminal `session.error`, and `auto_retry_start` projects Pi's attempt, next-attempt time, and redacted error text through `session.lifecycle: retry`. Retry metadata is retained in reconnect and `getSession` snapshots until the next `agent_start` begins the attempt. `agent_settled` remains the authoritative idle boundary after retry success, exhaustion, or cancellation and clears the run's user/assistant ownership.
31
+ - Prompt, steer, and follow-up requests acknowledge acceptance immediately after Pi accepts the call; the daemon owns the still-running send promise and publishes any asynchronous rejection as `session.error`. Manual compact requests likewise acknowledge startup instead of holding the public/private request open for the summarization call; the daemon-owned promise reports its outcome through `session.compaction`. A second compact request while Pi is compacting fails as `SESSION_BUSY`, and optional `/compact` instructions pass to `AgentSession.compact(customInstructions)`. A later prompt on the same session invalidates an older send rejection so it cannot error the new turn. If the rejected send left Pi streaming, the daemon aborts it. Steer/follow-up against an idle session starts a new prompt instead of `SESSION_NOT_RUNNING`. Agent and compaction completion are never held behind the 30-second public/private request budgets. Pi retryable provider failures remain live: an `agent_end` with `willRetry` does not publish terminal `session.error`, and `auto_retry_start` projects Pi's attempt, next-attempt time, and redacted error text through `session.lifecycle: retry`. Retry metadata is retained in reconnect and `getSession` snapshots until the next `agent_start` begins the attempt. `agent_settled` remains the authoritative idle boundary after retry success, exhaustion, or cancellation and clears the run's user/assistant ownership.
32
32
  - Registry keys combine the SDK session ID with its cwd. A replacement subscription is rebound to the replacement session so old-session events cannot be published under the new identity. A collision is a visible error; it never replaces or disposes an unrelated runtime.
33
- - After `agent_settled`, the daemon disposes an idle runtime after five minutes (injectable for tests). Disposal never deletes Pi JSONL; the daemon remembers the selected session file and recreates that runtime on the next private prompt. A new agent start cancels a pending disposal.
33
+ - After `agent_settled` or a terminal compaction that will not resume the turn, the daemon disposes an idle runtime after five minutes (injectable for tests). Disposal never deletes Pi JSONL; the daemon remembers the selected session file and recreates that runtime on the next private prompt. Agent and compaction starts cancel pending disposal, and the timer refuses to dispose a session while `isStreaming` or `isCompacting` is authoritative.
34
34
  - A startup validation failure writes only a stable failure code to the owner-only non-secret state sidecar. It never records a transcript, session path, or credential. The supervisor surfaces that code as unavailable instead of claiming an empty or idle session.
35
35
  - After a forced crash, the next health, request, or subscription probe re-runs supervised startup. Each private health probe uses the supervisor's five-second operation budget; it must not inherit the general 30-second command timeout and hold every browser request until the browser aborts. Daemon readiness has its own 15-second bounded budget, separate from the shorter probe, lock, and shutdown budget, because loading Pi settings and provider/model catalogs can legitimately exceed five seconds. The supervisor removes an existing POSIX socket only when its recorded daemon PID is dead, the endpoint is a socket, and authenticated IPC deterministically refuses or times out. An endpoint that responds, authenticates incorrectly, returns malformed protocol data, or cannot be classified remains `DAEMON_ENDPOINT_UNVERIFIED`.
36
36
  - The web server starts warming the supervisor immediately after HTTP listen without awaiting Pi provider/model initialization. A first request arriving during that warmup shares the supervisor's `startPromise`.
@@ -14,27 +14,67 @@ const findPersistedMessageEntry = (sessionManager, message) => {
14
14
  /**
15
15
  * Keeps daemon-published live message ids resolvable after Pi persists those
16
16
  * messages under its own session-entry ids.
17
+ *
18
+ * Scopes are pruned lazily: every retain stamps the scope's last-touched time
19
+ * and drops scopes idle beyond ALIAS_SCOPE_IDLE_TTL_MS (and, under memory
20
+ * pressure from very long-lived daemons with many abandoned sessions, the
21
+ * oldest scopes beyond MAX_SCOPES). Deleted sessions are cleared eagerly via
22
+ * clearSession; pruning here only bounds the ones that are merely abandoned.
17
23
  */
18
- export function createMessageEntryAliases({ scheduleMicrotask = queueMicrotask } = {}) {
24
+ export const ALIAS_SCOPE_IDLE_TTL_MS = 24 * 60 * 60 * 1000;
25
+ export const MAX_SCOPES = 512;
26
+ const PRUNE_EVERY_N_RETAINS = 64;
27
+
28
+ export function createMessageEntryAliases({ scheduleMicrotask = queueMicrotask, now = () => Date.now() } = {}) {
19
29
  const aliasesByScope = new Map();
20
30
  const pendingByMessage = new WeakMap();
31
+ let retainsSincePrune = 0;
32
+
33
+ const pruneScopes = (nowMs) => {
34
+ for (const [key, entry] of aliasesByScope.entries()) {
35
+ if (!entry || nowMs - (entry.lastTouchedAt || 0) > ALIAS_SCOPE_IDLE_TTL_MS) {
36
+ aliasesByScope.delete(key);
37
+ }
38
+ }
39
+ while (aliasesByScope.size > MAX_SCOPES) {
40
+ let oldestKey = null;
41
+ let oldestAt = Infinity;
42
+ for (const [key, entry] of aliasesByScope.entries()) {
43
+ const touchedAt = entry?.lastTouchedAt || 0;
44
+ if (touchedAt < oldestAt) {
45
+ oldestAt = touchedAt;
46
+ oldestKey = key;
47
+ }
48
+ }
49
+ if (!oldestKey) break;
50
+ aliasesByScope.delete(oldestKey);
51
+ }
52
+ };
21
53
 
22
- const getScope = (cwd, sessionId, create = false) => {
54
+ const getScopeEntry = (cwd, sessionId, create = false) => {
23
55
  const key = scopeKey(cwd, sessionId);
24
- let scope = aliasesByScope.get(key);
25
- if (!scope && create) {
26
- scope = new Map();
27
- aliasesByScope.set(key, scope);
56
+ let entry = aliasesByScope.get(key);
57
+ if (!entry && create) {
58
+ entry = { aliases: new Map(), lastTouchedAt: now() };
59
+ aliasesByScope.set(key, entry);
28
60
  }
29
- return scope;
61
+ return entry;
30
62
  };
31
63
 
64
+ const getScope = (cwd, sessionId, create = false) => getScopeEntry(cwd, sessionId, create)?.aliases;
65
+
32
66
  const retain = ({ cwd, sessionId, syntheticMessageId, message }) => {
33
67
  if (typeof cwd !== 'string' || typeof sessionId !== 'string' || typeof syntheticMessageId !== 'string'
34
68
  || !message || typeof message !== 'object') return;
35
69
  const alias = { message };
36
- getScope(cwd, sessionId, true).set(syntheticMessageId, alias);
70
+ const entry = getScopeEntry(cwd, sessionId, true);
71
+ entry.aliases.set(syntheticMessageId, alias);
72
+ entry.lastTouchedAt = now();
37
73
  pendingByMessage.set(message, { alias });
74
+ if (++retainsSincePrune >= PRUNE_EVERY_N_RETAINS) {
75
+ retainsSincePrune = 0;
76
+ pruneScopes(now());
77
+ }
38
78
  };
39
79
 
40
80
  const releasePersisted = (pending, sessionManager) => {
@@ -80,17 +120,17 @@ export function createMessageEntryAliases({ scheduleMicrotask = queueMicrotask }
80
120
 
81
121
  clearSession({ cwd, sessionId }) {
82
122
  const key = scopeKey(cwd, sessionId);
83
- const scope = aliasesByScope.get(key);
84
- if (!scope) return;
85
- for (const alias of scope.values()) {
123
+ const entry = aliasesByScope.get(key);
124
+ if (!entry) return;
125
+ for (const alias of entry.aliases.values()) {
86
126
  if (alias.message) pendingByMessage.delete(alias.message);
87
127
  }
88
128
  aliasesByScope.delete(key);
89
129
  },
90
130
 
91
131
  clear() {
92
- for (const scope of aliasesByScope.values()) {
93
- for (const alias of scope.values()) {
132
+ for (const entry of aliasesByScope.values()) {
133
+ for (const alias of entry.aliases.values()) {
94
134
  if (alias.message) pendingByMessage.delete(alias.message);
95
135
  }
96
136
  }
@@ -0,0 +1,110 @@
1
+ import { describe, expect, test } from 'vitest';
2
+ import {
3
+ ALIAS_SCOPE_IDLE_TTL_MS,
4
+ MAX_SCOPES,
5
+ createMessageEntryAliases,
6
+ } from './message-entry-aliases.js';
7
+
8
+ const createSessionManager = (entryId, message) => ({
9
+ getEntries: () => [{ type: 'message', id: entryId, message }],
10
+ getEntry: (id) => (id === entryId ? { id: entryId } : undefined),
11
+ });
12
+
13
+ describe('message entry aliases', () => {
14
+ test('retain + observeMessageEnd resolves the persisted Pi entry id', () => {
15
+ const aliases = createMessageEntryAliases({ scheduleMicrotask: (fn) => fn() });
16
+ const message = { role: 'assistant', content: 'hello' };
17
+ const sessionManager = createSessionManager('entry-1', message);
18
+
19
+ aliases.retain({ cwd: '/repo', sessionId: 's1', syntheticMessageId: 'asst-s1-7', message });
20
+ // Before Pi persists the message there is no entry to find: the synthetic
21
+ // id resolves to itself.
22
+ const emptyManager = { getEntries: () => [], getEntry: () => undefined };
23
+ expect(aliases.resolve({ cwd: '/repo', sessionId: 's1', requestedId: 'asst-s1-7', sessionManager: emptyManager })).toBe('asst-s1-7');
24
+ expect(aliases.resolve({ cwd: '/repo', sessionId: 's1', requestedId: 'asst-s1-7' })).toBe('asst-s1-7');
25
+
26
+ aliases.observeMessageEnd({
27
+ cwd: '/repo',
28
+ sessionId: 's1',
29
+ syntheticMessageId: 'asst-s1-7',
30
+ message,
31
+ sessionManager,
32
+ });
33
+
34
+ expect(aliases.resolve({ cwd: '/repo', sessionId: 's1', requestedId: 'asst-s1-7', sessionManager })).toBe('entry-1');
35
+ // Part-suffixed requests resolve through the same alias.
36
+ expect(aliases.resolve({ cwd: '/repo', sessionId: 's1', requestedId: 'asst-s1-7:2', sessionManager })).toBe('entry-1');
37
+ });
38
+
39
+ test('clearSession drops only that scope', () => {
40
+ const aliases = createMessageEntryAliases();
41
+ const messageA = { role: 'user' };
42
+ const messageB = { role: 'user' };
43
+ aliases.retain({ cwd: '/a', sessionId: 's1', syntheticMessageId: 'u-a', message: messageA });
44
+ aliases.retain({ cwd: '/b', sessionId: 's2', syntheticMessageId: 'u-b', message: messageB });
45
+
46
+ aliases.clearSession({ cwd: '/a', sessionId: 's1' });
47
+
48
+ expect(aliases.resolve({ cwd: '/a', sessionId: 's1', requestedId: 'u-a' })).toBe('u-a');
49
+ // The other scope is untouched and still resolves through its alias.
50
+ const managerB = createSessionManager('entry-b', messageB);
51
+ aliases.observeMessageEnd({ cwd: '/b', sessionId: 's2', syntheticMessageId: 'u-b', message: messageB, sessionManager: managerB });
52
+ expect(aliases.resolve({ cwd: '/b', sessionId: 's2', requestedId: 'u-b', sessionManager: managerB })).toBe('entry-b');
53
+ });
54
+
55
+ test(`idle scopes are pruned after ${ALIAS_SCOPE_IDLE_TTL_MS}ms once the retain threshold fires`, () => {
56
+ let clock = 0;
57
+ const now = () => clock;
58
+ const aliases = createMessageEntryAliases({ now });
59
+
60
+ aliases.retain({ cwd: '/old', sessionId: 'old', syntheticMessageId: 'u-old', message: { role: 'user' } });
61
+
62
+ clock += ALIAS_SCOPE_IDLE_TTL_MS + 1;
63
+ // Pruning is amortized into retain; crossing the threshold triggers one pass.
64
+ for (let i = 0; i < 64; i += 1) {
65
+ aliases.retain({ cwd: `/churn`, sessionId: `churn-${i}`, syntheticMessageId: `u-churn-${i}`, message: { role: 'user' } });
66
+ }
67
+
68
+ // The stale scope's alias is gone; resolve falls back to the raw id.
69
+ expect(aliases.resolve({ cwd: '/old', sessionId: 'old', requestedId: 'u-old' })).toBe('u-old');
70
+ });
71
+
72
+ test('recent scopes survive idle pruning', () => {
73
+ let clock = 0;
74
+ const now = () => clock;
75
+ const aliases = createMessageEntryAliases({ now });
76
+ const message = { role: 'user' };
77
+
78
+ clock += ALIAS_SCOPE_IDLE_TTL_MS + 1;
79
+ aliases.retain({ cwd: '/fresh', sessionId: 'fresh', syntheticMessageId: 'u-fresh', message });
80
+ for (let i = 0; i < 64; i += 1) {
81
+ aliases.retain({ cwd: `/churn`, sessionId: `churn-${i}`, syntheticMessageId: `u-churn-${i}`, message: { role: 'user' } });
82
+ }
83
+
84
+ const manager = createSessionManager('entry-fresh', message);
85
+ expect(aliases.resolve({ cwd: '/fresh', sessionId: 'fresh', requestedId: 'u-fresh', sessionManager: manager })).toBe('entry-fresh');
86
+ });
87
+
88
+ test(`scope count is capped at ${MAX_SCOPES}, evicting the oldest first`, () => {
89
+ let clock = 0;
90
+ const now = () => ++clock; // each retain stamps a fresher time
91
+ const aliases = createMessageEntryAliases({ now });
92
+
93
+ const overflow = 40;
94
+ for (let i = 0; i < MAX_SCOPES + overflow; i += 1) {
95
+ aliases.retain({ cwd: `/dir-${i}`, sessionId: `s-${i}`, syntheticMessageId: `u-${i}`, message: { role: 'user' } });
96
+ }
97
+
98
+ // Evicted (oldest) scopes fall back to raw ids without throwing…
99
+ for (let i = 0; i < overflow; i += 1) {
100
+ expect(aliases.resolve({ cwd: `/dir-${i}`, sessionId: `s-${i}`, requestedId: `u-${i}` })).toBe(`u-${i}`);
101
+ }
102
+ // …while the newest scope still holds its alias entry mapping.
103
+ const newestIndex = MAX_SCOPES + overflow - 1;
104
+ const newestMessage = { role: 'user', index: newestIndex };
105
+ aliases.retain({ cwd: `/dir-late`, sessionId: `s-late`, syntheticMessageId: `u-late`, message: newestMessage });
106
+ const manager = createSessionManager('entry-late', newestMessage);
107
+ aliases.observeMessageEnd({ cwd: '/dir-late', sessionId: 's-late', syntheticMessageId: 'u-late', message: newestMessage, sessionManager: manager });
108
+ expect(aliases.resolve({ cwd: '/dir-late', sessionId: 's-late', requestedId: 'u-late', sessionManager: manager })).toBe('entry-late');
109
+ });
110
+ });