@blackbelt-technology/pi-agent-dashboard 0.6.0 → 0.7.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 (105) hide show
  1. package/README.md +40 -38
  2. package/docs/architecture.md +148 -2
  3. package/package.json +6 -4
  4. package/packages/extension/package.json +4 -3
  5. package/packages/extension/src/AGENTS.md +1 -0
  6. package/packages/extension/src/__tests__/bridge-resume-disconnect.test.ts +333 -0
  7. package/packages/extension/src/__tests__/openspec-cli-shim.test.ts +145 -0
  8. package/packages/extension/src/__tests__/provider-register-native-models.test.ts +182 -0
  9. package/packages/extension/src/__tests__/provider-register-thinking-levels.test.ts +54 -1
  10. package/packages/extension/src/__tests__/single-derivation-guard.test.ts +39 -0
  11. package/packages/extension/src/bridge-context.ts +21 -0
  12. package/packages/extension/src/bridge.ts +41 -6
  13. package/packages/extension/src/openspec-cli-shim.ts +173 -0
  14. package/packages/extension/src/openspec-cli-shim.ts.AGENTS.md +7 -0
  15. package/packages/extension/src/provider-register.ts +180 -17
  16. package/packages/extension/src/provider-register.ts.AGENTS.md +1 -1
  17. package/packages/extension/src/session-sync.ts +9 -4
  18. package/packages/server/package.json +8 -8
  19. package/packages/server/src/__tests__/decorate-goals-spend.test.ts +79 -0
  20. package/packages/server/src/__tests__/embed-lifecycle-boot-smoke.test.ts +44 -0
  21. package/packages/server/src/__tests__/goal-routes.test.ts +62 -7
  22. package/packages/server/src/__tests__/goal-supervisor.test.ts +4 -4
  23. package/packages/server/src/__tests__/headless-pid-registry.test.ts +7 -3
  24. package/packages/server/src/__tests__/memory-event-store.test.ts +369 -13
  25. package/packages/server/src/__tests__/models-introspection-thinking-map.test.ts +67 -0
  26. package/packages/server/src/__tests__/pi-changelog-routes.test.ts +9 -2
  27. package/packages/server/src/__tests__/recovery-offer.test.ts +42 -7
  28. package/packages/server/src/__tests__/recovery-reattach-retraction.test.ts +188 -0
  29. package/packages/server/src/__tests__/session-tags-persistence.test.ts +29 -0
  30. package/packages/server/src/browser-handlers/AGENTS.md +1 -1
  31. package/packages/server/src/browser-handlers/__tests__/session-meta-handler.test.ts +98 -1
  32. package/packages/server/src/browser-handlers/handler-context.ts +24 -13
  33. package/packages/server/src/browser-handlers/session-action-handler.ts +12 -1
  34. package/packages/server/src/browser-handlers/session-meta-handler.ts +29 -0
  35. package/packages/server/src/embed-lifecycle/AGENTS.md +17 -0
  36. package/packages/server/src/embed-lifecycle/__tests__/caps.test.ts +129 -0
  37. package/packages/server/src/embed-lifecycle/__tests__/embed-lifecycle-controller.test.ts +84 -0
  38. package/packages/server/src/embed-lifecycle/__tests__/identity-key.test.ts +73 -0
  39. package/packages/server/src/embed-lifecycle/__tests__/idle-reaper.test.ts +173 -0
  40. package/packages/server/src/embed-lifecycle/__tests__/lifecycle-config.test.ts +26 -0
  41. package/packages/server/src/embed-lifecycle/__tests__/lifecycle-event-capture.test.ts +32 -0
  42. package/packages/server/src/embed-lifecycle/__tests__/lifecycle-marker-persistence.test.ts +106 -0
  43. package/packages/server/src/embed-lifecycle/__tests__/lifecycle-metrics.test.ts +39 -0
  44. package/packages/server/src/embed-lifecycle/__tests__/liveness-probe.test.ts +77 -0
  45. package/packages/server/src/embed-lifecycle/__tests__/quiescence.test.ts +175 -0
  46. package/packages/server/src/embed-lifecycle/__tests__/reclamation-soak.test.ts +77 -0
  47. package/packages/server/src/embed-lifecycle/__tests__/session-lifecycle-policy.test.ts +38 -0
  48. package/packages/server/src/embed-lifecycle/__tests__/visitor-session-registry.test.ts +140 -0
  49. package/packages/server/src/embed-lifecycle/caps.ts +88 -0
  50. package/packages/server/src/embed-lifecycle/cwd-allowlist.ts +50 -0
  51. package/packages/server/src/embed-lifecycle/embed-lifecycle-controller.ts +90 -0
  52. package/packages/server/src/embed-lifecycle/identity-key.ts +73 -0
  53. package/packages/server/src/embed-lifecycle/idle-reaper.ts +161 -0
  54. package/packages/server/src/embed-lifecycle/lifecycle-event-capture.ts +30 -0
  55. package/packages/server/src/embed-lifecycle/lifecycle-metrics.ts +70 -0
  56. package/packages/server/src/embed-lifecycle/liveness-probe.ts +123 -0
  57. package/packages/server/src/embed-lifecycle/quiescence.ts +159 -0
  58. package/packages/server/src/embed-lifecycle/session-lifecycle-policy.ts +31 -0
  59. package/packages/server/src/embed-lifecycle/visitor-session-registry.ts +178 -0
  60. package/packages/server/src/event-wiring.ts +20 -0
  61. package/packages/server/src/event-wiring.ts.AGENTS.md +1 -0
  62. package/packages/server/src/goal/AGENTS.md +1 -0
  63. package/packages/server/src/goal/decorate-goals-spend.ts +47 -0
  64. package/packages/server/src/goal/goal-supervisor.ts +5 -3
  65. package/packages/server/src/model-proxy/AGENTS.md +2 -2
  66. package/packages/server/src/model-proxy/__tests__/internal-registry-native-merge.test.ts +155 -0
  67. package/packages/server/src/model-proxy/__tests__/read-native-models.test.ts +92 -0
  68. package/packages/server/src/model-proxy/internal-registry.ts +49 -23
  69. package/packages/server/src/model-proxy/registry-singleton.ts +15 -9
  70. package/packages/server/src/pairing/browser-gateway.ts +40 -11
  71. package/packages/server/src/pairing/browser-gateway.ts.AGENTS.md +1 -1
  72. package/packages/server/src/persistence/memory-event-store.ts +369 -23
  73. package/packages/server/src/persistence/memory-event-store.ts.AGENTS.md +1 -1
  74. package/packages/server/src/routes/AGENTS.md +2 -2
  75. package/packages/server/src/routes/goal-routes.ts +14 -9
  76. package/packages/server/src/routes/models-introspection-routes.ts +10 -0
  77. package/packages/server/src/routes/system-routes.ts +16 -1
  78. package/packages/server/src/server.ts +216 -65
  79. package/packages/server/src/server.ts.AGENTS.md +1 -1
  80. package/packages/server/src/session/memory-session-manager.ts +4 -0
  81. package/packages/server/src/session/session-scanner.ts +9 -0
  82. package/packages/server/src/session/session-to-meta.ts +6 -0
  83. package/packages/server/src/spawn-process/headless-pid-registry.ts +14 -4
  84. package/packages/shared/package.json +1 -1
  85. package/packages/shared/src/AGENTS.md +5 -3
  86. package/packages/shared/src/__tests__/models-json-reader.test.ts +100 -0
  87. package/packages/shared/src/__tests__/nightly-workflow-contract.test.ts +125 -0
  88. package/packages/shared/src/__tests__/openspec-poller-1.6.0-compat.test.ts +112 -0
  89. package/packages/shared/src/__tests__/pnpm-migration-contract.test.ts +177 -0
  90. package/packages/shared/src/__tests__/publish-workflow-contract.test.ts +6 -3
  91. package/packages/shared/src/browser-protocol.ts +22 -0
  92. package/packages/shared/src/config.ts +70 -0
  93. package/packages/shared/src/dashboard-plugin/AGENTS.md +1 -1
  94. package/packages/shared/src/dashboard-plugin/slot-props.ts +9 -0
  95. package/packages/shared/src/dashboard-plugin/ui-primitives.ts +19 -0
  96. package/packages/shared/src/models-json-reader.ts +98 -0
  97. package/packages/shared/src/platform/AGENTS.md +1 -1
  98. package/packages/shared/src/platform/paths.ts +12 -0
  99. package/packages/shared/src/session-meta.ts +9 -0
  100. package/packages/shared/src/types.ts +52 -1
  101. package/docs/AGENTS.md +0 -47
  102. package/packages/extension/AGENTS.md +0 -7
  103. package/packages/server/AGENTS.md +0 -7
  104. package/packages/shared/AGENTS.md +0 -7
  105. package/scripts/AGENTS.md +0 -38
@@ -1,8 +1,12 @@
1
1
  import type { DashboardEvent } from "@blackbelt-technology/pi-dashboard-shared/types.js";
2
- import { describe, expect, it } from "vitest";
2
+ import { describe, expect, it, vi } from "vitest";
3
3
  import {
4
+ capString,
4
5
  createMemoryEventStore,
5
6
  exceedsSerializedSize,
7
+ measureBytes,
8
+ reduceSubagentEvent,
9
+ shrinkEntryToBudget,
6
10
  } from "../persistence/memory-event-store.js";
7
11
 
8
12
  function makeEvent(type: string = "test"): DashboardEvent {
@@ -185,7 +189,9 @@ describe("memory-event-store", () => {
185
189
  const stored = store.getEvent("s1", 1);
186
190
  const val = (stored as any).data.payload.data as string;
187
191
  expect(val.length).toBeLessThan(500);
188
- expect(val).toContain("truncated");
192
+ // capString is now head+tail: its generic marker names the hidden count.
193
+ // See change: head-tail-truncate-subagent-event-timeline (D2).
194
+ expect(val).toContain("hidden");
189
195
  });
190
196
 
191
197
  it("skill invocation envelope survives string truncation with closing tag intact", () => {
@@ -215,15 +221,15 @@ describe("memory-event-store", () => {
215
221
  expect(content.length).toBeLessThan(10_000);
216
222
  });
217
223
 
218
- it("user message with a large pasted image survives the per-event size ceiling", () => {
219
- // Regression: the per-event total-size ceiling (DEFAULT_MAX_EVENT_DATA_SIZE)
220
- // counted preserved base64 image bytes, so ANY user message with a pasted
221
- // image (> 20KB base64) was replaced by the {__truncated} placeholder and
222
- // vanished from chat. Image blocks are deliberately preserved by the
223
- // string pass; the size walk must not count their bytes either.
224
- // See change: bound-subagent-event-serialization (regression fix).
224
+ it("large pasted image over the ceiling is now byte-detected and placeholdered", () => {
225
+ // Behavior REVERSAL (intended): the size walk used to exempt base64 image
226
+ // `data` (counted 8 bytes), letting an image-bearing event escape the
227
+ // ceiling and then OOM the broadcast JSON.stringify. It now counts the
228
+ // image at its REAL byte size, so an over-ceiling image-bearing event
229
+ // correctly trips the ceiling and gets the {__truncated} placeholder.
230
+ // See change: head-tail-truncate-subagent-event-timeline (D8).
225
231
  const store = createMemoryEventStore(neverPinned); // production defaults
226
- const bigImage = "A".repeat(100_000); // realistic pasted screenshot
232
+ const bigImage = "A".repeat(100_000); // > 20KB ceiling
227
233
  const event: DashboardEvent = {
228
234
  eventType: "message_start",
229
235
  timestamp: Date.now(),
@@ -239,9 +245,9 @@ describe("memory-event-store", () => {
239
245
  };
240
246
  store.insertEvent("s1", event);
241
247
  const stored = store.getEvent("s1", 1) as any;
242
- expect(stored.data.__truncated).toBeUndefined();
243
- expect(stored.data.message.role).toBe("user");
244
- expect(stored.data.message.content[1].data).toBe(bigImage);
248
+ expect(stored.data.__truncated).toBe(true);
249
+ expect(stored.data.eventType).toBe("message_start");
250
+ expect(Buffer.byteLength(JSON.stringify(stored.data))).toBeLessThanOrEqual(20_000);
245
251
  });
246
252
 
247
253
  it("truncates other fields alongside preserved image data", () => {
@@ -575,4 +581,354 @@ describe("memory-event-store", () => {
575
581
  expect(store.getTrimStats().evictedSessions).toBe(2);
576
582
  });
577
583
  });
584
+
585
+ // See change: head-tail-truncate-subagent-event-timeline.
586
+ describe("subagent-timeline head+tail reduction", () => {
587
+ const CEIL = 20_000;
588
+
589
+ // Build a subagent `tool_execution_update` event: toolName Agent, entries at
590
+ // partialResult.details.entries, streaming content at partialResult.content.
591
+ function subagentEvent(opts: {
592
+ entries: unknown[];
593
+ prompt?: string;
594
+ description?: string;
595
+ contentText?: string;
596
+ contentImage?: string;
597
+ agentId?: string;
598
+ }): DashboardEvent {
599
+ return {
600
+ eventType: "tool_execution_update",
601
+ timestamp: Date.now(),
602
+ data: {
603
+ toolCallId: "tc1",
604
+ toolName: "Agent",
605
+ args: { prompt: opts.prompt ?? "do the task" },
606
+ partialResult: {
607
+ content: [
608
+ ...(opts.contentText != null ? [{ type: "text", text: opts.contentText }] : []),
609
+ ...(opts.contentImage != null
610
+ ? [{ type: "image", data: opts.contentImage, mimeType: "image/png" }]
611
+ : []),
612
+ ],
613
+ details: {
614
+ agentId: opts.agentId ?? "ag1",
615
+ description: opts.description ?? "explore",
616
+ entries: opts.entries,
617
+ },
618
+ },
619
+ },
620
+ };
621
+ }
622
+
623
+ function toolEntry(i: number, outputSize: number): unknown {
624
+ return {
625
+ kind: "tool",
626
+ toolName: "Read",
627
+ input: { file_path: `/src/file-${i}.ts` },
628
+ output: "X".repeat(outputSize),
629
+ ts: 1000 + i,
630
+ };
631
+ }
632
+
633
+ const bytesOf = (data: unknown) => Buffer.byteLength(JSON.stringify(data));
634
+
635
+ // --- capString (E1, E2, E3) ---
636
+ it("E1: capString keeps head + tail + a hidden marker", () => {
637
+ const s = "H".repeat(500) + "M".repeat(600) + "T".repeat(500); // len maxSize+...
638
+ const maxSize = 1000;
639
+ const long = "H".repeat(maxSize + 500);
640
+ const out = capString(long, maxSize);
641
+ expect(out).toContain(long.slice(0, 100)); // head present
642
+ expect(out).toContain(long.slice(long.length - 100)); // tail present
643
+ expect(out).toMatch(/hidden/);
644
+ expect(out.length).toBeLessThanOrEqual(maxSize + 40); // ~marker length
645
+ void s;
646
+ });
647
+
648
+ it("E2: capString is a no-op at or under the cap", () => {
649
+ const s = "A".repeat(1000);
650
+ expect(capString(s, 1000)).toBe(s);
651
+ expect(capString(s, 2000)).toBe(s);
652
+ });
653
+
654
+ it("E3: capString preserves a skill-invocation envelope", () => {
655
+ const body = "body ".repeat(5000);
656
+ const env = `<skill name="ci" location="/u/.pi/SKILL.md">\n${body}\n</skill>\n\nargs here`;
657
+ const out = capString(env, 1000);
658
+ expect(out).toMatch(/^<skill name="ci" location="[^"]+">\n/);
659
+ expect(out).toMatch(/\n<\/skill>\n\nargs here$/);
660
+ expect(out.length).toBeLessThan(env.length);
661
+ });
662
+
663
+ // --- reduction via insertEvent (E4..E9, E12..E15) ---
664
+ it("E4: keeps first + last entries + a text sentinel, not {__truncated}", () => {
665
+ const store = createMemoryEventStore(neverPinned);
666
+ const entries = Array.from({ length: 30 }, (_, i) => toolEntry(i, 1500));
667
+ store.insertEvent("s1", subagentEvent({ entries }));
668
+ const stored = store.getEvent("s1", 1) as any;
669
+ expect(stored.data.__truncated).toBeUndefined();
670
+ const kept = stored.data.partialResult.details.entries as any[];
671
+ expect(kept[0].input.file_path).toBe("/src/file-0.ts"); // head
672
+ const sentinel = kept.find((e) => e.kind === "text" && /steps hidden/.test(e.text));
673
+ expect(sentinel).toBeTruthy();
674
+ const last = kept[kept.length - 1];
675
+ expect(last.input.file_path).toBe("/src/file-29.ts"); // final entry retained
676
+ expect(bytesOf(stored.data)).toBeLessThanOrEqual(CEIL);
677
+ });
678
+
679
+ it("E5: a large prompt does not starve the timeline", () => {
680
+ const store = createMemoryEventStore(neverPinned);
681
+ const entries = Array.from({ length: 10 }, (_, i) => toolEntry(i, 1500));
682
+ store.insertEvent("s1", subagentEvent({ entries, prompt: "P".repeat(16_000) }));
683
+ const stored = store.getEvent("s1", 1) as any;
684
+ expect(stored.data.__truncated).toBeUndefined();
685
+ expect(stored.data.args.prompt.length).toBeLessThanOrEqual(2_000 + 40);
686
+ const kept = stored.data.partialResult.details.entries as any[];
687
+ expect(kept[0].input.file_path).toBe("/src/file-0.ts");
688
+ expect(kept[kept.length - 1].input.file_path).toBe("/src/file-9.ts");
689
+ expect(bytesOf(stored.data)).toBeLessThanOrEqual(CEIL);
690
+ });
691
+
692
+ it("E6: large content text does not starve the timeline", () => {
693
+ const store = createMemoryEventStore(neverPinned);
694
+ const entries = Array.from({ length: 10 }, (_, i) => toolEntry(i, 1500));
695
+ store.insertEvent("s1", subagentEvent({ entries, contentText: "C".repeat(16_000) }));
696
+ const stored = store.getEvent("s1", 1) as any;
697
+ expect(stored.data.__truncated).toBeUndefined();
698
+ expect(stored.data.partialResult.content[0].text.length).toBeLessThanOrEqual(1_500 + 40);
699
+ const kept = stored.data.partialResult.details.entries as any[];
700
+ expect(kept[kept.length - 1].input.file_path).toBe("/src/file-9.ts");
701
+ expect(bytesOf(stored.data)).toBeLessThanOrEqual(CEIL);
702
+ });
703
+
704
+ it("E7: byte-accurate bound holds under escape/CJK-heavy entries", () => {
705
+ const store = createMemoryEventStore(neverPinned);
706
+ // "\" and CJK expand under JSON/UTF-8: code-unit count < ceiling, bytes >>.
707
+ const nasty = '"\\\u4e2d\u6587'.repeat(3_000); // ~12k code units, far more bytes
708
+ const entries = Array.from({ length: 12 }, (_, i) => ({
709
+ kind: "tool",
710
+ toolName: "Read",
711
+ input: { q: nasty },
712
+ output: nasty,
713
+ ts: 1000 + i,
714
+ }));
715
+ store.insertEvent("s1", subagentEvent({ entries }));
716
+ const stored = store.getEvent("s1", 1) as any;
717
+ expect(Buffer.byteLength(JSON.stringify(stored.data))).toBeLessThanOrEqual(CEIL);
718
+ });
719
+
720
+ it("E8: shape-only match (no toolName/agentId) is NOT reduced", () => {
721
+ // Production config disables the per-field string pass (maxStringFieldSize
722
+ // = 0), so the ceiling is the bound. A shape-only array must NOT get the
723
+ // subagent head+tail reducer — it gets the blunt {__truncated} placeholder.
724
+ const store = createMemoryEventStore(neverPinned, 100, 20000, 0, 20000);
725
+ const event: DashboardEvent = {
726
+ eventType: "some_other_event",
727
+ timestamp: Date.now(),
728
+ data: {
729
+ details: { entries: Array.from({ length: 30 }, (_, i) => toolEntry(i, 1500)) },
730
+ },
731
+ };
732
+ store.insertEvent("s1", event);
733
+ const stored = store.getEvent("s1", 1) as any;
734
+ expect(stored.data.__truncated).toBe(true);
735
+ expect(Array.isArray(stored.data.details)).toBe(false);
736
+ });
737
+
738
+ it("E9: a >20-entry timeline is not clobbered to a string (maxStringFieldSize>0)", () => {
739
+ // maxStringFieldSize = 4000 (default) so the generic array clobber WOULD
740
+ // fire for a >20 array on the generic path.
741
+ const store = createMemoryEventStore(neverPinned);
742
+ const entries = Array.from({ length: 25 }, (_, i) => toolEntry(i, 1500));
743
+ store.insertEvent("s1", subagentEvent({ entries }));
744
+ const stored = store.getEvent("s1", 1) as any;
745
+ expect(Array.isArray(stored.data.partialResult.details.entries)).toBe(true);
746
+ expect(stored.data.partialResult.details.entries).not.toBe("[array truncated]");
747
+ });
748
+
749
+ it("E10: shrinkEntryToBudget bounds a many-leaf object entry (not leafCount×cap)", () => {
750
+ // leafCount×cap would be 10×2000 = 20000; the entry-level bound holds it
751
+ // far under B while the per-leaf floor (256) + markers set the achievable
752
+ // minimum for 11 leaves at ~2.9 KB, so B=4000 is a real entry-level bound.
753
+ const B = 4_000;
754
+ const input: Record<string, string> = {};
755
+ for (let i = 0; i < 10; i++) input[`leaf${i}`] = "L".repeat(2_000);
756
+ const entry = {
757
+ kind: "tool",
758
+ toolName: "Big",
759
+ input,
760
+ output: "O".repeat(5_000),
761
+ ts: 1,
762
+ };
763
+ shrinkEntryToBudget(entry, B);
764
+ expect(Buffer.byteLength(JSON.stringify(entry))).toBeLessThanOrEqual(B);
765
+ });
766
+
767
+ it("E11: image-bearing NON-subagent event is byte-detected → {__truncated}", () => {
768
+ const store = createMemoryEventStore(neverPinned);
769
+ const event: DashboardEvent = {
770
+ eventType: "message_start",
771
+ timestamp: Date.now(),
772
+ data: {
773
+ message: {
774
+ role: "user",
775
+ content: [{ type: "image", data: "A".repeat(2_000_000), mimeType: "image/png" }],
776
+ },
777
+ },
778
+ };
779
+ store.insertEvent("s1", event);
780
+ const stored = store.getEvent("s1", 1) as any;
781
+ expect(stored.data.__truncated).toBe(true);
782
+ expect(bytesOf(stored.data)).toBeLessThanOrEqual(CEIL);
783
+ });
784
+
785
+ it("E12: an under-ceiling subagent event is stored unchanged", () => {
786
+ const store = createMemoryEventStore(neverPinned);
787
+ const entries = Array.from({ length: 3 }, (_, i) => toolEntry(i, 500)); // ~small
788
+ const event = subagentEvent({ entries });
789
+ expect(exceedsSerializedSize(event.data, CEIL)).toBe(false);
790
+ store.insertEvent("s1", event);
791
+ const stored = store.getEvent("s1", 1) as any;
792
+ const kept = stored.data.partialResult.details.entries as any[];
793
+ expect(kept.length).toBe(3);
794
+ expect(kept.some((e) => e.kind === "text" && /hidden/.test(e.text))).toBe(false);
795
+ expect(stored.data.args.prompt).toBe("do the task");
796
+ });
797
+
798
+ it("E13: non-subagent over-ceiling event → {__truncated}", () => {
799
+ // Production config: string pass off (maxStringFieldSize = 0), so the
800
+ // 60 KB blob is bounded by the ceiling → placeholder (existing behavior).
801
+ const store = createMemoryEventStore(neverPinned, 100, 20000, 0, 20000);
802
+ const event: DashboardEvent = {
803
+ eventType: "subagent_end",
804
+ timestamp: Date.now(),
805
+ data: { blob: "Z".repeat(60_000) },
806
+ };
807
+ store.insertEvent("s1", event);
808
+ const stored = store.getEvent("s1", 1) as any;
809
+ expect(stored.data.__truncated).toBe(true);
810
+ expect(stored.data.reason).toBeTruthy();
811
+ expect(stored.data.eventType).toBe("subagent_end");
812
+ });
813
+
814
+ it("E14: pathological single huge final entry stays bounded", () => {
815
+ const store = createMemoryEventStore(neverPinned);
816
+ // Many entries so the middle elides; final entry alone is 40 KB.
817
+ const entries = Array.from({ length: 25 }, (_, i) => toolEntry(i, 1000));
818
+ entries[entries.length - 1] = toolEntry(24, 40_000);
819
+ store.insertEvent("s1", subagentEvent({ entries }));
820
+ const stored = store.getEvent("s1", 1) as any;
821
+ expect(bytesOf(stored.data)).toBeLessThanOrEqual(CEIL);
822
+ });
823
+
824
+ it("E15: reducer returns a NEW event and does not mutate the input", () => {
825
+ const entries = Array.from({ length: 30 }, (_, i) => toolEntry(i, 1500));
826
+ const event = subagentEvent({ entries, prompt: "P".repeat(16_000) });
827
+ const origPrompt = (event.data as any).args.prompt;
828
+ const origEntriesRef = (event.data as any).partialResult.details.entries;
829
+ const origLen = origEntriesRef.length;
830
+ const reduced = reduceSubagentEvent(event, CEIL);
831
+ expect(reduced).not.toBe(event);
832
+ expect((event.data as any).args.prompt).toBe(origPrompt); // unchanged
833
+ expect((event.data as any).partialResult.details.entries).toBe(origEntriesRef);
834
+ expect(origEntriesRef.length).toBe(origLen);
835
+ expect((origEntriesRef[0] as any).output.length).toBe(1500); // leaf untouched
836
+ });
837
+
838
+ // --- performance (P1, P2) ---
839
+ it("P1: size measurement is bounded and never full-stringifies oversized data", () => {
840
+ const spy = vi.spyOn(JSON, "stringify");
841
+ const store = createMemoryEventStore(neverPinned);
842
+ const event: DashboardEvent = {
843
+ eventType: "message_start",
844
+ timestamp: Date.now(),
845
+ data: { huge: "S".repeat(5_000_000) },
846
+ };
847
+ const start = performance.now();
848
+ store.insertEvent("s1", event);
849
+ const elapsed = performance.now() - start;
850
+ const stored = store.getEvent("s1", 1) as any;
851
+ expect(bytesOf(stored.data)).toBeLessThanOrEqual(CEIL);
852
+ // No stringify call was made on the 5MB string by the store.
853
+ for (const call of spy.mock.calls) {
854
+ const arg = call[0];
855
+ const asStr = typeof arg === "string" ? arg : "";
856
+ expect(asStr.length).toBeLessThan(1_000_000);
857
+ }
858
+ expect(elapsed).toBeLessThan(50);
859
+ spy.mockRestore();
860
+ });
861
+
862
+ it("P2: the shrink loop terminates on a pathological entry", () => {
863
+ const input: Record<string, unknown> = { big: "S".repeat(5_000_000) };
864
+ for (let i = 0; i < 500; i++) input[`n${i}`] = i;
865
+ const entries = [
866
+ toolEntry(0, 500),
867
+ { kind: "tool", toolName: "Big", input, output: "", ts: 2 },
868
+ ];
869
+ const event = subagentEvent({ entries });
870
+ const reduced = reduceSubagentEvent(event, CEIL);
871
+ expect(Buffer.byteLength(JSON.stringify(reduced.data))).toBeLessThanOrEqual(CEIL);
872
+ });
873
+
874
+ // --- error-handling (X1, X2) ---
875
+ it("X1: a 5MB base64 image in a subagent event does not OOM", () => {
876
+ const spy = vi.spyOn(JSON, "stringify");
877
+ const store = createMemoryEventStore(neverPinned);
878
+ const entries = Array.from({ length: 6 }, (_, i) => toolEntry(i, 800));
879
+ store.insertEvent(
880
+ "s1",
881
+ subagentEvent({ entries, contentImage: "A".repeat(5_000_000) }),
882
+ );
883
+ const stored = store.getEvent("s1", 1) as any;
884
+ expect(bytesOf(stored.data)).toBeLessThanOrEqual(CEIL);
885
+ for (const call of spy.mock.calls) {
886
+ const arg = call[0];
887
+ const asStr = typeof arg === "string" ? arg : "";
888
+ expect(asStr.length).toBeLessThan(1_000_000);
889
+ }
890
+ spy.mockRestore();
891
+ });
892
+
893
+ it("X2: an unreducible empty-entries subagent event falls back to {__truncated}", () => {
894
+ const store = createMemoryEventStore(neverPinned);
895
+ // Empty entries + an oversized envelope the caps cannot shrink below ceiling:
896
+ // a huge prompt beyond PROMPT_CAP still caps, so instead give a huge
897
+ // non-capped envelope field (extra) that stays over ceiling.
898
+ const event: DashboardEvent = {
899
+ eventType: "tool_execution_update",
900
+ timestamp: Date.now(),
901
+ data: {
902
+ toolName: "Agent",
903
+ extra: "Z".repeat(60_000), // not a capped field → envelope stays huge
904
+ partialResult: { details: { agentId: "ag1", entries: [] } },
905
+ },
906
+ };
907
+ store.insertEvent("s1", event);
908
+ const stored = store.getEvent("s1", 1) as any;
909
+ expect(stored.data.__truncated).toBe(true);
910
+ expect(bytesOf(stored.data)).toBeLessThanOrEqual(CEIL);
911
+ });
912
+
913
+ it("measureBytes never undercounts and stays bounded", () => {
914
+ // The walk is a SAFE overcount (one trailing-comma byte per element), never
915
+ // an undercount — the bound can never let an over-ceiling event through.
916
+ const actual = Buffer.byteLength(JSON.stringify({ a: "hi" }));
917
+ const m = measureBytes({ a: "hi" }, 1_000);
918
+ expect(m).toBeGreaterThanOrEqual(actual);
919
+ expect(m).toBeLessThanOrEqual(actual + 4);
920
+ // A 5 MB field short-circuits to the cap+1 over-ceiling sentinel.
921
+ expect(measureBytes({ big: "A".repeat(5_000_000) }, 1_000)).toBe(1_001);
922
+ // Lone surrogates escape to \uXXXX (6 bytes) — must never be undercounted.
923
+ for (const s of ["\ud800".repeat(50), "\udc00".repeat(50), `${"\ud800".repeat(50)}x`]) {
924
+ const m = measureBytes({ s }, 100_000);
925
+ expect(m).toBeGreaterThanOrEqual(Buffer.byteLength(JSON.stringify({ s })));
926
+ }
927
+ // A valid surrogate pair is still one 4-byte sequence, not two escapes.
928
+ const pair = { s: "\ud800\udc00".repeat(50) };
929
+ expect(measureBytes(pair, 100_000)).toBeGreaterThanOrEqual(
930
+ Buffer.byteLength(JSON.stringify(pair)),
931
+ );
932
+ });
933
+ });
578
934
  });
@@ -0,0 +1,67 @@
1
+ /**
2
+ * GET /api/models projects the RAW native `thinkingLevelMap`, derives NO
3
+ * server-side `supportedThinkingLevels`, and NEVER emits `compat` or any
4
+ * credential — default and ?annotated=1.
5
+ *
6
+ * See change: honor-native-models-json-metadata (test-plan S1, §5.3).
7
+ */
8
+ import Fastify from "fastify";
9
+ import { describe, expect, it } from "vitest";
10
+ import { registerModelsIntrospectionRoute } from "../routes/models-introspection-routes.js";
11
+
12
+ const MAP = { minimal: null, xhigh: "xhigh" };
13
+
14
+ // The registry model carries `compat` (for proxy routing); toRow must drop it.
15
+ const model = {
16
+ id: "glm-5.2",
17
+ provider: "newapi",
18
+ reasoning: true,
19
+ input: ["text", "image"],
20
+ contextWindow: 200000,
21
+ maxTokens: 65536,
22
+ thinkingLevelMap: MAP,
23
+ compat: { thinkingFormat: "deepseek", supportsReasoningEffort: true },
24
+ cost: { input: 3, output: 15 },
25
+ };
26
+
27
+ function makeRegistry() {
28
+ return {
29
+ getAvailable: async () => [model],
30
+ getAllAnnotated: () => [{ model, excludedReason: null as null }],
31
+ };
32
+ }
33
+
34
+ async function buildApp() {
35
+ const app = Fastify({ logger: false });
36
+ registerModelsIntrospectionRoute(app, { getRegistry: async () => makeRegistry() });
37
+ await app.ready();
38
+ return app;
39
+ }
40
+
41
+ describe("GET /api/models — thinkingLevelMap passthrough, no compat, no derivation", () => {
42
+ it("default variant emits raw thinkingLevelMap, no supportedThinkingLevels, no compat", async () => {
43
+ const app = await buildApp();
44
+ const res = await app.inject({ method: "GET", url: "/api/models" });
45
+ const row = JSON.parse(res.body).data[0];
46
+ expect(row.thinkingLevelMap).toEqual(MAP);
47
+ expect(row.supportedThinkingLevels).toBeUndefined();
48
+ expect(row.compat).toBeUndefined();
49
+ });
50
+
51
+ it("?annotated=1 variant also omits compat + derived levels", async () => {
52
+ const app = await buildApp();
53
+ const res = await app.inject({ method: "GET", url: "/api/models?annotated=1" });
54
+ const row = JSON.parse(res.body).data[0];
55
+ expect(row.thinkingLevelMap).toEqual(MAP);
56
+ expect(row.supportedThinkingLevels).toBeUndefined();
57
+ expect(row.compat).toBeUndefined();
58
+ });
59
+
60
+ it("neither variant leaks compat or credentials anywhere in the payload", async () => {
61
+ const app = await buildApp();
62
+ for (const url of ["/api/models", "/api/models?annotated=1"]) {
63
+ const res = await app.inject({ method: "GET", url });
64
+ expect(res.body).not.toMatch(/compat|thinkingFormat|deepseek|api_?key|bearer|secret|access_?token/i);
65
+ }
66
+ });
67
+ });
@@ -152,10 +152,17 @@ describe("pi-changelog-routes", () => {
152
152
  });
153
153
 
154
154
  it("returns 200 with empty releases when CHANGELOG missing", async () => {
155
- // Whitelisted package but nothing on disk.
155
+ // Real-looking scoped package that is NOT installed anywhere on disk.
156
+ // Must NOT be a transitive dependency: findChangelogPath Strategy 3 walks
157
+ // up node_modules from the module location, so any hoisted dep (e.g.
158
+ // @mariozechner/pi-coding-agent, pulled in transitively by the extension
159
+ // packages) would be found there — under pnpm's fully-hoisted linker every
160
+ // transitive dep lands at repo-root node_modules. Use a name that resolves
161
+ // nowhere so the empty-response path is layout-independent.
162
+ // See change: adopt-pnpm-for-dev-ci.
156
163
  const res = await app.inject({
157
164
  method: "GET",
158
- url: "/api/pi-core/changelog?pkg=@mariozechner/pi-coding-agent&from=0.68.0&to=0.70.0",
165
+ url: "/api/pi-core/changelog?pkg=@blackbelt-technology/pi-not-installed-fixture&from=0.68.0&to=0.70.0",
159
166
  });
160
167
  expect(res.statusCode).toBe(200);
161
168
  const body = res.json();
@@ -6,19 +6,18 @@
6
6
  * Plus the zero-candidate no-offer case.
7
7
  * See change: reopen-sessions-after-shutdown (task 5.1).
8
8
  */
9
- import { describe, it, expect, afterEach, beforeEach, vi } from "vitest";
10
- import { WebSocket } from "ws";
11
- import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync } from "node:fs";
12
- import path from "node:path";
13
- import os from "node:os";
14
9
 
15
- const wait = (ms: number) => new Promise((r) => setTimeout(r, ms));
10
+ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
11
+ import os from "node:os";
12
+ import path from "node:path";
13
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
14
+ import { WebSocket } from "ws";
16
15
 
17
16
  function seedCandidate(sessionsDir: string, id: string, live: boolean): void {
18
17
  const cwdDir = path.join(sessionsDir, "proj");
19
18
  mkdirSync(cwdDir, { recursive: true });
20
19
  const jsonl = path.join(cwdDir, `2026-06-30T10-00-00-000Z_${id}.jsonl`);
21
- writeFileSync(jsonl, JSON.stringify({ type: "session", id, cwd: cwdDir }) + "\n");
20
+ writeFileSync(jsonl, `${JSON.stringify({ type: "session", id, cwd: cwdDir })}\n`);
22
21
  writeFileSync(jsonl.replace(/\.jsonl$/, ".meta.json"), JSON.stringify({
23
22
  source: "cli", cwd: cwdDir, status: "streaming",
24
23
  startedAt: Date.now(), cachedAt: Date.now() + 60_000, live,
@@ -189,4 +188,40 @@ describe("cold-start recovery offer", () => {
189
188
  const msgs = await connectAndCollect(port);
190
189
  expect(msgs.filter((m) => m.type === "recovery_offer")).toHaveLength(0);
191
190
  });
191
+
192
+ // A reopen attempted while a candidate's liveness is still unresolved (grace
193
+ // window open) is REFUSED (no double-spawn) AND must NOT clear the held offer
194
+ // — the user can legitimately reopen once the window closes / on reconnect.
195
+ // See change: fix-recovery-offer-bridge-liveness-gate.
196
+ it("ask mode: resume during the grace window is refused and does NOT drop the offer", async () => {
197
+ writeConfig("ask");
198
+ const id = "a11ce111-2222-3333-4444-555555555555";
199
+ seedCandidate(sessionsDir, id, true);
200
+ const port = await boot();
201
+
202
+ // First client: receive the offer (carries a future graceUntil), then try
203
+ // to reopen immediately — inside the window.
204
+ const ws = new WebSocket(`ws://127.0.0.1:${port}/ws`);
205
+ const msgs: Record<string, unknown>[] = [];
206
+ await new Promise<void>((resolve) => {
207
+ ws.on("open", () => {
208
+ ws.on("message", (raw) => { try { msgs.push(JSON.parse(raw.toString())); } catch {} });
209
+ setTimeout(() => {
210
+ ws.send(JSON.stringify({ type: "resume_session", sessionId: id, mode: "continue" }));
211
+ setTimeout(resolve, 150);
212
+ }, 100);
213
+ });
214
+ });
215
+ ws.close();
216
+
217
+ const offer = msgs.find((m) => m.type === "recovery_offer");
218
+ expect(offer).toBeTruthy();
219
+ expect(typeof (offer as any).graceUntil).toBe("number");
220
+ // Reopen refused while liveness is unresolved (no pi spawned).
221
+ const result = msgs.find((m) => m.type === "resume_result") as any;
222
+ expect(result?.success).toBe(false);
223
+ // The held offer survived the refused reopen → a later client still sees it.
224
+ const second = await connectAndCollect(port);
225
+ expect(second.filter((m) => m.type === "recovery_offer")).toHaveLength(1);
226
+ }, 15_000);
192
227
  });