@kenkaiiii/ggcoder 5.109.0 → 6.0.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 (71) hide show
  1. package/README.md +1 -1
  2. package/assets/skills/gg-guide/references/code-mode.md +3 -0
  3. package/dist/app-sidecar/branch-routes.d.ts +42 -0
  4. package/dist/app-sidecar/branch-routes.js +189 -0
  5. package/dist/app-sidecar/branch-routes.js.map +1 -0
  6. package/dist/app-sidecar/git-branches.d.ts +81 -0
  7. package/dist/app-sidecar/git-branches.js +270 -0
  8. package/dist/app-sidecar/git-branches.js.map +1 -0
  9. package/dist/app-sidecar/history-routes.js +3 -0
  10. package/dist/app-sidecar/history-routes.js.map +1 -1
  11. package/dist/app-sidecar/history.d.ts +2 -0
  12. package/dist/app-sidecar/history.js.map +1 -1
  13. package/dist/app-sidecar/repo-polls.d.ts +3 -1
  14. package/dist/app-sidecar/repo-polls.js +9 -1
  15. package/dist/app-sidecar/repo-polls.js.map +1 -1
  16. package/dist/app-sidecar/route-context.d.ts +1 -0
  17. package/dist/app-sidecar/session-types.d.ts +5 -0
  18. package/dist/app-sidecar/workspace-routes.js +12 -2
  19. package/dist/app-sidecar/workspace-routes.js.map +1 -1
  20. package/dist/app-sidecar/worktrees.d.ts +100 -0
  21. package/dist/app-sidecar/worktrees.js +260 -0
  22. package/dist/app-sidecar/worktrees.js.map +1 -0
  23. package/dist/app-sidecar-sessions.d.ts +3 -1
  24. package/dist/app-sidecar-sessions.js +6 -4
  25. package/dist/app-sidecar-sessions.js.map +1 -1
  26. package/dist/app-sidecar.js +159 -7
  27. package/dist/app-sidecar.js.map +1 -1
  28. package/dist/core/agent-session.d.ts +72 -0
  29. package/dist/core/agent-session.js +203 -46
  30. package/dist/core/agent-session.js.map +1 -1
  31. package/dist/core/checkout-record.d.ts +22 -0
  32. package/dist/core/checkout-record.js +68 -0
  33. package/dist/core/checkout-record.js.map +1 -0
  34. package/dist/core/compaction/tool-result-pruner.d.ts +11 -0
  35. package/dist/core/compaction/tool-result-pruner.js +26 -0
  36. package/dist/core/compaction/tool-result-pruner.js.map +1 -1
  37. package/dist/core/destructive-git-guard.d.ts +23 -0
  38. package/dist/core/destructive-git-guard.js +11 -8
  39. package/dist/core/destructive-git-guard.js.map +1 -1
  40. package/dist/core/event-bus.d.ts +4 -0
  41. package/dist/core/event-bus.js +1 -0
  42. package/dist/core/event-bus.js.map +1 -1
  43. package/dist/core/lsp/servers.js +1 -1
  44. package/dist/core/project-discovery.d.ts +3 -1
  45. package/dist/core/project-discovery.js +5 -3
  46. package/dist/core/project-discovery.js.map +1 -1
  47. package/dist/core/regrounding.d.ts +9 -1
  48. package/dist/core/regrounding.js +46 -6
  49. package/dist/core/regrounding.js.map +1 -1
  50. package/dist/core/session-manager.d.ts +3 -1
  51. package/dist/core/session-manager.js.map +1 -1
  52. package/dist/core/shared-checkout-guard.d.ts +78 -0
  53. package/dist/core/shared-checkout-guard.js +219 -0
  54. package/dist/core/shared-checkout-guard.js.map +1 -0
  55. package/dist/modes/subagent-worker-mode.js +4 -0
  56. package/dist/modes/subagent-worker-mode.js.map +1 -1
  57. package/dist/tools/bash.d.ts +3 -1
  58. package/dist/tools/bash.js +19 -7
  59. package/dist/tools/bash.js.map +1 -1
  60. package/dist/tools/index.d.ts +2 -0
  61. package/dist/tools/index.js +1 -1
  62. package/dist/tools/index.js.map +1 -1
  63. package/dist/ui/App.js +2 -2
  64. package/dist/ui/App.js.map +1 -1
  65. package/dist/ui/hooks/useAgentLoop.d.ts +1 -1
  66. package/dist/ui/hooks/useAgentLoop.js +10 -1
  67. package/dist/ui/hooks/useAgentLoop.js.map +1 -1
  68. package/dist/utils/git.d.ts +7 -0
  69. package/dist/utils/git.js +12 -1
  70. package/dist/utils/git.js.map +1 -1
  71. package/package.json +12 -12
@@ -48,7 +48,7 @@ import { decidePlanStepCompaction, DEFAULT_CACHE_WRITE_READ_RATIO, PLAN_STEP_KEE
48
48
  import { extractPlanSteps, findCompletedMarkers } from "../utils/plan-steps.js";
49
49
  import { readFileSync } from "node:fs";
50
50
  import { clampThinkingForPlanMode } from "./thinking-level.js";
51
- import { pruneMinimumTokens, pruneStaleToolResults, shouldPruneToolResults, } from "./compaction/tool-result-pruner.js";
51
+ import { pruneMinimumTokens, pruneStaleToolResults, shouldPruneToolResults, stablePrefixEnd, } from "./compaction/tool-result-pruner.js";
52
52
  import { discoverAgents } from "./agents.js";
53
53
  import { enhancePrompt } from "../utils/prompt-enhancer.js";
54
54
  import { assistantText, renderTranscript } from "./claude-code/events.js";
@@ -57,7 +57,7 @@ import { CLAUDE_CODE_SEED_CHARS, CLAUDE_CODE_SESSION_KIND, claudeCodeResumeId, c
57
57
  import { claudeCodeComplete, resolveClaudeCodeProcess, } from "./claude-code/complete.js";
58
58
  import { detectLanguages, detectProjectStack } from "./language-detector.js";
59
59
  import { buildLoopBreakMessage } from "./loop-breaker.js";
60
- import { buildRegroundingMessage, requestTextForRegrounding } from "./regrounding.js";
60
+ import { buildRegroundingMessage, recordUserDecision, requestTextForRegrounding, } from "./regrounding.js";
61
61
  import { buildSemanticLoopJudgePrompt, buildSemanticLoopMessage, parseSemanticLoopVerdict, SEMANTIC_LOOP_JUDGE_TIMEOUT_MS, withJudgeTimeout, } from "./semantic-loop-check.js";
62
62
  import { buildEnvDeltaMessage, buildLanguageUpdateMessage } from "./env-delta.js";
63
63
  import { buildUserShellContextText } from "./user-shell-context.js";
@@ -66,6 +66,7 @@ import { listProjectFiles } from "./project-files.js";
66
66
  import { wrapSteeringText, buildNotificationSteeringText, buildIdleWakeNotificationText, STEERING_PREFIX, } from "./steering.js";
67
67
  import { AgentNotificationQueue } from "./agent-notifications.js";
68
68
  import { VerificationGate, VERIFICATION_STATE_KIND } from "./verification-gate.js";
69
+ import { CHECKOUT_RECORD_KIND, latestCheckoutRecord, } from "./checkout-record.js";
69
70
  import { findUserSessionPrompt, getUserSessionPrompt } from "./session-preview.js";
70
71
  import { normalizeMessageImages } from "./message-images.js";
71
72
  import { loadStreamRules } from "./stream-rules.js";
@@ -314,9 +315,15 @@ export class AgentSession {
314
315
  deferredCompactionPending = false;
315
316
  /** Latest provider count, anchored to the assistant response it measured. */
316
317
  providerContext = null;
318
+ /** Where the last prune made history stable; becomes the cache anchor on the next step. */
319
+ pendingCacheAnchor = null;
320
+ /** The message currently carrying `cacheAnchor` (see applyPendingCacheAnchor). */
321
+ cacheAnchored = null;
317
322
  /** See {@link toolDefinitionChars}. */
318
323
  toolCharsCache = null;
319
324
  originalRequest = "";
325
+ /** The user's own ask_user answers this run; they scope the pinned request. */
326
+ runUserDecisions = [];
320
327
  // Messages queued by the user while a run is in flight. Drained at the
321
328
  // mid-loop steering boundary (user steering wins over the hooks), mirroring
322
329
  // the TUI's getSteeringMessages. Each entry carries its own attachments so a
@@ -374,6 +381,8 @@ export class AgentSession {
374
381
  * transport-specific windows (e.g. OpenAI Codex OAuth's smaller window)
375
382
  * without re-resolving credentials on every poll. */
376
383
  lastAccountId;
384
+ /** The branch and checkout this conversation is on (core/checkout-record.ts). */
385
+ checkoutRecord = null;
377
386
  baseUrl;
378
387
  maxTokens;
379
388
  thinkingLevel;
@@ -570,6 +579,7 @@ export class AgentSession {
570
579
  }),
571
580
  getPackageCooldownDays: () => this.settingsManager.get("packageCooldownDays"),
572
581
  getBashPath: () => this.settingsManager.get("bashPath"),
582
+ getCheckoutSharers: this.opts.getCheckoutSharers,
573
583
  getNetworkPolicy: () => ({
574
584
  mode: this.settingsManager.get("networkMode"),
575
585
  allow: this.settingsManager.get("networkAllow"),
@@ -1093,19 +1103,7 @@ export class AgentSession {
1093
1103
  accountId: creds?.accountId,
1094
1104
  approvedPlanPath: this.approvedPlanPath,
1095
1105
  });
1096
- let activeTokens;
1097
- if (this.providerContext) {
1098
- const anchorIndex = this.messages.lastIndexOf(this.providerContext.anchor);
1099
- if (anchorIndex >= 0) {
1100
- activeTokens = calculateActiveContextTokens(this.messages, {
1101
- usage: this.providerContext.usage,
1102
- pendingMessages: this.messages.slice(anchorIndex + 1),
1103
- });
1104
- }
1105
- else {
1106
- this.providerContext = null;
1107
- }
1108
- }
1106
+ const activeTokens = this.idleActiveContextTokens();
1109
1107
  log("INFO", "compaction", "Pre-run compaction decision", {
1110
1108
  provider: this.provider,
1111
1109
  model: this.model,
@@ -1118,8 +1116,7 @@ export class AgentSession {
1118
1116
  try {
1119
1117
  await this.compact(creds, "automatic");
1120
1118
  if (this.lastCompactionCompacted) {
1121
- // Re-grounding hook keys off this — the context was just summarized.
1122
- this.compactionOccurred = true;
1119
+ this.markCompacted();
1123
1120
  this.compactionRetryAfter = 0;
1124
1121
  }
1125
1122
  else {
@@ -1634,6 +1631,12 @@ export class AgentSession {
1634
1631
  this.compactionOccurred = true;
1635
1632
  }
1636
1633
  this.originalRequest = originalRequest;
1634
+ this.runUserDecisions = [];
1635
+ }
1636
+ /** The context was just summarized: arm a fresh re-ground note, even if one already ran this run. */
1637
+ markCompacted() {
1638
+ this.compactionOccurred = true;
1639
+ this.regroundingInjected = false;
1637
1640
  }
1638
1641
  /**
1639
1642
  * Fold one agent event into the hook stat accumulators. Pure bookkeeping —
@@ -1664,6 +1667,9 @@ export class AgentSession {
1664
1667
  if (safetyRule)
1665
1668
  this.recordSafetyBlock(safetyRule, name, args, event.details);
1666
1669
  this.loopMonitor.recordToolEnd(name, args, event.result, event.isError);
1670
+ if (name === "ask_user" && !event.isError) {
1671
+ this.runUserDecisions = recordUserDecision(this.runUserDecisions, event.result);
1672
+ }
1667
1673
  const verificationChanged = await this.verificationTracker.recordToolCallEnd(event, call, this.planModeRef.current);
1668
1674
  if (verificationChanged)
1669
1675
  await this.persistVerificationState();
@@ -1907,7 +1913,7 @@ export class AgentSession {
1907
1913
  if (!this.regroundingInjected && this.compactionOccurred) {
1908
1914
  this.regroundingInjected = true;
1909
1915
  this.eventBus.emit("hook", { kind: "regrounding" });
1910
- return [buildRegroundingMessage(this.originalRequest)];
1916
+ return [buildRegroundingMessage(this.originalRequest, this.runUserDecisions)];
1911
1917
  }
1912
1918
  return null;
1913
1919
  }
@@ -2452,32 +2458,21 @@ export class AgentSession {
2452
2458
  };
2453
2459
  let activeTokens = measureActiveTokens();
2454
2460
  // Cheap stale-tool-output pruning before the expensive LLM
2455
- // compaction check, once the context is big enough for the freed
2456
- // tokens to be worth a cache rewrite. In-place mutation preserves
2457
- // anchors; drop the retained usage afterwards since it counted the
2458
- // pruned content.
2459
- if (shouldPruneToolResults(activeTokens, policy.targetTokens)) {
2460
- const cacheCold = this.getCacheExpiryStatus()?.expired ?? false;
2461
- const pruneResult = pruneStaleToolResults(messages, {
2462
- minimumTokens: pruneMinimumTokens(activeTokens, cacheCold, policy.targetTokens),
2463
- });
2464
- if (pruneResult.pruned) {
2465
- this.cacheDiagnostics.noteEdit("tool_prune", pruneResult.freedTokens);
2466
- this.providerContext = null;
2467
- log("INFO", "compaction", "Pruned stale tool outputs", {
2468
- prunedResults: String(pruneResult.prunedResults),
2469
- compactedToolCalls: String(pruneResult.compactedToolCalls),
2470
- freedTokens: String(pruneResult.freedTokens),
2471
- });
2472
- // The measured size counted the pruned content, so take the
2473
- // freed tokens off it. Never swap the provider's count for a
2474
- // whole-history estimate here: that estimate rides a shared
2475
- // chars-per-token ratio, and it once read a 234K-token MiMo
2476
- // context (23% of 1M) as ~400K and compacted it against a 340K
2477
- // trigger.
2478
- activeTokens = Math.max(0, activeTokens - pruneResult.freedTokens);
2479
- }
2480
- }
2461
+ // compaction check (see pruneToolOutputsIfDue). First move the
2462
+ // cache anchor the last prune left pending, never in the request
2463
+ // that pruned: that one still reads through the previous anchor.
2464
+ // The new anchor's cache entry is created by reading the previous
2465
+ // request's tail, so a prune in this same step (which edits history
2466
+ // before that tail) waits one step.
2467
+ const freedTokens = this.applyPendingCacheAnchor(messages)
2468
+ ? 0
2469
+ : this.pruneToolOutputsIfDue(messages, activeTokens, policy.targetTokens);
2470
+ // The measured size counted the pruned content, so take the freed
2471
+ // tokens off it. Never swap the provider's count for a
2472
+ // whole-history estimate here: that estimate rides a shared
2473
+ // chars-per-token ratio, and it once read a 234K-token MiMo context
2474
+ // (23% of 1M) as ~400K and compacted it against a 340K trigger.
2475
+ activeTokens = Math.max(0, activeTokens - freedTokens);
2481
2476
  if (Date.now() < this.compactionRetryAfter)
2482
2477
  return messages;
2483
2478
  // An approved plan runs as ONE run, so step boundaries are only
@@ -2523,7 +2518,7 @@ export class AgentSession {
2523
2518
  return messages;
2524
2519
  }
2525
2520
  this.compactionRetryAfter = 0;
2526
- this.compactionOccurred = true;
2521
+ this.markCompacted();
2527
2522
  return this.messages;
2528
2523
  },
2529
2524
  });
@@ -2832,6 +2827,7 @@ export class AgentSession {
2832
2827
  this.currentLeafId = loaded.header.leafId;
2833
2828
  this.setSessionPath(loaded.path);
2834
2829
  this.markers.restore(loaded.entries, loaded.header.leafId);
2830
+ this.checkoutRecord = latestCheckoutRecord(loaded.entries) ?? this.checkoutRecord;
2835
2831
  this.lastPersistedIndex = this.messages.length;
2836
2832
  this.providerContext = null;
2837
2833
  await this.subAgentManager?.rebindParentSession(this.sessionId);
@@ -2873,6 +2869,8 @@ export class AgentSession {
2873
2869
  this.lastPersistedIndex = this.messages.length;
2874
2870
  await this.markers.rePersistAll();
2875
2871
  await this.persistVerificationState();
2872
+ // A compaction checkpoint is a new file: the conversation's branch must follow it.
2873
+ await this.persistCheckoutRecord();
2876
2874
  await this.persistAppMarker("compaction", {
2877
2875
  originalCount: result.originalCount,
2878
2876
  newCount: result.newCount,
@@ -3732,6 +3730,16 @@ export class AgentSession {
3732
3730
  listBackgroundProcesses() {
3733
3731
  return this.processManager?.list() ?? [];
3734
3732
  }
3733
+ /**
3734
+ * Start a background process on the host's behalf (a new worktree's setup),
3735
+ * listed with the agent's own background tasks. Null without a process manager.
3736
+ */
3737
+ async startBackgroundProcess(command, cwd = this.cwd) {
3738
+ if (!this.processManager)
3739
+ return null;
3740
+ const started = await this.processManager.start(command, cwd);
3741
+ return { id: started.id, pid: started.pid };
3742
+ }
3735
3743
  /** Stop a background process by id. Returns a human-readable status string. */
3736
3744
  async killBackgroundProcess(id) {
3737
3745
  if (!this.processManager)
@@ -4248,6 +4256,42 @@ export class AgentSession {
4248
4256
  data: this.opts.completionReview.snapshot(),
4249
4257
  });
4250
4258
  }
4259
+ /**
4260
+ * A chat row saying where this conversation now works ("Opened on branch x in
4261
+ * its own worktree"), live and on every later restore of the transcript.
4262
+ */
4263
+ noteCheckout(text) {
4264
+ this.eventBus.emit("checkout_notice", { text });
4265
+ void this.persistAppMarker("checkout", { text }).catch(() => { });
4266
+ }
4267
+ /** The branch and checkout this conversation last recorded, or null. */
4268
+ getCheckoutRecord() {
4269
+ return this.checkoutRecord;
4270
+ }
4271
+ /**
4272
+ * Remember the branch this conversation is on, so resuming it later opens
4273
+ * that branch (see core/checkout-record.ts). Unchanged records write nothing.
4274
+ */
4275
+ async recordCheckout(record) {
4276
+ const previous = this.checkoutRecord;
4277
+ if (previous?.branch === record.branch && previous.cwd === record.cwd)
4278
+ return;
4279
+ this.checkoutRecord = { ...record };
4280
+ await this.persistCheckoutRecord();
4281
+ }
4282
+ async persistCheckoutRecord() {
4283
+ if (!this.sessionPath || !this.checkoutRecord)
4284
+ return;
4285
+ const entry = {
4286
+ type: "custom",
4287
+ kind: CHECKOUT_RECORD_KIND,
4288
+ id: crypto.randomUUID(),
4289
+ parentId: null,
4290
+ timestamp: new Date().toISOString(),
4291
+ data: { ...this.checkoutRecord },
4292
+ };
4293
+ await this.sessionManager.appendEntry(this.sessionPath, entry);
4294
+ }
4251
4295
  async persistVerificationState() {
4252
4296
  if (this.opts.completionReview)
4253
4297
  await this.persistCompletionReviewState();
@@ -4439,6 +4483,106 @@ export class AgentSession {
4439
4483
  }
4440
4484
  /** This chat's running Claude Code process, reused while `key` (its start settings) matches. */
4441
4485
  claudeCodeLive = null;
4486
+ /**
4487
+ * Context size between runs: the last provider usage plus messages appended
4488
+ * after it, or undefined when there is no usable sample (callers estimate).
4489
+ * Same measurement the pre-run compaction check makes.
4490
+ */
4491
+ idleActiveContextTokens() {
4492
+ if (!this.providerContext)
4493
+ return undefined;
4494
+ const anchorIndex = this.messages.lastIndexOf(this.providerContext.anchor);
4495
+ if (anchorIndex < 0) {
4496
+ this.providerContext = null;
4497
+ return undefined;
4498
+ }
4499
+ return calculateActiveContextTokens(this.messages, {
4500
+ usage: this.providerContext.usage,
4501
+ pendingMessages: this.messages.slice(anchorIndex + 1),
4502
+ });
4503
+ }
4504
+ /**
4505
+ * Prune stale tool outputs in place once the context is big enough for the
4506
+ * freed tokens to be worth a cache rewrite (a larger share on a warm cache,
4507
+ * see pruneMinimumTokens). In-place mutation preserves usage anchors; the
4508
+ * retained usage is dropped since it counted the pruned content. Shared by
4509
+ * the in-flight context transform and prewarm so both send the same prefix.
4510
+ * Returns the freed tokens (0 when nothing was pruned).
4511
+ */
4512
+ pruneToolOutputsIfDue(messages, activeTokens, targetTokens) {
4513
+ if (!shouldPruneToolResults(activeTokens, targetTokens))
4514
+ return 0;
4515
+ const cacheCold = this.getCacheExpiryStatus()?.expired ?? false;
4516
+ const pruneResult = pruneStaleToolResults(messages, {
4517
+ minimumTokens: pruneMinimumTokens(activeTokens, cacheCold, targetTokens),
4518
+ });
4519
+ if (!pruneResult.pruned)
4520
+ return 0;
4521
+ this.cacheDiagnostics.noteEdit("tool_prune", pruneResult.freedTokens);
4522
+ this.providerContext = null;
4523
+ this.pendingCacheAnchor = stablePrefixEnd(messages) ?? null;
4524
+ log("INFO", "compaction", "Pruned stale tool outputs", {
4525
+ prunedResults: String(pruneResult.prunedResults),
4526
+ compactedToolCalls: String(pruneResult.compactedToolCalls),
4527
+ freedTokens: String(pruneResult.freedTokens),
4528
+ });
4529
+ return pruneResult.freedTokens;
4530
+ }
4531
+ /**
4532
+ * Mark where the last prune made history stable (`Message.cacheAnchor`), so
4533
+ * the provider can keep a cache breakpoint there. Without it every prune on a
4534
+ * 5-min route re-sent everything after the last entry the tail's lookback
4535
+ * finds; in live sessions a prune freed ~24K tokens and re-wrote ~400K. gg-ai
4536
+ * decides per route whether the hint is used (not on 1-h routes). Returns
4537
+ * true when the anchor moved.
4538
+ */
4539
+ applyPendingCacheAnchor(messages) {
4540
+ const next = this.pendingCacheAnchor;
4541
+ this.pendingCacheAnchor = null;
4542
+ if (!next || next === this.cacheAnchored || !messages.includes(next))
4543
+ return false;
4544
+ if (this.cacheAnchored)
4545
+ delete this.cacheAnchored.cacheAnchor;
4546
+ next.cacheAnchor = true;
4547
+ this.cacheAnchored = next;
4548
+ return true;
4549
+ }
4550
+ /**
4551
+ * Apply the next request's context policy before warming: report when its
4552
+ * pre-run check will compact, otherwise prune now exactly as its first model
4553
+ * step would. The cache is cold here (prewarm only runs once it has lapsed),
4554
+ * so the prune uses the cold-cache floor, as the request would without the
4555
+ * prewarm; afterwards the warm cache's larger floor keeps that request from
4556
+ * pruning again. Prewarm is Anthropic-only, so the cached account id never
4557
+ * changes the window.
4558
+ */
4559
+ prepareContextForPrewarm() {
4560
+ if (!this.settingsManager.get("autoCompact"))
4561
+ return "ready";
4562
+ // A post-turn compaction is about to replace this history.
4563
+ if (this.postTurnCompaction)
4564
+ return "compaction_due";
4565
+ const contextWindow = getContextWindow(this.model, {
4566
+ provider: this.provider,
4567
+ accountId: this.lastAccountId,
4568
+ });
4569
+ const policy = resolveCompactionPolicy({
4570
+ provider: this.provider,
4571
+ model: this.model,
4572
+ contextWindow,
4573
+ threshold: this.settingsManager.get("compactThreshold"),
4574
+ compactAtTokens: this.settingsManager.get("compactAtTokens"),
4575
+ accountId: this.lastAccountId,
4576
+ approvedPlanPath: this.approvedPlanPath,
4577
+ });
4578
+ const activeTokens = this.idleActiveContextTokens();
4579
+ if (Date.now() >= this.compactionRetryAfter &&
4580
+ shouldCompact(this.messages, contextWindow, policy.threshold, activeTokens, policy.targetTokens)) {
4581
+ return "compaction_due";
4582
+ }
4583
+ this.pruneToolOutputsIfDue(this.messages, activeTokens ?? calculateActiveContextTokens(this.messages), policy.targetTokens);
4584
+ return "ready";
4585
+ }
4442
4586
  /**
4443
4587
  * Best-effort Anthropic prompt-cache prewarm before the user's next turn
4444
4588
  * (desktop app calls this on the first keystroke after opening a chat or an
@@ -4476,6 +4620,16 @@ export class AgentSession {
4476
4620
  return { ok: false, reason: "run_active" };
4477
4621
  if (this.prewarmController)
4478
4622
  return { ok: false, reason: "in_flight" };
4623
+ // Warm what the next request will actually send. Its pre-run check compacts
4624
+ // an over-trigger history (rewriting the whole prefix, so warming now is
4625
+ // waste), and its first model step prunes stale tool outputs when due:
4626
+ // apply that same in-place prune now, so the request finds nothing left to
4627
+ // prune and the warmed prefix matches it. Measured with a live A/B: a 700K
4628
+ // session wrote its full history at the 1-h price here, then rewrote it on
4629
+ // the very next request.
4630
+ if (this.prepareContextForPrewarm() === "compaction_due") {
4631
+ return { ok: false, reason: "compaction_due" };
4632
+ }
4479
4633
  // End at the last user/tool message: the next real turn appends a new user
4480
4634
  // message after the trailing assistant reply, and its cache lookback hits
4481
4635
  // the entry written at this boundary. A request must end on a user turn.
@@ -4699,6 +4853,7 @@ export class AgentSession {
4699
4853
  }
4700
4854
  this.opts.completionReview?.restore(savedCompletionReview?.type === "custom" ? savedCompletionReview.data : null);
4701
4855
  this.verificationTracker.clearBackground();
4856
+ this.checkoutRecord = latestCheckoutRecord(loaded.entries);
4702
4857
  if (savedVerification?.type === "custom") {
4703
4858
  this.verificationGate.restore(savedVerification.data);
4704
4859
  }
@@ -4854,12 +5009,14 @@ export class AgentSession {
4854
5009
  if (!this.sessionPath)
4855
5010
  return;
4856
5011
  const entryId = crypto.randomUUID();
5012
+ // The cache-anchor hint only holds for the live run; never store it.
5013
+ const { cacheAnchor: _cacheAnchor, ...stored } = message;
4857
5014
  const entry = {
4858
5015
  type: "message",
4859
5016
  id: entryId,
4860
5017
  parentId: this.currentLeafId,
4861
5018
  timestamp: new Date().toISOString(),
4862
- message,
5019
+ message: stored,
4863
5020
  };
4864
5021
  await this.sessionManager.appendEntry(this.sessionPath, entry);
4865
5022
  this.currentLeafId = entryId;