@vellumai/assistant 0.8.9 → 0.8.10-dev.202606092238.d04fd59

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 (147) hide show
  1. package/AGENTS.md +1 -1
  2. package/examples/plugins/echo/README.md +3 -3
  3. package/node_modules/@vellumai/skill-host-contracts/src/tool-types.ts +2 -0
  4. package/openapi.yaml +38 -12
  5. package/package.json +1 -1
  6. package/scripts/sync-llm-catalog.ts +2 -0
  7. package/src/__tests__/agent-loop-exit-reason.test.ts +19 -14
  8. package/src/__tests__/build-persisted-content.test.ts +75 -1
  9. package/src/__tests__/config-managed-gemini-defaults.test.ts +2 -46
  10. package/src/__tests__/context-overflow-reducer.test.ts +264 -124
  11. package/src/__tests__/context-window-manager-overflow-rung.test.ts +289 -0
  12. package/src/__tests__/conversation-agent-loop-overflow.test.ts +22 -22
  13. package/src/__tests__/conversation-agent-loop.test.ts +45 -37
  14. package/src/__tests__/conversation-fork-crud.test.ts +110 -0
  15. package/src/__tests__/conversation-provider-retry-repair.test.ts +16 -20
  16. package/src/__tests__/conversation-runtime-assembly.test.ts +118 -5
  17. package/src/__tests__/conversation-surfaces-app-control.test.ts +4 -1
  18. package/src/__tests__/conversation-tool-setup-app-refresh.test.ts +91 -142
  19. package/src/__tests__/conversation-tool-setup-skill-attribution.test.ts +116 -0
  20. package/src/__tests__/conversation-tool-setup-test-helpers.ts +98 -0
  21. package/src/__tests__/corrected-target.test.ts +93 -0
  22. package/src/__tests__/credential-execution-feature-gates.test.ts +3 -5
  23. package/src/__tests__/credential-security-invariants.test.ts +1 -0
  24. package/src/__tests__/embedding-managed-proxy-selection.test.ts +6 -40
  25. package/src/__tests__/external-plugin-loader.test.ts +0 -1
  26. package/src/__tests__/guardian-routing-invariants.test.ts +91 -0
  27. package/src/__tests__/history-repair-hook.test.ts +2 -0
  28. package/src/__tests__/host-app-control-proxy.test.ts +45 -0
  29. package/src/__tests__/llm-catalog-parity.test.ts +4 -0
  30. package/src/__tests__/memory-retrieval-hook.test.ts +29 -15
  31. package/src/__tests__/notification-decision-strategy.test.ts +3 -3
  32. package/src/__tests__/persistence-secret-redaction.test.ts +78 -0
  33. package/src/__tests__/plugin-bootstrap.test.ts +82 -73
  34. package/src/__tests__/plugin-tool-contribution.test.ts +7 -4
  35. package/src/__tests__/plugin-types.test.ts +0 -8
  36. package/src/__tests__/provider-catalog-visibility.test.ts +1 -9
  37. package/src/__tests__/retry-thinking-adaptive-only.test.ts +245 -0
  38. package/src/__tests__/server-history-render.test.ts +39 -0
  39. package/src/__tests__/skills.test.ts +123 -0
  40. package/src/__tests__/title-generate-hook.test.ts +2 -0
  41. package/src/__tests__/tool-audit-listener.test.ts +51 -0
  42. package/src/__tests__/tool-executor-lifecycle-events.test.ts +32 -0
  43. package/src/__tests__/tool-start-timestamp.test.ts +218 -0
  44. package/src/agent/loop.ts +26 -23
  45. package/src/api/events/tool-result.ts +9 -0
  46. package/src/api/events/tool-use-start.ts +7 -0
  47. package/src/api/responses/conversation-message.ts +91 -14
  48. package/src/approvals/guardian-request-resolvers.ts +26 -0
  49. package/src/cli/commands/channel-verification-sessions.ts +6 -6
  50. package/src/cli/commands/inference-providers.ts +0 -8
  51. package/src/cli/commands/plugins.ts +2 -2
  52. package/src/cli/lib/__tests__/install-from-github.test.ts +174 -18
  53. package/src/cli/lib/__tests__/plugin-catalog-cache.test.ts +1 -1
  54. package/src/cli/lib/__tests__/plugin-details.test.ts +1 -1
  55. package/src/cli/lib/__tests__/plugin-marketplace.test.ts +1 -1
  56. package/src/cli/lib/__tests__/search-plugins.test.ts +11 -11
  57. package/src/cli/lib/install-from-github.ts +130 -19
  58. package/src/cli/lib/plugin-catalog-cache.ts +1 -1
  59. package/src/cli/lib/plugin-details.ts +4 -4
  60. package/src/cli/lib/plugin-marketplace.ts +2 -2
  61. package/src/cli/lib/search-plugins.ts +6 -6
  62. package/src/config/bundled-skills/skill-management/SKILL.md +89 -1
  63. package/src/config/env-registry.ts +12 -0
  64. package/src/config/feature-flag-registry.json +0 -80
  65. package/src/config/loader.ts +5 -22
  66. package/src/config/seed-inference-profiles.ts +1 -1
  67. package/src/config/skills.ts +101 -47
  68. package/src/context/strip-injections.ts +7 -4
  69. package/src/daemon/conversation-agent-loop-handlers.ts +102 -6
  70. package/src/daemon/conversation-agent-loop.ts +134 -232
  71. package/src/daemon/conversation-runtime-assembly.ts +44 -8
  72. package/src/daemon/conversation-tool-setup.ts +9 -1
  73. package/src/daemon/external-plugins-bootstrap.ts +33 -87
  74. package/src/daemon/handlers/config-channels.ts +11 -2
  75. package/src/daemon/handlers/shared.ts +9 -1
  76. package/src/daemon/handlers/skills.ts +6 -2
  77. package/src/daemon/host-app-control-proxy.ts +72 -57
  78. package/src/daemon/message-protocol.ts +0 -7
  79. package/src/daemon/message-types/skills.ts +4 -0
  80. package/src/events/tool-audit-listener.ts +7 -1
  81. package/src/memory/__tests__/tool-invocation-test-helpers.ts +69 -0
  82. package/src/memory/conversation-crud.ts +44 -1
  83. package/src/memory/db-init.ts +4 -0
  84. package/src/memory/embedding-backend.ts +5 -22
  85. package/src/memory/memory-retrospective-startup-cleanup.ts +1 -1
  86. package/src/memory/migrations/275-tool-invocations-add-skill-id.test.ts +81 -0
  87. package/src/memory/migrations/275-tool-invocations-add-skill-id.ts +20 -0
  88. package/src/memory/migrations/276-tool-invocations-created-at-id-index.test.ts +68 -0
  89. package/src/memory/migrations/276-tool-invocations-created-at-id-index.ts +20 -0
  90. package/src/memory/migrations/index.ts +2 -0
  91. package/src/memory/schema/conversations.ts +3 -0
  92. package/src/memory/tool-execution-events-store.test.ts +162 -0
  93. package/src/memory/tool-execution-events-store.ts +73 -0
  94. package/src/memory/tool-usage-store.ts +4 -3
  95. package/src/memory/v2/__tests__/injected-block-slugs.test.ts +51 -0
  96. package/src/memory/v2/activation-store.ts +50 -1
  97. package/src/memory/v2/injected-block-slugs.ts +30 -0
  98. package/src/notifications/__tests__/copy-composer.test.ts +244 -0
  99. package/src/notifications/access-request-copy.ts +298 -0
  100. package/src/notifications/adapters/slack.ts +3 -3
  101. package/src/notifications/adapters/telegram.ts +2 -1
  102. package/src/notifications/copy-composer.ts +49 -267
  103. package/src/notifications/decision-engine.ts +16 -35
  104. package/src/notifications/home-feed-side-effect.ts +1 -6
  105. package/src/platform/client.ts +1 -3
  106. package/src/platform/feature-gate.ts +3 -12
  107. package/src/plugin-api/constants.ts +2 -0
  108. package/src/plugin-api/index.ts +34 -6
  109. package/src/plugin-api/types.ts +19 -0
  110. package/src/plugins/defaults/compaction/compact.ts +39 -1
  111. package/src/plugins/defaults/compaction/context-overflow-reducer.ts +240 -32
  112. package/src/plugins/defaults/compaction/corrected-target.ts +53 -0
  113. package/src/plugins/defaults/compaction/window-manager.ts +136 -0
  114. package/src/plugins/defaults/index.ts +24 -0
  115. package/src/plugins/defaults/memory-retrieval/hooks/post-compact.ts +68 -43
  116. package/src/plugins/defaults/memory-retrieval/hooks/{user-prompt-submit-temp.ts → user-prompt-submit.ts} +36 -67
  117. package/src/plugins/defaults/memory-retrieval/package.json +14 -0
  118. package/src/plugins/external-api.ts +1 -1
  119. package/src/plugins/types.ts +5 -51
  120. package/src/providers/inference/__tests__/base-url-route-validation.test.ts +1 -2
  121. package/src/providers/model-catalog.ts +57 -1
  122. package/src/providers/registry.ts +0 -8
  123. package/src/providers/retry.ts +35 -7
  124. package/src/runtime/routes/__tests__/acp-routes.test.ts +151 -0
  125. package/src/runtime/routes/__tests__/inference-provider-connection-routes.test.ts +0 -62
  126. package/src/runtime/routes/__tests__/plugins-routes.test.ts +4 -4
  127. package/src/runtime/routes/acp-routes.test.ts +106 -0
  128. package/src/runtime/routes/acp-routes.ts +248 -2
  129. package/src/runtime/routes/browser-tabs-routes.ts +1 -1
  130. package/src/runtime/routes/channel-verification-routes.ts +14 -5
  131. package/src/runtime/routes/chatgpt-subscription-auth-routes.ts +0 -14
  132. package/src/runtime/routes/inbound-stages/acl-enforcement.ts +33 -34
  133. package/src/runtime/routes/inference-provider-connection-routes.ts +0 -45
  134. package/src/runtime/routes/plugins-routes.ts +3 -3
  135. package/src/runtime/verification-outbound-actions.ts +147 -2
  136. package/src/runtime/verification-templates.ts +29 -3
  137. package/src/telemetry/types.ts +25 -1
  138. package/src/telemetry/usage-telemetry-reporter.test.ts +141 -7
  139. package/src/telemetry/usage-telemetry-reporter.ts +63 -7
  140. package/src/tools/executor.ts +4 -1
  141. package/src/tools/skills/load.ts +11 -6
  142. package/src/tools/terminal/safe-env.ts +1 -0
  143. package/src/tools/types.ts +10 -0
  144. package/src/__tests__/plugin-skill-contribution.test.ts +0 -355
  145. package/src/daemon/message-types/browser.ts +0 -10
  146. package/src/notifications/__tests__/emit-signal-home-feed.test.ts +0 -187
  147. package/src/plugins/plugin-skill-contributions.ts +0 -292
@@ -0,0 +1,289 @@
1
+ /**
2
+ * Coverage for the turn-scoped overflow-recovery state machine that lives on
3
+ * `ContextWindowManager.reduceOverflowOneRung`. The manager holds the reducer
4
+ * state across the successive rung calls of a single turn, derives the
5
+ * compaction target from its own preflight budget corrected by the provider's
6
+ * actual token count, and starts a fresh ladder once the turn boundary resets
7
+ * it. `reduceContextOverflow` is mocked so these tests pin the manager's own
8
+ * orchestration without exercising the full reduction ladder.
9
+ */
10
+ import { beforeEach, describe, expect, mock, test } from "bun:test";
11
+
12
+ function makeLoggerStub(): Record<string, unknown> {
13
+ const stub: Record<string, unknown> = {};
14
+ for (const m of [
15
+ "info",
16
+ "warn",
17
+ "error",
18
+ "debug",
19
+ "trace",
20
+ "fatal",
21
+ "silent",
22
+ "child",
23
+ ]) {
24
+ stub[m] = m === "child" ? () => makeLoggerStub() : () => {};
25
+ }
26
+ return stub;
27
+ }
28
+
29
+ mock.module("../util/logger.js", () => ({
30
+ getLogger: () => makeLoggerStub(),
31
+ }));
32
+
33
+ // ── Module-level mock state ───────────────────────────────────────────
34
+ // The reducer call is captured so tests can assert which state and config the
35
+ // manager fed in; the returned step is seeded per call so tests can drive the
36
+ // ladder forward across rungs.
37
+
38
+ interface ReducerState {
39
+ appliedTiers: string[];
40
+ injectionMode: string;
41
+ exhausted: boolean;
42
+ }
43
+
44
+ interface ReducerStepResult {
45
+ messages: unknown;
46
+ tier: string;
47
+ state: ReducerState;
48
+ estimatedTokens: number;
49
+ }
50
+
51
+ let reduceCalls: Array<{
52
+ messages: unknown;
53
+ config: Record<string, unknown>;
54
+ state: ReducerState | undefined;
55
+ }> = [];
56
+ let reduceSteps: ReducerStepResult[] = [];
57
+
58
+ const estimateReturns: number[] = [];
59
+
60
+ mock.module("../context/token-estimator.js", () => ({
61
+ estimatePromptTokens: (): number => {
62
+ const next = estimateReturns.shift();
63
+ if (next === undefined) {
64
+ throw new Error(
65
+ "estimatePromptTokens called more times than estimateReturns seeded",
66
+ );
67
+ }
68
+ return next;
69
+ },
70
+ }));
71
+
72
+ mock.module(
73
+ "../plugins/defaults/compaction/context-overflow-reducer.js",
74
+ () => ({
75
+ createInitialReducerState: (): ReducerState => ({
76
+ appliedTiers: [],
77
+ injectionMode: "full",
78
+ exhausted: false,
79
+ }),
80
+ reduceContextOverflow: async (
81
+ messages: unknown,
82
+ config: Record<string, unknown>,
83
+ state: ReducerState | undefined,
84
+ ): Promise<ReducerStepResult> => {
85
+ reduceCalls.push({ messages, config, state });
86
+ const idx = reduceCalls.length - 1;
87
+ const step = reduceSteps[idx];
88
+ if (!step) {
89
+ throw new Error(
90
+ `Mock reducer called ${reduceCalls.length} time(s) but only ${reduceSteps.length} step(s) seeded`,
91
+ );
92
+ }
93
+ return step;
94
+ },
95
+ }),
96
+ );
97
+
98
+ import { ContextWindowManager } from "../plugins/defaults/compaction/window-manager.js";
99
+ import type { Message, Provider } from "../providers/types.js";
100
+
101
+ function makeProvider(): Provider {
102
+ return {
103
+ name: "mock-provider",
104
+ sendMessage: async () => ({
105
+ content: [],
106
+ model: "mock-model",
107
+ usage: { inputTokens: 0, outputTokens: 0 },
108
+ stopReason: "end_turn",
109
+ }),
110
+ };
111
+ }
112
+
113
+ function makeMessages(count: number): Message[] {
114
+ const messages: Message[] = [];
115
+ for (let i = 0; i < count; i++) {
116
+ messages.push({
117
+ role: i % 2 === 0 ? "user" : "assistant",
118
+ content: [{ type: "text", text: `msg ${i}` }],
119
+ });
120
+ }
121
+ return messages;
122
+ }
123
+
124
+ function makeConfig(maxAttempts: number = 3) {
125
+ return {
126
+ enabled: true,
127
+ maxInputTokens: 200_000,
128
+ targetBudgetRatio: 0.3,
129
+ compactThreshold: 0.8,
130
+ summaryBudgetRatio: 0.05,
131
+ overflowRecovery: {
132
+ enabled: true,
133
+ safetyMarginRatio: 0.05,
134
+ maxAttempts,
135
+ interactiveLatestTurnCompression: "summarize" as const,
136
+ nonInteractiveLatestTurnCompression: "summarize" as const,
137
+ },
138
+ };
139
+ }
140
+
141
+ function buildManager(maxAttempts: number = 3): ContextWindowManager {
142
+ return new ContextWindowManager({
143
+ provider: makeProvider(),
144
+ systemPrompt: "you are a test assistant",
145
+ config: makeConfig(maxAttempts),
146
+ conversationId: "conv-test",
147
+ });
148
+ }
149
+
150
+ function makeStep(
151
+ appliedTiers: string[],
152
+ exhausted: boolean = false,
153
+ ): ReducerStepResult {
154
+ return {
155
+ messages: makeMessages(2),
156
+ tier: appliedTiers[appliedTiers.length - 1] ?? "emergency_compaction",
157
+ state: { appliedTiers, injectionMode: "full", exhausted },
158
+ estimatedTokens: 100_000,
159
+ };
160
+ }
161
+
162
+ describe("ContextWindowManager.reduceOverflowOneRung", () => {
163
+ beforeEach(() => {
164
+ reduceCalls = [];
165
+ reduceSteps = [];
166
+ estimateReturns.length = 0;
167
+ });
168
+
169
+ test("holds reducer state across rungs within a turn", async () => {
170
+ // GIVEN a manager and a reducer that advances the ladder one rung per call
171
+ estimateReturns.push(240_000, 240_000);
172
+ reduceSteps = [
173
+ makeStep(["emergency_compaction"]),
174
+ makeStep(["emergency_compaction", "forced_compaction"]),
175
+ ];
176
+ const manager = buildManager();
177
+
178
+ // WHEN two rungs run within the same turn
179
+ await manager.reduceOverflowOneRung(makeMessages(10), {
180
+ actualTokens: null,
181
+ allowAutoCompressLatestTurn: false,
182
+ });
183
+ await manager.reduceOverflowOneRung(makeMessages(10), {
184
+ actualTokens: null,
185
+ allowAutoCompressLatestTurn: false,
186
+ });
187
+
188
+ // THEN the first call seeds an empty ladder
189
+ expect(reduceCalls).toHaveLength(2);
190
+ expect(reduceCalls[0]?.state?.appliedTiers).toEqual([]);
191
+ // AND the second call carries the first rung's state forward
192
+ expect(reduceCalls[1]?.state?.appliedTiers).toEqual([
193
+ "emergency_compaction",
194
+ ]);
195
+ });
196
+
197
+ test("resetOverflowRecovery starts a fresh ladder", async () => {
198
+ // GIVEN a manager whose ladder has already advanced one rung
199
+ estimateReturns.push(240_000, 240_000);
200
+ reduceSteps = [
201
+ makeStep(["emergency_compaction"]),
202
+ makeStep(["emergency_compaction"]),
203
+ ];
204
+ const manager = buildManager();
205
+ await manager.reduceOverflowOneRung(makeMessages(10), {
206
+ actualTokens: null,
207
+ allowAutoCompressLatestTurn: false,
208
+ });
209
+
210
+ // WHEN the turn boundary resets recovery and a new rung runs
211
+ manager.resetOverflowRecovery();
212
+ await manager.reduceOverflowOneRung(makeMessages(10), {
213
+ actualTokens: null,
214
+ allowAutoCompressLatestTurn: false,
215
+ });
216
+
217
+ // THEN the post-reset call seeds an empty ladder again
218
+ expect(reduceCalls[1]?.state?.appliedTiers).toEqual([]);
219
+ });
220
+
221
+ test("corrected target lowers below preflight when the provider under-counted", async () => {
222
+ // GIVEN the provider rejected at 480k while the estimator counted 240k
223
+ estimateReturns.push(240_000);
224
+ reduceSteps = [makeStep(["emergency_compaction"])];
225
+ const manager = buildManager();
226
+
227
+ // WHEN a rung runs with the provider's actual token count
228
+ await manager.reduceOverflowOneRung(makeMessages(10), {
229
+ actualTokens: 480_000,
230
+ allowAutoCompressLatestTurn: false,
231
+ });
232
+
233
+ // THEN the target is the preflight budget (200k * 0.95 = 190k) divided by
234
+ // the 2x estimation-error ratio
235
+ expect(reduceCalls[0]?.config.targetTokens).toBe(95_000);
236
+ });
237
+
238
+ test("target is the full preflight budget when the actual count is unknown", async () => {
239
+ // GIVEN no provider-reported actual token count
240
+ estimateReturns.push(240_000);
241
+ reduceSteps = [makeStep(["emergency_compaction"])];
242
+ const manager = buildManager();
243
+
244
+ // WHEN a rung runs
245
+ await manager.reduceOverflowOneRung(makeMessages(10), {
246
+ actualTokens: null,
247
+ allowAutoCompressLatestTurn: false,
248
+ });
249
+
250
+ // THEN the target is the uncorrected preflight budget (200k * 0.95)
251
+ expect(reduceCalls[0]?.config.targetTokens).toBe(190_000);
252
+ });
253
+
254
+ test("long histories widen the safety margin", async () => {
255
+ // GIVEN a history longer than the 50-message threshold
256
+ estimateReturns.push(240_000);
257
+ reduceSteps = [makeStep(["emergency_compaction"])];
258
+ const manager = buildManager();
259
+
260
+ // WHEN a rung runs over 60 messages with no actual-token correction
261
+ await manager.reduceOverflowOneRung(makeMessages(60), {
262
+ actualTokens: null,
263
+ allowAutoCompressLatestTurn: false,
264
+ });
265
+
266
+ // THEN the safety margin bumps to 0.15 → preflight budget 200k * 0.85
267
+ expect(reduceCalls[0]?.config.targetTokens).toBe(170_000);
268
+ });
269
+
270
+ test("forwards the policy auto-compress permission to the ladder", async () => {
271
+ // GIVEN the overflow policy permits the terminal auto-compress rung
272
+ estimateReturns.push(240_000);
273
+ reduceSteps = [makeStep(["emergency_compaction"])];
274
+ const manager = buildManager();
275
+
276
+ // WHEN a rung runs
277
+ await manager.reduceOverflowOneRung(makeMessages(10), {
278
+ actualTokens: null,
279
+ allowAutoCompressLatestTurn: true,
280
+ overrideProfile: "fast",
281
+ });
282
+
283
+ // THEN the manager passes the policy decision and profile through to the
284
+ // reducer config alongside the budget it owns
285
+ expect(reduceCalls[0]?.config.allowAutoCompressLatestTurn).toBe(true);
286
+ expect(reduceCalls[0]?.config.overrideProfile).toBe("fast");
287
+ expect(reduceCalls[0]?.config.maxMiddleTierAttempts).toBe(3);
288
+ });
289
+ });
@@ -1721,28 +1721,30 @@ describe("session-agent-loop overflow recovery (JARVIS-110)", () => {
1721
1721
  return 170_000;
1722
1722
  };
1723
1723
 
1724
- // Convergence reducer becomes exhausted on the second tier so the
1725
- // loop escalates from convergence to the action-resolution block.
1724
+ // The reduction ladder applies a middle tier first, then escalates to its
1725
+ // terminal auto-compress-latest-turn rung and reports exhaustion. The
1726
+ // terminal rung is what produces a `budget_yield_unrecovered` outcome when
1727
+ // its rerun still yields at the mid-loop checkpoint.
1726
1728
  let reducerCallCount = 0;
1727
1729
  mockReducerStepFn = (msgs: Message[]) => {
1728
1730
  reducerCallCount++;
1729
- const exhausted = reducerCallCount >= 2;
1731
+ const terminal = reducerCallCount >= 2;
1730
1732
  return {
1731
1733
  messages: msgs,
1732
- tier: exhausted ? "tool_result_truncation" : "forced_compaction",
1734
+ tier: terminal ? "auto_compress_latest_turn" : "forced_compaction",
1733
1735
  state: {
1734
- appliedTiers: exhausted
1735
- ? ["forced_compaction", "tool_result_truncation"]
1736
+ appliedTiers: terminal
1737
+ ? ["forced_compaction", "auto_compress_latest_turn"]
1736
1738
  : ["forced_compaction"],
1737
1739
  injectionMode: "full" as const,
1738
- exhausted,
1740
+ exhausted: terminal,
1739
1741
  },
1740
- estimatedTokens: exhausted ? 60_000 : 80_000,
1742
+ estimatedTokens: terminal ? 60_000 : 80_000,
1741
1743
  };
1742
1744
  };
1743
1745
 
1744
- // The overflow policy directs us into auto_compress_latest_turn so the
1745
- // emergency compaction + final agentLoop.run path executes.
1746
+ // The overflow policy permits the terminal auto-compress-latest-turn rung,
1747
+ // so the ladder runs it as its final step.
1746
1748
  mockOverflowAction = "auto_compress_latest_turn";
1747
1749
 
1748
1750
  // Every provider call returns a tool_use, so each loop run does a tool
@@ -1752,19 +1754,16 @@ describe("session-agent-loop overflow recovery (JARVIS-110)", () => {
1752
1754
  toolUseResponse("tu-1", "bash", { command: "ls" }),
1753
1755
  ]);
1754
1756
 
1755
- // Every forced `maybeCompact` is invoked through three distinct call
1756
- // sites, all owned by the loop's pre-call budget gate / recovery ladder:
1757
- // 1. First-call (turn-start) gate (`force: true`) — the loop now owns
1758
- // the turn-start compaction. It succeeds, but the mocked estimate
1759
- // stays above the mid-loop threshold, so the turn proceeds and the
1760
- // mid-loop gate still trips on the next iteration.
1757
+ // Forced `maybeCompact` is invoked through the loop's own pre-call budget
1758
+ // gate at two call sites (the reduction-ladder rungs are mocked out, so
1759
+ // their summary calls don't reach this manager):
1760
+ // 1. First-call (turn-start) gate (`force: true`) — the loop owns the
1761
+ // turn-start compaction. It succeeds, but the mocked estimate stays
1762
+ // above the mid-loop threshold, so the turn proceeds and the mid-loop
1763
+ // gate still trips on the next iteration.
1761
1764
  // 2. Mid-loop after the first tool turn (`force: true`) — must signal
1762
1765
  // `exhausted: true` so the daemon escalates to the convergence
1763
1766
  // reducer instead of looping forever.
1764
- // 3. auto_compress_latest_turn emergency compaction (`force: true`,
1765
- // `minKeepRecentUserTurns: 0`) — succeeds and drops tokens below
1766
- // threshold; the subsequent rerun yields again and is classified
1767
- // as BUDGET_YIELD_UNRECOVERED.
1768
1767
  let forcedMaybeCompactCallCount = 0;
1769
1768
  const ctx = makeCtx({
1770
1769
  loopProvider: provider,
@@ -1843,7 +1842,8 @@ describe("session-agent-loop overflow recovery (JARVIS-110)", () => {
1843
1842
  exhausted: true,
1844
1843
  };
1845
1844
  }
1846
- // Emergency compaction call from auto_compress_latest_turn.
1845
+ // Defensive fallback for any additional forced probe; the two gate
1846
+ // call sites above are the only ones this test exercises.
1847
1847
  return {
1848
1848
  compacted: true,
1849
1849
  messages: [
@@ -1853,7 +1853,7 @@ describe("session-agent-loop overflow recovery (JARVIS-110)", () => {
1853
1853
  },
1854
1854
  ] as Message[],
1855
1855
  compactedPersistedMessages: 5,
1856
- summaryText: "Emergency summary",
1856
+ summaryText: "Fallback summary",
1857
1857
  previousEstimatedInputTokens: 170_000,
1858
1858
  estimatedInputTokens: 90_000,
1859
1859
  maxInputTokens: 200_000,
@@ -1710,27 +1710,31 @@ describe("session-agent-loop", () => {
1710
1710
  test("non-interactive auto-compress continues without approval prompt", async () => {
1711
1711
  const events: ServerMessage[] = [];
1712
1712
 
1713
- // Reducer exhausts all tiers
1714
- mockReducerStepFn = (msgs: Message[]) => ({
1715
- messages: msgs,
1716
- tier: "injection_downgrade",
1717
- state: {
1718
- appliedTiers: [
1719
- "forced_compaction",
1720
- "tool_result_truncation",
1721
- "media_stubbing",
1722
- "injection_downgrade",
1723
- ],
1724
- injectionMode: "minimal",
1725
- exhausted: true,
1726
- },
1727
- estimatedTokens: 120000,
1728
- });
1713
+ // The ladder applies a middle tier first, then escalates to its terminal
1714
+ // auto-compress-latest-turn rung (permitted by the overflow policy) and
1715
+ // reports exhaustion — mirroring the reducer owning every rung.
1716
+ let reducerCalls = 0;
1717
+ mockReducerStepFn = (msgs: Message[]) => {
1718
+ reducerCalls++;
1719
+ const terminal = reducerCalls >= 2;
1720
+ return {
1721
+ messages: msgs,
1722
+ tier: terminal ? "auto_compress_latest_turn" : "forced_compaction",
1723
+ state: {
1724
+ appliedTiers: terminal
1725
+ ? ["forced_compaction", "auto_compress_latest_turn"]
1726
+ : ["forced_compaction"],
1727
+ injectionMode: "full",
1728
+ exhausted: terminal,
1729
+ },
1730
+ estimatedTokens: 120000,
1731
+ };
1732
+ };
1729
1733
 
1730
1734
  mockOverflowAction = "auto_compress_latest_turn";
1731
1735
 
1732
1736
  // The provider rejects the first two calls with context-too-large errors,
1733
- // then succeeds after the emergency auto-compress runs.
1737
+ // then succeeds after the terminal auto-compress rung runs.
1734
1738
  const ctx = makeCtx({
1735
1739
  providerResponses: [
1736
1740
  new Error("context_length_exceeded"),
@@ -1785,24 +1789,26 @@ describe("session-agent-loop", () => {
1785
1789
  // attribute the silent stall.
1786
1790
  const events: ServerMessage[] = [];
1787
1791
 
1788
- // Reducer exhausts all 4 tiers on first call so the convergence
1789
- // loop runs exactly one iteration before falling through to
1790
- // the auto_compress_latest_turn branch.
1791
- mockReducerStepFn = (msgs: Message[]) => ({
1792
- messages: msgs,
1793
- tier: "injection_downgrade",
1794
- state: {
1795
- appliedTiers: [
1796
- "forced_compaction",
1797
- "tool_result_truncation",
1798
- "media_stubbing",
1799
- "injection_downgrade",
1800
- ],
1801
- injectionMode: "minimal",
1802
- exhausted: true,
1803
- },
1804
- estimatedTokens: 120_000,
1805
- });
1792
+ // The ladder applies a middle tier, then runs its terminal
1793
+ // auto-compress-latest-turn rung and reports exhaustion. Its rerun is the
1794
+ // one that still yields at the mid-loop budget checkpoint.
1795
+ let reducerCalls = 0;
1796
+ mockReducerStepFn = (msgs: Message[]) => {
1797
+ reducerCalls++;
1798
+ const terminal = reducerCalls >= 2;
1799
+ return {
1800
+ messages: msgs,
1801
+ tier: terminal ? "auto_compress_latest_turn" : "forced_compaction",
1802
+ state: {
1803
+ appliedTiers: terminal
1804
+ ? ["forced_compaction", "auto_compress_latest_turn"]
1805
+ : ["forced_compaction"],
1806
+ injectionMode: "full",
1807
+ exhausted: terminal,
1808
+ },
1809
+ estimatedTokens: 120_000,
1810
+ };
1811
+ };
1806
1812
 
1807
1813
  mockOverflowAction = "auto_compress_latest_turn";
1808
1814
 
@@ -1934,8 +1940,10 @@ describe("session-agent-loop", () => {
1934
1940
 
1935
1941
  await runAgentLoopImpl(ctx, "hello", "msg-1", (msg) => events.push(msg));
1936
1942
 
1937
- // maxAttempts is 3 — reducer should be called at most 3 times
1938
- expect(reducerCalls).toBeLessThanOrEqual(3);
1943
+ // A misbehaving reducer that never reports exhaustion is bounded by the
1944
+ // driver's safety backstop: at most the middle-tier budget plus the
1945
+ // emergency and terminal rungs (maxAttempts + 2 = 5).
1946
+ expect(reducerCalls).toBeLessThanOrEqual(5);
1939
1947
  });
1940
1948
  });
1941
1949
 
@@ -922,6 +922,116 @@ describe("forkConversation", () => {
922
922
  expect(loadGraphMemoryState(fork.id)).toBeNull();
923
923
  });
924
924
 
925
+ test("truncated fork seeds everInjected from inherited memory attachments", async () => {
926
+ const source = createConversation("Truncated seed thread");
927
+ await addMessage(source.id, "user", "first turn", {
928
+ metadata: {
929
+ memoryInjectedBlock:
930
+ "# memory/concepts/topics/page-a.md\nSummary A\n\n# memory/concepts/topics/page-b.md\nSummary B",
931
+ },
932
+ skipIndexing: true,
933
+ });
934
+ await addMessage(source.id, "assistant", "first reply", {
935
+ skipIndexing: true,
936
+ });
937
+ const boundaryMessage = await addMessage(source.id, "user", "second turn", {
938
+ metadata: {
939
+ memoryInjectedBlock: "# memory/concepts/topics/page-c.md\nSummary C",
940
+ },
941
+ skipIndexing: true,
942
+ });
943
+ await addMessage(source.id, "assistant", "second reply", {
944
+ skipIndexing: true,
945
+ });
946
+ // Past the fork boundary — its attachment must NOT be claimed.
947
+ await addMessage(source.id, "user", "third turn", {
948
+ metadata: {
949
+ memoryInjectedBlock: "# memory/concepts/topics/page-d.md\nSummary D",
950
+ },
951
+ skipIndexing: true,
952
+ });
953
+
954
+ const db = getDb();
955
+ db.insert(activationState)
956
+ .values({
957
+ conversationId: source.id,
958
+ messageId: "parent-msg",
959
+ stateJson: JSON.stringify({ "topics/page-d": 0.9 }),
960
+ everInjectedJson: JSON.stringify([
961
+ { slug: "topics/page-a", turn: 1 },
962
+ { slug: "topics/page-b", turn: 1 },
963
+ { slug: "topics/page-c", turn: 2 },
964
+ { slug: "topics/page-d", turn: 3 },
965
+ ]),
966
+ currentTurn: 3,
967
+ updatedAt: 1_700_000_000_000,
968
+ })
969
+ .run();
970
+
971
+ const fork = forkConversation({
972
+ conversationId: source.id,
973
+ throughMessageId: boundaryMessage.id,
974
+ });
975
+
976
+ const childState = await hydrateActivationState(db, fork.id);
977
+ expect(childState).not.toBeNull();
978
+ // Exactly the slugs whose attachments live in the copied history —
979
+ // page-d (injected past the boundary) stays re-injectable.
980
+ expect(childState?.everInjected.map((e) => e.slug).sort()).toEqual([
981
+ "topics/page-a",
982
+ "topics/page-b",
983
+ "topics/page-c",
984
+ ]);
985
+ expect(childState?.everInjected.every((e) => e.turn === 0)).toBe(true);
986
+ // Activation scores and the turn counter start fresh, matching the
987
+ // graph tracker (also not copied for truncated forks).
988
+ expect(childState?.state).toEqual({});
989
+ expect(childState?.currentTurn).toBe(0);
990
+ });
991
+
992
+ test("truncated fork ignores attachments behind an inherited compaction boundary", async () => {
993
+ const source = createConversation("Compacted truncated thread");
994
+ await addMessage(source.id, "user", "compacted turn", {
995
+ metadata: {
996
+ memoryInjectedBlock:
997
+ "# memory/concepts/topics/page-compacted.md\nOld summary",
998
+ },
999
+ skipIndexing: true,
1000
+ });
1001
+ await addMessage(source.id, "assistant", "compacted reply", {
1002
+ skipIndexing: true,
1003
+ });
1004
+ const boundaryMessage = await addMessage(source.id, "user", "live turn", {
1005
+ metadata: {
1006
+ memoryInjectedBlock: "# memory/concepts/topics/page-live.md\nSummary",
1007
+ },
1008
+ skipIndexing: true,
1009
+ });
1010
+ await addMessage(source.id, "assistant", "live reply", {
1011
+ skipIndexing: true,
1012
+ });
1013
+ await addMessage(source.id, "user", "past boundary", {
1014
+ skipIndexing: true,
1015
+ });
1016
+ // First two messages sit behind the compaction boundary: their
1017
+ // attachments are not rendered, so the fork must not claim them.
1018
+ getDb()
1019
+ .update(conversations)
1020
+ .set({ contextCompactedMessageCount: 2 })
1021
+ .where(eq(conversations.id, source.id))
1022
+ .run();
1023
+
1024
+ const fork = forkConversation({
1025
+ conversationId: source.id,
1026
+ throughMessageId: boundaryMessage.id,
1027
+ });
1028
+
1029
+ const childState = await hydrateActivationState(getDb(), fork.id);
1030
+ expect(childState?.everInjected.map((e) => e.slug)).toEqual([
1031
+ "topics/page-live",
1032
+ ]);
1033
+ });
1034
+
925
1035
  test("defaults conversationType to standard and inherits the parent's group", async () => {
926
1036
  const source = createConversation("Default inheritance thread");
927
1037
  await addMessage(source.id, "user", "first message", {
@@ -98,8 +98,9 @@ mock.module("../context/token-estimator.js", () => ({
98
98
 
99
99
  // Overflow recovery module mocks — the convergence loop delegates to these
100
100
  // but these tests exercise the Conversation-level flow, not the reducer internals.
101
- // The reducer mock delegates to the compactFn to simulate a forced compaction
102
- // tier, matching the real reducer's behavior for Tier 1.
101
+ // The reducer mock runs the forced-compaction tier through defaultCompact, which
102
+ // resolves the conversation's ContextWindowManager from the store — mirroring the
103
+ // real reducer's Tier 1.
103
104
  mock.module(
104
105
  "../plugins/defaults/compaction/context-overflow-reducer.js",
105
106
  () => ({
@@ -110,29 +111,24 @@ mock.module(
110
111
  }),
111
112
  reduceContextOverflow: async (
112
113
  msgs: Message[],
113
- _cfg: unknown,
114
+ cfg: { conversationId: string },
114
115
  _state: unknown,
115
- compactFn?: (
116
- m: Message[],
117
- s: AbortSignal | undefined,
118
- o: Record<string, unknown>,
119
- ) => Promise<{
120
- compacted: boolean;
121
- messages: Message[];
122
- compactedPersistedMessages?: number;
123
- summaryText?: string;
124
- [k: string]: unknown;
125
- }>,
126
116
  signal?: AbortSignal,
127
117
  ) => {
118
+ const { defaultCompact } =
119
+ await import("../plugins/defaults/compaction/compact.js");
120
+ const cr = await defaultCompact({
121
+ conversationId: cfg.conversationId,
122
+ messages: msgs,
123
+ signal,
124
+ force: true,
125
+ minKeepRecentUserTurns: 0,
126
+ });
128
127
  let resultMessages = msgs;
129
128
  let compactionResult;
130
- if (compactFn) {
131
- const cr = await compactFn(msgs, signal, { force: true });
132
- if (cr.compacted) {
133
- resultMessages = cr.messages;
134
- compactionResult = cr;
135
- }
129
+ if (cr.compacted) {
130
+ resultMessages = cr.messages;
131
+ compactionResult = cr;
136
132
  }
137
133
  return {
138
134
  messages: resultMessages,