pi-mega-compact 0.11.1 → 0.11.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/dist/extensions/dashboard-server/api-contracts/endpoints.js +28 -1
  2. package/dist/extensions/dashboard-server/api-contracts/maintenance.js +7 -0
  3. package/dist/extensions/dashboard-server/api-contracts/provider-cache.js +7 -0
  4. package/dist/extensions/dashboard-server/api-contracts.test.js +3 -2
  5. package/dist/extensions/dashboard-server/index-reader.js +22 -0
  6. package/dist/extensions/dashboard-server/routes-cache.js +80 -0
  7. package/dist/extensions/dashboard-server/routes-cache.test.js +248 -0
  8. package/dist/extensions/dashboard-server/routes-maintenance.js +293 -0
  9. package/dist/extensions/dashboard-server/routes-repo.js +24 -0
  10. package/dist/extensions/dashboard-server/routes.js +2 -0
  11. package/dist/extensions/dashboard-server/server.js +5 -1
  12. package/dist/extensions/mega-cache-replay.test.js +233 -24
  13. package/dist/extensions/mega-compact-s38.test.js +201 -6
  14. package/dist/extensions/mega-config.js +3 -0
  15. package/dist/extensions/mega-events/agent-handlers.js +23 -7
  16. package/dist/extensions/mega-events/context-handler.js +37 -19
  17. package/dist/extensions/mega-events/error-classifier.js +27 -16
  18. package/dist/extensions/mega-runtime/runtime-snapshot.js +14 -4
  19. package/dist/extensions/mega-runtime/snapshot.js +1 -1
  20. package/dist/extensions/mega-runtime/snapshot.test.js +127 -0
  21. package/dist/extensions/mega-runtime/widget.js +4 -4
  22. package/dist/extensions/mega-runtime/widget.test.js +103 -12
  23. package/dist/src/pricing.js +78 -0
  24. package/dist/src/store/sqlite/maintenance.js +20 -1
  25. package/dist/src/store/sqlite/perf-samples.js +104 -0
  26. package/dist/src/store/sqlite/perf-samples.test.js +93 -1
  27. package/extensions/dashboard-client/dist/assets/{AchievementTiles-DZp_xQOW.js → AchievementTiles-vEo2MtE2.js} +2 -2
  28. package/extensions/dashboard-client/dist/assets/{AchievementTiles-DZp_xQOW.js.map → AchievementTiles-vEo2MtE2.js.map} +1 -1
  29. package/extensions/dashboard-client/dist/assets/AchievementsTab-DjxfYrDc.js +2 -0
  30. package/extensions/dashboard-client/dist/assets/{AchievementsTab-BzFHpAHM.js.map → AchievementsTab-DjxfYrDc.js.map} +1 -1
  31. package/extensions/dashboard-client/dist/assets/CacheTab-Dnpv94wq.js +2 -0
  32. package/extensions/dashboard-client/dist/assets/CacheTab-Dnpv94wq.js.map +1 -0
  33. package/extensions/dashboard-client/dist/assets/{ConfigTab-DQ4FG33J.js → ConfigTab-Cm6ymbmx.js} +2 -2
  34. package/extensions/dashboard-client/dist/assets/{ConfigTab-DQ4FG33J.js.map → ConfigTab-Cm6ymbmx.js.map} +1 -1
  35. package/extensions/dashboard-client/dist/assets/{EventsTab-D5HoEVYo.js → EventsTab-DXWl_YzI.js} +2 -2
  36. package/extensions/dashboard-client/dist/assets/{EventsTab-D5HoEVYo.js.map → EventsTab-DXWl_YzI.js.map} +1 -1
  37. package/extensions/dashboard-client/dist/assets/{GameTab-Jzsc4yeY.js → GameTab-BLDudcO5.js} +2 -2
  38. package/extensions/dashboard-client/dist/assets/{GameTab-Jzsc4yeY.js.map → GameTab-BLDudcO5.js.map} +1 -1
  39. package/extensions/dashboard-client/dist/assets/MaintenanceTab-DLkKCztn.js +2 -0
  40. package/extensions/dashboard-client/dist/assets/MaintenanceTab-DLkKCztn.js.map +1 -0
  41. package/extensions/dashboard-client/dist/assets/{MetricsTab-D_XnsEYX.js → MetricsTab-Cq4u-rZF.js} +2 -2
  42. package/extensions/dashboard-client/dist/assets/{MetricsTab-D_XnsEYX.js.map → MetricsTab-Cq4u-rZF.js.map} +1 -1
  43. package/extensions/dashboard-client/dist/assets/{OverviewTab-BMREvAth.js → OverviewTab-D4kGvsiQ.js} +2 -2
  44. package/extensions/dashboard-client/dist/assets/{OverviewTab-BMREvAth.js.map → OverviewTab-D4kGvsiQ.js.map} +1 -1
  45. package/extensions/dashboard-client/dist/assets/ReposTab-C0Wnrf2u.js +2 -0
  46. package/extensions/dashboard-client/dist/assets/ReposTab-C0Wnrf2u.js.map +1 -0
  47. package/extensions/dashboard-client/dist/assets/{SessionsTab-mz_vz8i2.js → SessionsTab-DZC2-GCn.js} +2 -2
  48. package/extensions/dashboard-client/dist/assets/{SessionsTab-mz_vz8i2.js.map → SessionsTab-DZC2-GCn.js.map} +1 -1
  49. package/extensions/dashboard-client/dist/assets/TimeSavedCard-UqljSyP-.js +2 -0
  50. package/extensions/dashboard-client/dist/assets/TimeSavedCard-UqljSyP-.js.map +1 -0
  51. package/extensions/dashboard-client/dist/assets/{TopicsTab-DKuct4oD.js → TopicsTab-01G71hv1.js} +2 -2
  52. package/extensions/dashboard-client/dist/assets/{TopicsTab-DKuct4oD.js.map → TopicsTab-01G71hv1.js.map} +1 -1
  53. package/extensions/dashboard-client/dist/assets/{TurnsTab-11MGLxY8.js → TurnsTab-DLRg0LZT.js} +2 -2
  54. package/extensions/dashboard-client/dist/assets/{TurnsTab-11MGLxY8.js.map → TurnsTab-DLRg0LZT.js.map} +1 -1
  55. package/extensions/dashboard-client/dist/assets/index-BEdKlpAB.css +1 -0
  56. package/extensions/dashboard-client/dist/assets/{index-CqLN7STl.js → index-BX0bcgLu.js} +10 -10
  57. package/extensions/dashboard-client/dist/assets/{index-CqLN7STl.js.map → index-BX0bcgLu.js.map} +1 -1
  58. package/extensions/dashboard-client/dist/assets/{useSSE-CXrQSbVY.js → useSSE-BBYt5UPB.js} +2 -2
  59. package/extensions/dashboard-client/dist/assets/{useSSE-CXrQSbVY.js.map → useSSE-BBYt5UPB.js.map} +1 -1
  60. package/extensions/dashboard-client/dist/index.html +2 -2
  61. package/extensions/dashboard-client/src/App.tsx +5 -1
  62. package/extensions/dashboard-client/src/api/client.ts +29 -0
  63. package/extensions/dashboard-client/src/components/ActiveReposTable.tsx +13 -1
  64. package/extensions/dashboard-client/src/components/ProviderCacheCard.tsx +141 -0
  65. package/extensions/dashboard-client/src/components/SavingsByModelTable.tsx +31 -3
  66. package/extensions/dashboard-client/src/main.tsx +1 -0
  67. package/extensions/dashboard-client/src/styles/maintenance.css +267 -0
  68. package/extensions/dashboard-client/src/styles/overview-extra.css +9 -0
  69. package/extensions/dashboard-client/src/tabs/CacheTab.tsx +83 -29
  70. package/extensions/dashboard-client/src/tabs/MaintenanceTab.tsx +458 -0
  71. package/extensions/dashboard-client/src/utils/format.ts +42 -7
  72. package/extensions/dashboard-server/api-contracts/endpoints.ts +54 -1
  73. package/extensions/dashboard-server/api-contracts/index.ts +16 -0
  74. package/extensions/dashboard-server/api-contracts/maintenance.ts +84 -0
  75. package/extensions/dashboard-server/api-contracts/multi-repo.ts +6 -0
  76. package/extensions/dashboard-server/api-contracts/provider-cache.ts +30 -0
  77. package/extensions/dashboard-server/api-contracts.test.ts +3 -2
  78. package/extensions/dashboard-server/api-contracts.ts +9 -0
  79. package/extensions/dashboard-server/index-reader.ts +23 -0
  80. package/extensions/dashboard-server/routes-cache.test.ts +302 -0
  81. package/extensions/dashboard-server/routes-cache.ts +123 -0
  82. package/extensions/dashboard-server/routes-maintenance.ts +352 -0
  83. package/extensions/dashboard-server/routes-repo.ts +31 -4
  84. package/extensions/dashboard-server/routes.ts +2 -0
  85. package/extensions/dashboard-server/server.ts +4 -0
  86. package/extensions/mega-cache-replay.test.ts +481 -166
  87. package/extensions/mega-compact-s38.test.ts +210 -6
  88. package/extensions/mega-config.ts +6 -0
  89. package/extensions/mega-events/agent-handlers.ts +24 -6
  90. package/extensions/mega-events/context-handler.ts +59 -24
  91. package/extensions/mega-events/error-classifier.ts +30 -13
  92. package/extensions/mega-runtime/runtime-snapshot.ts +31 -9
  93. package/extensions/mega-runtime/snapshot.test.ts +139 -0
  94. package/extensions/mega-runtime/snapshot.ts +6 -4
  95. package/extensions/mega-runtime/widget.test.ts +290 -105
  96. package/extensions/mega-runtime/widget.ts +29 -6
  97. package/package.json +1 -1
  98. package/src/pricing.ts +95 -0
  99. package/src/store/sqlite/maintenance.ts +20 -1
  100. package/src/store/sqlite/perf-samples.test.ts +107 -3
  101. package/src/store/sqlite/perf-samples.ts +142 -6
  102. package/extensions/dashboard-client/dist/assets/AchievementsTab-BzFHpAHM.js +0 -2
  103. package/extensions/dashboard-client/dist/assets/CacheTab-DEQbTq2T.js +0 -2
  104. package/extensions/dashboard-client/dist/assets/CacheTab-DEQbTq2T.js.map +0 -1
  105. package/extensions/dashboard-client/dist/assets/ReposTab-DuyhOktG.js +0 -2
  106. package/extensions/dashboard-client/dist/assets/ReposTab-DuyhOktG.js.map +0 -1
  107. package/extensions/dashboard-client/dist/assets/TimeSavedCard-B8AIjNTY.js +0 -2
  108. package/extensions/dashboard-client/dist/assets/TimeSavedCard-B8AIjNTY.js.map +0 -1
  109. package/extensions/dashboard-client/dist/assets/index-gn66lYD2.css +0 -1
@@ -624,9 +624,11 @@ test("R6(e): success resets retry-nudge-pending state", async () => {
624
624
 
625
625
  test("R3: repeated identical transient error text upgrades to poisoned-context at threshold", async () => {
626
626
  // The stateful repeat signal: 3 consecutive identical transient errors
627
- // (default threshold) upgrade to poisoned. Uses "5xx server error" (5xx
628
- // marker transient) so the classifier returns transient, then the repeat
629
- // tracker upgrades it. auto=false to skip the compact attempt.
627
+ // (default threshold) upgrade to poisoned. Uses "5xx server error"
628
+ // deliberately NO known-retryable marker ("5xx" is not /5\d\d/, and
629
+ // "server error" alone matches nothing): the classifier returns transient
630
+ // via the generic 'error' fallthrough, then the repeat tracker upgrades it.
631
+ // auto=false to skip the compact attempt.
630
632
  const prevAuto = process.env.MEGACOMPACT_AUTO;
631
633
  const prevBackoff = process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS;
632
634
  process.env.MEGACOMPACT_AUTO = "false";
@@ -652,6 +654,204 @@ test("R3: repeated identical transient error text upgrades to poisoned-context a
652
654
  }
653
655
  });
654
656
 
657
+ // ---- R7 regression tests: network/throughput errors must NEVER upgrade to ----
658
+ // ---- poisoned-context (2026-07-30 false-alarm incident) ----
659
+
660
+ /** R7 helper: fire the same transient error text `count` times with turn_start
661
+ * + elapsed backoff between turns so each turn's nudge can fire. */
662
+ async function r7RepeatTurns(h: ReturnType<typeof harness>, text: string, count: number) {
663
+ for (let i = 0; i < count; i++) {
664
+ await s38TurnEnd(h, "error", text);
665
+ await h.fire("turn_start", { type: "turn_start", turnIndex: i + 2 }, h.ctx());
666
+ await new Promise((r) => setTimeout(r, 3));
667
+ }
668
+ }
669
+
670
+ /** R7 helper: shared assertions for "stays transient" — no poisoned upgrade,
671
+ * no /clear advise, and the transient retry path actually ran. */
672
+ function assertStaysTransient(h: ReturnType<typeof harness>, label: string) {
673
+ assert.ok(
674
+ !eventTypes(h.stateDir).includes("poisoned_context"),
675
+ `${label}: no poisoned_context event (network errors never upgrade)`,
676
+ );
677
+ assert.ok(
678
+ !h.sendUserMessages.some((m) => m.includes("/clear")),
679
+ `${label}: no /clear advise message`,
680
+ );
681
+ assert.ok(
682
+ eventTypes(h.stateDir).includes("error_retry"),
683
+ `${label}: transient retry path ran (error_retry event)`,
684
+ );
685
+ }
686
+
687
+ test("R7(a): repeated 'timed out' phrasing (2026-07-30 incident text) stays transient — no poisoned upgrade", async () => {
688
+ // The incident error text was "Request timed out or failed. Try again" —
689
+ // "timed out" (two words) does NOT match the old guard's /timeout/, so the
690
+ // 3rd repeat fired the /clear poisoned advise. Must stay transient.
691
+ const prevAuto = process.env.MEGACOMPACT_AUTO;
692
+ const prevBackoff = process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS;
693
+ process.env.MEGACOMPACT_AUTO = "false";
694
+ process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS = "1";
695
+ try {
696
+ const h = harness();
697
+ await r7RepeatTurns(h, "Request timed out or failed. Try again", 3);
698
+ assertStaysTransient(h, "timed out x3");
699
+ } finally {
700
+ if (prevAuto === undefined) delete process.env.MEGACOMPACT_AUTO;
701
+ else process.env.MEGACOMPACT_AUTO = prevAuto;
702
+ if (prevBackoff === undefined) delete process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS;
703
+ else process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS = prevBackoff;
704
+ }
705
+ });
706
+
707
+ test("R7(b): repeated ETIMEDOUT errno stays transient", async () => {
708
+ // Node's timeout errno lowercases to "etimedout" — does NOT contain the
709
+ // substring "timeout". Slipped through the old guard.
710
+ const prevAuto = process.env.MEGACOMPACT_AUTO;
711
+ const prevBackoff = process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS;
712
+ process.env.MEGACOMPACT_AUTO = "false";
713
+ process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS = "1";
714
+ try {
715
+ const h = harness();
716
+ await r7RepeatTurns(h, "connect ETIMEDOUT 142.250.80.46:443", 3);
717
+ assertStaysTransient(h, "ETIMEDOUT x3");
718
+ } finally {
719
+ if (prevAuto === undefined) delete process.env.MEGACOMPACT_AUTO;
720
+ else process.env.MEGACOMPACT_AUTO = prevAuto;
721
+ if (prevBackoff === undefined) delete process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS;
722
+ else process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS = prevBackoff;
723
+ }
724
+ });
725
+
726
+ test("R7(c): repeated 'socket hang up' stays transient", async () => {
727
+ // Node surfaces ECONNRESET as the message "socket hang up" (the errno lives
728
+ // in error.code, which extractErrorSignature never sees).
729
+ const prevAuto = process.env.MEGACOMPACT_AUTO;
730
+ const prevBackoff = process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS;
731
+ process.env.MEGACOMPACT_AUTO = "false";
732
+ process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS = "1";
733
+ try {
734
+ const h = harness();
735
+ await r7RepeatTurns(h, "socket hang up", 3);
736
+ assertStaysTransient(h, "socket hang up x3");
737
+ } finally {
738
+ if (prevAuto === undefined) delete process.env.MEGACOMPACT_AUTO;
739
+ else process.env.MEGACOMPACT_AUTO = prevAuto;
740
+ if (prevBackoff === undefined) delete process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS;
741
+ else process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS = prevBackoff;
742
+ }
743
+ });
744
+
745
+ test("R7(d): repeated 429 rate-limit stays transient", async () => {
746
+ // /clear cannot fix a rate limit — the classifier explicitly keeps 429
747
+ // transient, so the repeat-upgrade must not override that verdict.
748
+ const prevAuto = process.env.MEGACOMPACT_AUTO;
749
+ const prevBackoff = process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS;
750
+ process.env.MEGACOMPACT_AUTO = "false";
751
+ process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS = "1";
752
+ try {
753
+ const h = harness();
754
+ await r7RepeatTurns(h, "429 Too Many Requests: rate limit exceeded", 3);
755
+ assertStaysTransient(h, "429 x3");
756
+ } finally {
757
+ if (prevAuto === undefined) delete process.env.MEGACOMPACT_AUTO;
758
+ else process.env.MEGACOMPACT_AUTO = prevAuto;
759
+ if (prevBackoff === undefined) delete process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS;
760
+ else process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS = prevBackoff;
761
+ }
762
+ });
763
+
764
+ test("R7(e): 0-token 'timed out' turn is NOT poisoned on first occurrence", async () => {
765
+ // Deeper gap: with usage PRESENT at 0 tokens, the classifier's 0-token
766
+ // poisoned signal fires on turn ONE for "timed out" phrasing (the stopReason
767
+ // 'error' is in the text blob and no transient marker matched). The network
768
+ // markers must be checked before that signal so this returns transient.
769
+ const prevAuto = process.env.MEGACOMPACT_AUTO;
770
+ process.env.MEGACOMPACT_AUTO = "false";
771
+ try {
772
+ const h = harness();
773
+ await s38TurnEndUsage(h, "error", "Request timed out or failed. Try again", 0);
774
+ assert.ok(
775
+ !eventTypes(h.stateDir).includes("poisoned_context"),
776
+ "0-token timed out: no poisoned_context on first turn",
777
+ );
778
+ assert.ok(
779
+ !h.sendUserMessages.some((m) => m.includes("/clear")),
780
+ "0-token timed out: no /clear advise on first turn",
781
+ );
782
+ } finally {
783
+ if (prevAuto === undefined) delete process.env.MEGACOMPACT_AUTO;
784
+ else process.env.MEGACOMPACT_AUTO = prevAuto;
785
+ }
786
+ });
787
+
788
+ test("R7(f): repeated non-network transient still upgrades to poisoned-context (control)", async () => {
789
+ // True-positive control: an error with NO known-retryable marker that
790
+ // repeats identically must still upgrade (the R3 feature itself).
791
+ const prevAuto = process.env.MEGACOMPACT_AUTO;
792
+ const prevBackoff = process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS;
793
+ process.env.MEGACOMPACT_AUTO = "false";
794
+ process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS = "1";
795
+ try {
796
+ const h = harness();
797
+ await r7RepeatTurns(h, "upstream rejected the request", 3);
798
+ assert.ok(
799
+ eventTypes(h.stateDir).includes("poisoned_context"),
800
+ "non-network repeat: poisoned_context event logged",
801
+ );
802
+ assert.ok(
803
+ h.sendUserMessages.some((m) => m.includes("/clear")),
804
+ "non-network repeat: /clear advise fired",
805
+ );
806
+ } finally {
807
+ if (prevAuto === undefined) delete process.env.MEGACOMPACT_AUTO;
808
+ else process.env.MEGACOMPACT_AUTO = prevAuto;
809
+ if (prevBackoff === undefined) delete process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS;
810
+ else process.env.MEGACOMPACT_ERROR_RETRY_BACKOFF_MS = prevBackoff;
811
+ }
812
+ });
813
+
814
+ test("R7(g): 'Request failed — please retry.' 0-token stays poisoned-context (2026-07-28 control)", async () => {
815
+ // The deterministic-rejection incident that motivated R3 must remain
816
+ // poisoned: the shared marker pattern must NOT match this text.
817
+ const prevAuto = process.env.MEGACOMPACT_AUTO;
818
+ process.env.MEGACOMPACT_AUTO = "false";
819
+ try {
820
+ const h = harness();
821
+ await s38TurnEndUsage(h, "error", "Request failed — please retry.", 0);
822
+ assert.ok(
823
+ eventTypes(h.stateDir).includes("poisoned_context"),
824
+ "deterministic rejection: poisoned_context event logged",
825
+ );
826
+ assert.ok(h.sendUserMessages.some((m) => m.includes("/clear")), "deterministic rejection: /clear advise fired");
827
+ } finally {
828
+ if (prevAuto === undefined) delete process.env.MEGACOMPACT_AUTO;
829
+ else process.env.MEGACOMPACT_AUTO = prevAuto;
830
+ }
831
+ });
832
+
833
+ test("R7 classifier: 0-token 'timed out' error → transient (not poisoned)", () => {
834
+ // Unit-level pin of the R7(e) gap.
835
+ assert.equal(
836
+ classifyErrorFn({
837
+ stopReason: "error",
838
+ content: "Request timed out or failed. Try again",
839
+ usage: { inputTokens: 0, outputTokens: 0 },
840
+ }),
841
+ "transient",
842
+ );
843
+ });
844
+
845
+ test("R7 classifier: bare network phrasings → transient", () => {
846
+ assert.equal(classifyErrorFn("socket hang up"), "transient");
847
+ assert.equal(classifyErrorFn("the operation timed out"), "transient");
848
+ assert.equal(classifyErrorFn("connect ETIMEDOUT 10.0.0.1:443"), "transient");
849
+ });
850
+
851
+ test("R7 classifier: 429/rate-limit → transient (control)", () => {
852
+ assert.equal(classifyErrorFn("429 Too Many Requests: rate limit exceeded"), "transient");
853
+ });
854
+
655
855
  test("cleanup", async () => {
656
856
  // PGlite WASM close can hang; race with a timeout to prevent 40-min hangs.
657
857
  try {
@@ -661,8 +861,12 @@ test("cleanup", async () => {
661
861
  // Force-exit: each harness() creates a MegaRuntime with an fs.watch
662
862
  // game-state watcher that is never disposed (no session_shutdown in tests).
663
863
  // Those handles keep the event loop alive indefinitely after all tests
664
- // complete, so `node --test` (without --test-force-exit) would hang. The
665
- // streaming reporter has already printed every test result by this point;
666
- // process.exit(0) just forces the exit the watchers are preventing.
864
+ // complete, so `node --test` (without --test-force-exit) would hang.
865
+ // Drain stdout/stderr, then defer the exit: a bare process.exit() discards
866
+ // unflushed pipe buffers observed 2026-07-30: when piped, the trailing
867
+ // tests' results and the run summary silently vanished from the report.
868
+ await new Promise((r) => process.stdout.write("", r));
869
+ await new Promise((r) => process.stderr.write("", r));
870
+ await new Promise((r) => setTimeout(r, 1500));
667
871
  process.exit(0);
668
872
  });
@@ -63,6 +63,9 @@ export interface MegaConfig {
63
63
  /** High-pressure floor for preserveRecent — when context is near the limit
64
64
  * we compact deeper, but never below this (keeps recent turns for coherence). */
65
65
  preserveRecentMin: number;
66
+ /** D.1: minimum context-growth percentage delta before re-compacting instead of
67
+ * replaying the cached trim (Default 50). Set via MEGACOMPACT_RECOMPACT_PCT_DELTA.*/
68
+ recompactPctDelta: number;
66
69
  auto: boolean;
67
70
  autoInline: boolean;
68
71
  autoInlineK: number;
@@ -312,6 +315,9 @@ export function loadConfig(): MegaConfig {
312
315
  recallMaxTokens: envFlag("MEGACOMPACT_RECALL_MAX_TOKENS", 1500),
313
316
  windowDedupe: envBool("MEGACOMPACT_WINDOW_DEDUPE", true),
314
317
  tuiWidget: envBool("MEGACOMPACT_TUI_WIDGET", true),
318
+ // D.1: env-overridable recompact delta (minimum context growth % before
319
+ // re-compacting instead of replaying the cached live trim). Default 50.
320
+ recompactPctDelta: envFlag("MEGACOMPACT_RECOMPACT_PCT_DELTA", 50),
315
321
  debug: envBool("MEGACOMPACT_DEBUG", false),
316
322
  };
317
323
  }
@@ -8,7 +8,7 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
8
8
  import type { MegaRuntime } from "../mega-runtime.js";
9
9
  import { piCompactWouldNoop, runMemoryReview } from "../mega-pipeline.js";
10
10
  import { memoryReviewCadence, type MegaConfig } from "../mega-config.js";
11
- import { recordScore } from "../../src/store/sqlite.js";
11
+ import { recordScore, readLatestCacheHitPct } from "../../src/store/sqlite.js";
12
12
  import { evaluateAndUnlockAchievements } from "../../src/store/sqlite/game-achievements.js";
13
13
  import {
14
14
  ensureConversationIdFor,
@@ -20,6 +20,7 @@ import {
20
20
  classifyError,
21
21
  errorRetryBackoffMs,
22
22
  extractErrorSignature,
23
+ isKnownRetryableTransient,
23
24
  } from "./error-classifier.js";
24
25
  import { safeSendUserMessage } from "./send-safe.js";
25
26
  import { vectorStats } from "../../src/vectorStore.js";
@@ -301,7 +302,10 @@ export function registerAgentHandlers(
301
302
  if (runtime.getCachedGameState().game_mode_on) {
302
303
  const repo = resolveRepoRoot(ctx.cwd) ?? runtime.currentStateDir;
303
304
  const st = vectorStats(runtime.store, runtime.rt.sessionId);
304
- const cachePct = st.dedupHitRate * 100;
305
+ // C.3: prefer provider cache hit rate, fall back to dedup hit rate
306
+ const providerPct = readLatestCacheHitPct(runtime.currentStateDir);
307
+ const cachePct =
308
+ providerPct != null ? providerPct : st.dedupHitRate * 100;
305
309
  const modelId = runtime.currentModel?.modelId ?? "unknown";
306
310
  recordScore(runtime.currentStateDir, {
307
311
  repo_root: repo,
@@ -394,9 +398,11 @@ export function registerAgentHandlers(
394
398
  // upgrade happens here. A 'transient' (or 'poisoned-context') turn
395
399
  // whose normalized error signature matches the previous one bumps
396
400
  // errorTextRepeatCount; once it crosses the threshold, the category
397
- // is upgraded to 'poisoned-context' (the request is deterministic).
398
- // Conservative: only upgrade, never downgrade, and only for transient
399
- // (a 'permanent' auth error repeating is still permanent).
401
+ // is upgraded to 'poisoned-context' (the request is deterministic)
402
+ // R7: unless the signature carries a known-retryable network/
403
+ // throughput marker (guard below). Conservative: only upgrade, never
404
+ // downgrade, and only for transient (a 'permanent' auth error
405
+ // repeating is still permanent).
400
406
  let effectiveCategory = category;
401
407
  const errSig = extractErrorSignature(event.message);
402
408
  if (category === "transient" || category === "poisoned-context") {
@@ -412,7 +418,19 @@ export function registerAgentHandlers(
412
418
  config.poisonedContextRepeatThreshold &&
413
419
  category === "transient"
414
420
  ) {
415
- effectiveCategory = "poisoned-context";
421
+ // R3/R7: upgrade only when the repeating error carries NO
422
+ // known-retryable marker. Network/throughput failures (timeout,
423
+ // ECONNRESET, 5xx, 429, connection lost, …) that repeat are
424
+ // still retryable — the API is just flaky, and /clear cannot fix
425
+ // them (2026-07-30 false-alarm incident). Only upgrade
426
+ // transient → poisoned-context for errors that repeat identically
427
+ // with no known-retryable cause, like the 2026-07-28 incident
428
+ // where the provider returned "Request failed — please retry."
429
+ // deterministically. The marker set is shared with classifyError
430
+ // (error-classifier.ts) so the two never drift.
431
+ if (!isKnownRetryableTransient(errSig)) {
432
+ effectiveCategory = "poisoned-context";
433
+ }
416
434
  }
417
435
  }
418
436
  } else {
@@ -174,7 +174,12 @@ export function registerContextHandler(
174
174
  const db = openStore(runtime.currentStateDir);
175
175
  const epochId = epochIdFor(runtime.rt.sessionId);
176
176
  for (const msg of messages) {
177
- const raw = toRawTranscriptRow(msg, runtime.rt.sessionId, epochId, runtime.currentTurn);
177
+ const raw = toRawTranscriptRow(
178
+ msg,
179
+ runtime.rt.sessionId,
180
+ epochId,
181
+ runtime.currentTurn,
182
+ );
178
183
  if (raw) appendRawTranscript(db, raw);
179
184
  }
180
185
  } catch (e) {
@@ -214,26 +219,19 @@ export function registerContextHandler(
214
219
  return;
215
220
  }
216
221
 
217
- // Debounce so we don't fire on every context event past threshold.
218
- const now = Date.now();
219
- if (now < runtime.debounceUntil) {
220
- runtime.diagCtxDebounce++;
221
- return;
222
- }
223
- runtime.debounceUntil = now + 2000;
224
-
222
+ // D.2: Replay MUST be exempt from debounce replay is free (no compute,
223
+ // no re-write) and prevents unnecessary KV-cache invalidation. Check
224
+ // replay FIRST, before debounce, so two context events <2s apart both
225
+ // return the cached sentinel verbatim (re-stabilises the provider prefix).
226
+ //
225
227
  // v0.8.6 cache-stability: replay the cached trim view when still in the
226
228
  // same compaction epoch AND context hasn't grown enough to warrant a
227
- // re-compact. This stabilizes the provider KV-cache prefix (the summary +
228
- // cut are reused verbatim) instead of regenerating a fresh summary +
229
- // sentinel every fire, which invalidated the prefix on every other turn
230
- // (the alternating cache-miss regression). Re-compact only when context
231
- // grew >=10% of the window (percent basis) or >=50% of the effective
232
- // threshold (token basis, when percent is unavailable). The cached `cut`
233
- // is only valid while the transcript grows within the epoch — it is
234
- // cleared on session_compact (durable truncation) + resetRuntime, so we
235
- // never replay a stale cut into a truncated transcript (PREVENT-PI-001/002).
236
- const RECOMPACT_PCT_DELTA = 10;
229
+ // re-compact. Re-compact only when context grew >=config.recompactPctDelta%
230
+ // of the window (percent basis) or >=50% of the effective threshold
231
+ // (token basis, when percent is unavailable). The cached `cut` is only
232
+ // valid while the transcript grows within the epoch it is cleared on
233
+ // session_compact (durable truncation) + resetRuntime, so we never replay
234
+ // a stale cut into a truncated transcript (PREVENT-PI-001/002).
237
235
  if (
238
236
  runtime.trimCache &&
239
237
  runtime.trimCache.checkpointId === runtime.rt.lastCheckpointId &&
@@ -241,7 +239,7 @@ export function registerContextHandler(
241
239
  ) {
242
240
  const grewEnough =
243
241
  pct != null && runtime.trimCache.ctxPct != null
244
- ? pct - runtime.trimCache.ctxPct >= RECOMPACT_PCT_DELTA
242
+ ? pct - runtime.trimCache.ctxPct >= config.recompactPctDelta
245
243
  : currentTokens - (runtime.trimCache.ctxTokens ?? 0) >=
246
244
  runtime.effectiveThreshold * 0.5;
247
245
  if (!grewEnough) {
@@ -258,6 +256,15 @@ export function registerContextHandler(
258
256
  // else: context grew enough → fall through to re-compact (cache is stale)
259
257
  }
260
258
 
259
+ // Debounce so we don't fire on every context event past threshold.
260
+ // (Replay already returned above — only fresh compacts reach this point.)
261
+ const now = Date.now();
262
+ if (now < runtime.debounceUntil) {
263
+ runtime.diagCtxDebounce++;
264
+ return;
265
+ }
266
+ runtime.debounceUntil = now + 2000;
267
+
261
268
  // Adaptive compression (Fix E): scale compression strength + keepFrom depth
262
269
  // with how close we are to the model context limit. Null-safe: when the
263
270
  // token-fallback path ran (pct unavailable) use the token-basis pressure
@@ -269,8 +276,24 @@ export function registerContextHandler(
269
276
  const ran = runCompact(pi, runtime, config, ctx, messages, {
270
277
  compressionPressure: pressure,
271
278
  });
279
+ // D.3: skip paths fall back to replay instead of returning empty.
280
+ // If runCompact skipped and we have a valid trimCache, replay it
281
+ // (free stability win) — otherwise defer to the next event.
272
282
  if (ran.skipped) {
273
283
  runtime.diagCtxRunSkipped++;
284
+ if (
285
+ runtime.trimCache &&
286
+ runtime.trimCache.checkpointId === runtime.rt.lastCheckpointId &&
287
+ runtime.trimCache.cut <= messages.length
288
+ ) {
289
+ const recent = messages.slice(runtime.trimCache.cut); // guardrails-allow PREVENT-PI-002
290
+ runtime.diagLiveTrimFires++;
291
+ runtime.diagLiveTrimReplays++;
292
+ runtime.snapshot(ctx);
293
+ return {
294
+ messages: [{ ...runtime.trimCache.summaryAgentMsg }, ...recent],
295
+ };
296
+ }
274
297
  return;
275
298
  }
276
299
 
@@ -295,7 +318,12 @@ export function registerContextHandler(
295
318
  // them (compression-by-conversation-epoch metrics). Isolated-store
296
319
  // only; best-effort + non-fatal.
297
320
  try {
298
- stampTurnsEpochFor(config, runtime.rt.sessionId, epoch.epochId, runtime.currentStateDir);
321
+ stampTurnsEpochFor(
322
+ config,
323
+ runtime.rt.sessionId,
324
+ epoch.epochId,
325
+ runtime.currentStateDir,
326
+ );
299
327
  } catch {
300
328
  /* non-fatal: epoch stamping never breaks compaction */
301
329
  }
@@ -304,7 +332,10 @@ export function registerContextHandler(
304
332
  // AUTO_WIKI_ENABLED; best-effort + non-fatal (never breaks compaction).
305
333
  try {
306
334
  if (config.autoWikiEnabled && config.turnsDbEnabled) {
307
- const every = Math.max(1, TurnsConfig.WIKI_REBUILD_EVERY_N_COMPACTS);
335
+ const every = Math.max(
336
+ 1,
337
+ TurnsConfig.WIKI_REBUILD_EVERY_N_COMPACTS,
338
+ );
308
339
  const tdb = openTurnStore(runtime.currentStateDir);
309
340
  const n = bumpWikiCompactCounter(tdb);
310
341
  if (n % every === 0) {
@@ -314,7 +345,9 @@ export function registerContextHandler(
314
345
  restarts: 5,
315
346
  seed: 0x9e3779b9,
316
347
  });
317
- createTopicStore(runtime.currentStateDir).replaceTopicModel(model);
348
+ createTopicStore(runtime.currentStateDir).replaceTopicModel(
349
+ model,
350
+ );
318
351
  runtime.logger.info("wiki_rebuild", {
319
352
  clusterCount: model.k,
320
353
  totalChunks: model.totalChunks,
@@ -326,7 +359,9 @@ export function registerContextHandler(
326
359
  }
327
360
  }
328
361
  } catch (wikiErr) {
329
- runtime.logger.warn("wiki_rebuild_failed", { error: String(wikiErr) });
362
+ runtime.logger.warn("wiki_rebuild_failed", {
363
+ error: String(wikiErr),
364
+ });
330
365
  }
331
366
  // S27 Task 6: Fire-and-forget dedup pipeline.
332
367
  // Deduplicates raw_transcript rows for the compacted range.
@@ -12,6 +12,28 @@
12
12
  * poisoned, choose transient (bounded by R1 dedup + R2 session cap).
13
13
  */
14
14
 
15
+ /** R7: known-retryable transient markers — network/throughput failures that
16
+ * retry can fix and /clear cannot. SINGLE SOURCE OF TRUTH: classifyError uses
17
+ * this for its transient-marker stage, and the agent-handlers R3 repeat
18
+ * upgrade guard uses it to keep these errors out of poisoned-context. Add new
19
+ * transient phrasings HERE only.
20
+ *
21
+ * Non-obvious alternatives:
22
+ * - `time(?:d[\s-]?out|out)` covers "timeout", "timed out", "timed-out" —
23
+ * "timed out" does NOT match /timeout/ (the 2026-07-30 incident phrasing).
24
+ * - `etimedout` is Node's timeout errno lowercased — does NOT contain the
25
+ * substring "timeout".
26
+ * - `socket hang up` is Node's ECONNRESET *message*; the errno lives in
27
+ * error.code, which extractErrorSignature never sees. */
28
+ export const KNOWN_RETRYABLE_TRANSIENT_PATTERN =
29
+ /max(imum)? output token|rate[\s.-]?limit|429|too many requests|overloaded|5\d\d|internal server|bad gateway|service unavailable|network|time(?:d[\s-]?out|out)|etimedout|econnreset|econnrefused|epipe|eai_again|socket hang up|premature close|other side closed|connection (lost|refused|reset|aborted?)|stream (interrupted|closed|ended|failed)|disconnected/;
30
+
31
+ /** R7: true when the error text carries a known-retryable transient marker.
32
+ * Defensively lowercases so callers can pass raw or normalized text. */
33
+ export function isKnownRetryableTransient(text: string): boolean {
34
+ return KNOWN_RETRYABLE_TRANSIENT_PATTERN.test(text.toLowerCase());
35
+ }
36
+
15
37
  /** S38.2: classify a turn-end error/stop signal into a retry category.
16
38
  *
17
39
  * `length` is returned as null — S28 owns the max-output-token length stopReason
@@ -134,19 +156,14 @@ export function classifyError(message: unknown):
134
156
  if (/too long|context window|maximum context length|context length exceeded|requires at least \d+ tokens|even after compaction|reduce the conversation|reduce your input/.test(s)) {
135
157
  return 'context-overflow';
136
158
  }
137
- // --- transient (specific markers FIRST — these override poisoned signals) ---
138
- // R3: network failures (timeout, ECONNRESET, 5xx, 429) MUST stay transient
139
- // even when usage is 0 tokens, because they are retryable. The specific
140
- // markers below return before any poisoned signal is evaluated.
141
- if (/max(imum)? output token/.test(s)) return 'transient';
142
- if (/rate[\s.-]?limit|429|too many requests/.test(s)) return 'transient';
143
- if (/5\d\d|internal server|bad gateway|service unavailable/.test(s)) return 'transient';
144
- // 'connection aborted' is a network failure (ECONNABORTED), NOT a user ESC
145
- // (which is stopReason 'aborted', handled by the early-return above). Added
146
- // so "Connection aborted by peer" stays transient under R3. ECONNRESET and
147
- // common errno names are included so a bare 0-token 'ECONNRESET' turn is not
148
- // misclassified as poisoned (R6: ECONNRESET → transient).
149
- if (/network|timeout|econnreset|econnrefused|epipe|connection (lost|refused|reset|aborted)|stream (interrupted|closed|ended|failed)|disconnected/.test(s)) return 'transient';
159
+ // --- transient (known-retryable markers FIRST — these override poisoned signals) ---
160
+ // R3: network/throughput failures (timeout, ECONNRESET, 5xx, 429) MUST stay
161
+ // transient even when usage is 0 tokens, because they are retryable and
162
+ // /clear cannot fix them. 'connection aborted' is a network failure
163
+ // (ECONNABORTED), NOT a user ESC (stopReason 'aborted', early-return above).
164
+ // The marker set is shared with the agent-handlers R3 repeat-upgrade guard
165
+ // (isKnownRetryableTransient) so the two never drift.
166
+ if (isKnownRetryableTransient(s)) return 'transient';
150
167
  // --- poisoned-context (R3: ORDER AFTER specific transient markers, BEFORE
151
168
  // the generic 'error' transient fallthrough) ---
152
169
  // A DETERMINISTIC request-rejection that retrying cannot fix. Re-submitting
@@ -20,20 +20,25 @@
20
20
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
21
21
  import { join } from "node:path";
22
22
  import {
23
- VectorStore,
23
+ type VectorStore,
24
24
  vectorStats,
25
25
  vectorRepoStats,
26
26
  vectorDataInvariant,
27
27
  } from "../../src/vectorStore.js";
28
28
  import {
29
29
  latestModelSnapshot,
30
+ readLatestCacheHitPct,
30
31
  recordPerfSample,
31
32
  recordSessionHeartbeat,
32
33
  appendTokenSample,
33
34
  type GameState,
34
35
  } from "../../src/store/sqlite.js";
35
- import { resolveRepoRoot, type MegaConfig, type PressureBand } from "../mega-config.js";
36
- import { Dashboard } from "../mega-dashboard.js";
36
+ import {
37
+ resolveRepoRoot,
38
+ type MegaConfig,
39
+ type PressureBand,
40
+ } from "../mega-config.js";
41
+ import type { Dashboard } from "../mega-dashboard.js";
37
42
  import type { WidgetData } from "./widget.js";
38
43
  import { computeMegaSnapshot } from "./snapshot.js";
39
44
  import { buildDashboardSnapshot } from "./dashboard-snapshot.js";
@@ -93,7 +98,10 @@ export interface RuntimeSnapshotContext extends RuntimeHelpersContext {
93
98
  /** Collect live state and write it to disk (+ paint the above-editor widget).
94
99
  * Extracted verbatim from `MegaRuntime.snapshot()` (runtime.ts); the public
95
100
  * method there is now `snapshotImpl(this, ctx)`. */
96
- export function snapshotImpl(self: RuntimeSnapshotContext, ctx?: ExtensionContext): void {
101
+ export function snapshotImpl(
102
+ self: RuntimeSnapshotContext,
103
+ ctx?: ExtensionContext,
104
+ ): void {
97
105
  if (ctx) self.lastWidgetCtx = ctx;
98
106
  if (ctx) self.bindRepo(ctx.cwd);
99
107
  // v0.8.5: gate the expensive body (6 sync SQLite opens +
@@ -179,7 +187,8 @@ export function snapshotImpl(self: RuntimeSnapshotContext, ctx?: ExtensionContex
179
187
  // try/catch mirrors the recordPerfSample pattern below. Skip the token
180
188
  // sample when lastCtxTokens is null (no context data yet).
181
189
  try {
182
- const repo = resolveRepoRoot(ctx?.cwd ?? self.currentStateDir) ?? self.currentStateDir;
190
+ const repo =
191
+ resolveRepoRoot(ctx?.cwd ?? self.currentStateDir) ?? self.currentStateDir;
183
192
  recordSessionHeartbeat(
184
193
  process.pid,
185
194
  self.rt.sessionId,
@@ -194,7 +203,7 @@ export function snapshotImpl(self: RuntimeSnapshotContext, ctx?: ExtensionContex
194
203
  self.lastCtxTokens,
195
204
  self.lastCtxPercent ?? 0,
196
205
  self.lastCtxWindow || 0,
197
- join(self.currentStateDir, "events.log"),
206
+ join(self.currentStateDir, "events.log"),
198
207
  );
199
208
  }
200
209
  } catch {
@@ -217,6 +226,15 @@ export function snapshotImpl(self: RuntimeSnapshotContext, ctx?: ExtensionContex
217
226
  }
218
227
  // ── gather widget data (computed per snapshot, rendered per frame) ────
219
228
  const modelSnap = latestModelSnapshot(self.currentStateDir);
229
+ // Provider prompt cache hit % for the widget (B/C): latest
230
+ // cache_hit_pct sample. Non-fatal — one extra sync open per
231
+ // material-change-gated recompute, acceptably cheap.
232
+ let providerCachePct = 0;
233
+ try {
234
+ providerCachePct = readLatestCacheHitPct(self.currentStateDir);
235
+ } catch {
236
+ /* non-fatal */
237
+ }
220
238
  const _snapResult = computeMegaSnapshot({
221
239
  lastCtxTokens: self.lastCtxTokens,
222
240
  lastCtxWindow: self.lastCtxWindow,
@@ -248,6 +266,7 @@ export function snapshotImpl(self: RuntimeSnapshotContext, ctx?: ExtensionContex
248
266
  ready,
249
267
  armed,
250
268
  modelSnap,
269
+ providerCachePct,
251
270
  });
252
271
  self.widgetData = _snapResult.widgetData;
253
272
  // S33: consume the flare after copying it into widgetData so it fires
@@ -271,8 +290,7 @@ export function snapshotImpl(self: RuntimeSnapshotContext, ctx?: ExtensionContex
271
290
  // free the slot and prevent a stale effect lingering between snapshots.
272
291
  if (
273
292
  self.activeEffect &&
274
- Date.now() - self.activeEffect.startedAt >=
275
- self.activeEffect.durationMs
293
+ Date.now() - self.activeEffect.startedAt >= self.activeEffect.durationMs
276
294
  ) {
277
295
  self.activeEffect = null;
278
296
  }
@@ -284,7 +302,11 @@ export function snapshotImpl(self: RuntimeSnapshotContext, ctx?: ExtensionContex
284
302
  // v0.8.5: record the material-change signature computed at the top so the
285
303
  // next snapshot() can skip this whole body when nothing material changed.
286
304
  try {
287
- recordPerfSample(self.currentStateDir, "db_recompute_ms", performance.now() - perfT0);
305
+ recordPerfSample(
306
+ self.currentStateDir,
307
+ "db_recompute_ms",
308
+ performance.now() - perfT0,
309
+ );
288
310
  recordPerfSample(self.currentStateDir, "disk_write_ms", perfDiskMs);
289
311
  } catch {
290
312
  /* non-fatal: perf instrumentation never blocks the agent */