@cortexkit/pi-magic-context 0.49.86 → 0.49.89

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 (41) hide show
  1. package/dist/auto-search-worker.js +13 -7
  2. package/dist/chunk-embedding-write-worker.js +6 -6
  3. package/dist/{compartment-chunk-embedding-avkyp2df.js → compartment-chunk-embedding-7pzb51r4.js} +3 -1
  4. package/dist/{embedding-backfill-7a01ns95.js → embedding-backfill-yydkxhrp.js} +8 -8
  5. package/dist/{embedding-cache-7rp4gqzr.js → embedding-cache-xft42rsb.js} +5 -1
  6. package/dist/embedding-worker.js +2 -2
  7. package/dist/{index-cxczethe.js → index-464qhgjp.js} +4 -4
  8. package/dist/{index-hpbdnbtf.js → index-68tyan5e.js} +8 -2
  9. package/dist/{index-7yz95h83.js → index-6x595qtk.js} +76 -13
  10. package/dist/{index-29nw7n1r.js → index-70sw39ck.js} +1 -1
  11. package/dist/{index-53fgdt6n.js → index-7xsbhw6m.js} +1 -1
  12. package/dist/{index-ex9te7tc.js → index-aahd8x9s.js} +1 -1
  13. package/dist/{index-rqdjb6j3.js → index-fsjsvq78.js} +1 -1
  14. package/dist/{index-fvfq9gva.js → index-hp320128.js} +1 -1
  15. package/dist/{index-yhzhdp3m.js → index-hrwc50n3.js} +48 -1
  16. package/dist/{index-fd57gfnn.js → index-hs862sjk.js} +3 -3
  17. package/dist/{index-7thk2cwt.js → index-jhsypxe9.js} +3 -0
  18. package/dist/{index-94z1xzmr.js → index-kezt62gs.js} +1 -1
  19. package/dist/{index-wy6h2wn2.js → index-kn83b37d.js} +5 -5
  20. package/dist/{index-5n3bqhp9.js → index-ndprcb9x.js} +25 -16
  21. package/dist/{index-0t9xfj3x.js → index-qpdh2aff.js} +1 -1
  22. package/dist/{index-bjr11ay6.js → index-qtfp61mq.js} +4 -4
  23. package/dist/{index-8x8wtn3t.js → index-rrm9ce0j.js} +108 -13
  24. package/dist/{index-gbc29ysq.js → index-rzwcmbww.js} +1 -1
  25. package/dist/{index-sqp84q6s.js → index-w48rf3j6.js} +2 -2
  26. package/dist/{index-8631kxcp.js → index-z2bdsba1.js} +14 -14
  27. package/dist/index.js +397 -135
  28. package/dist/{message-index-bounded-sra4jpac.js → message-index-bounded-vxf4ez55.js} +2 -2
  29. package/dist/migration-worker.js +4 -4
  30. package/dist/{project-embedding-registry-agkd7egh.js → project-embedding-registry-f9tzr12g.js} +7 -7
  31. package/dist/raw-ordinal-warmup-worker.js +3 -3
  32. package/dist/{read-session-chunk-wek7gb7j.js → read-session-chunk-tec7t4vy.js} +1 -1
  33. package/dist/{render-rphfegr8.js → render-mr2bb4yf.js} +9 -9
  34. package/dist/{rpc-notifications-889zvhn2.js → rpc-notifications-qc5ha504.js} +1 -1
  35. package/dist/{search-archive-7p43e77j.js → search-archive-abtztrw5.js} +3 -3
  36. package/dist/{search-rdvsnxky.js → search-rdqrskte.js} +14 -14
  37. package/dist/{storage-memory-0ndn65fm.js → storage-memory-2sed597w.js} +2 -2
  38. package/dist/subagent-entry.js +19 -19
  39. package/dist/tag-snapshot-worker-pi.js +4 -4
  40. package/dist/{v2-archive-reader-qc4c9wrp.js → v2-archive-reader-qaecyb4y.js} +1 -1
  41. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -166,7 +166,7 @@ import {
166
166
  registerTodoStateLifecycle,
167
167
  syncCtxMemoryToolEnabled,
168
168
  registerMagicContextTools
169
- } from "./index-8631kxcp.js";
169
+ } from "./index-z2bdsba1.js";
170
170
  import"./index-4knyh1kt.js";
171
171
  import {
172
172
  piHarnessKindFromExecutable,
@@ -174,7 +174,7 @@ import {
174
174
  ensureStorageDirectorySync,
175
175
  writeStorageFileSync,
176
176
  writeStorageFileAtomicSync
177
- } from "./index-8x8wtn3t.js";
177
+ } from "./index-rrm9ce0j.js";
178
178
  import {
179
179
  canonicalModelIdentity,
180
180
  piModelRefToCanonical,
@@ -217,7 +217,7 @@ import {
217
217
  import {
218
218
  EMBEDDING_WORKER_STOP_MAX_MS,
219
219
  getCachedLocalEmbeddingPooling
220
- } from "./index-rqdjb6j3.js";
220
+ } from "./index-fsjsvq78.js";
221
221
  import {
222
222
  pruneMissingProjectIdentities,
223
223
  setHomeProjectPermission,
@@ -230,7 +230,7 @@ import {
230
230
  resolveProjectIdentityForSession,
231
231
  beginBootQuietPeriod,
232
232
  scheduleAfterBootQuiet
233
- } from "./index-94z1xzmr.js";
233
+ } from "./index-kezt62gs.js";
234
234
  import {
235
235
  detectThinkingBindingMismatch,
236
236
  detectLatestTurnThinkingMismatch,
@@ -593,7 +593,7 @@ import {
593
593
  getSourceContents,
594
594
  recordSubagentInvocation,
595
595
  getLatestHistorianInvocationId
596
- } from "./index-bjr11ay6.js";
596
+ } from "./index-qtfp61mq.js";
597
597
  import {
598
598
  resolveOpenCodeDbPath,
599
599
  assertOpenCodeStoreGeneration,
@@ -654,12 +654,13 @@ import {
654
654
  primeInMemoryTailRawMessageCache2,
655
655
  readRawSessionMessageIdOrdinalsForRange2,
656
656
  hasRawSessionMessageById2,
657
+ readRawSessionMessageOrdinalById2,
657
658
  compareRawSessionMessageOrder2,
658
659
  getRawSessionMessageCount2,
659
660
  getRawSessionTagKeysThrough2,
660
661
  getLegacyProtectedTailStartOrdinal2,
661
662
  readSessionChunk2
662
- } from "./index-hpbdnbtf.js";
663
+ } from "./index-68tyan5e.js";
663
664
  import"./index-ddfjg278.js";
664
665
  import {
665
666
  formatSynapseLaneDescriptor
@@ -674,7 +675,7 @@ import {
674
675
  replaceCompartmentChunkEmbeddings2,
675
676
  deleteChunkEmbedBackoffForSession2,
676
677
  chunkWindowSourceKey2
677
- } from "./index-cxczethe.js";
678
+ } from "./index-464qhgjp.js";
678
679
  import {
679
680
  recordSessionProjectIdentity,
680
681
  GIT_SWEEP_LEASE_RENEWAL_MS,
@@ -683,7 +684,7 @@ import {
683
684
  markGitSweepSuccessAndRelease,
684
685
  parkGitSweepNonIndexable,
685
686
  releaseGitSweepLease
686
- } from "./index-ex9te7tc.js";
687
+ } from "./index-aahd8x9s.js";
687
688
  import {
688
689
  embedPauseBySession,
689
690
  embedRunStateBySession,
@@ -699,7 +700,7 @@ import {
699
700
  clearCompressionDepthRange,
700
701
  cleanSearchText,
701
702
  matchedSearchSnippet
702
- } from "./index-0t9xfj3x.js";
703
+ } from "./index-qpdh2aff.js";
703
704
  import {
704
705
  getErrorMessage,
705
706
  describeError,
@@ -716,7 +717,7 @@ import {
716
717
  openCurrentDatabase,
717
718
  openDatabaseAsync,
718
719
  closeDatabase
719
- } from "./index-7yz95h83.js";
720
+ } from "./index-6x595qtk.js";
720
721
  import {
721
722
  rememberV1HiddenRun
722
723
  } from "./index-6x556c2q.js";
@@ -731,7 +732,7 @@ import {
731
732
  expandWorkspaceIdentitySetWithAliases,
732
733
  sourceNameForMemory,
733
734
  computeWorkspaceEpochFingerprint
734
- } from "./index-53fgdt6n.js";
735
+ } from "./index-7xsbhw6m.js";
735
736
  import {
736
737
  configureContextDatabasePragmas2
737
738
  } from "./index-fapenpch.js";
@@ -756,7 +757,7 @@ import {
756
757
  createPrimer,
757
758
  updatePrimerSupport,
758
759
  updatePrimerAnswer
759
- } from "./index-gbc29ysq.js";
760
+ } from "./index-rzwcmbww.js";
760
761
  import {
761
762
  setEmbeddingSessionBusy2,
762
763
  isEmbeddingHostBusy2
@@ -782,13 +783,13 @@ import {
782
783
  archiveMemory2,
783
784
  getMemoryCount2,
784
785
  getMemoryCountsByStatus2
785
- } from "./index-29nw7n1r.js";
786
+ } from "./index-70sw39ck.js";
786
787
  import {
787
788
  invalidateMemory2
788
- } from "./index-yhzhdp3m.js";
789
+ } from "./index-hrwc50n3.js";
789
790
  import {
790
791
  pushNotification2
791
- } from "./index-7thk2cwt.js";
792
+ } from "./index-jhsypxe9.js";
792
793
  import {
793
794
  describeShadowBackfillWriteRefusal2,
794
795
  contentSha2562,
@@ -806,7 +807,7 @@ import {
806
807
  embedSessionCompartmentChunks2,
807
808
  getEmbeddingCoverageStatus2,
808
809
  getAutoEmbeddingSessionCoverage2
809
- } from "./index-wy6h2wn2.js";
810
+ } from "./index-kn83b37d.js";
810
811
  import {
811
812
  USER_FACING_FAILURES,
812
813
  renderUserFacingFailure,
@@ -841,8 +842,8 @@ import {
841
842
  scheduleClearAndReindex,
842
843
  clearSessionTracking,
843
844
  createAutoSearchDiagnostics
844
- } from "./index-5n3bqhp9.js";
845
- import"./index-sqp84q6s.js";
845
+ } from "./index-ndprcb9x.js";
846
+ import"./index-w48rf3j6.js";
846
847
  import"./index-3s39a1md.js";
847
848
  import {
848
849
  DREAMER_PRIMER_INVESTIGATOR_ALLOWED_TOOLS,
@@ -875,8 +876,8 @@ import {
875
876
  } from "./index-pdrberjp.js";
876
877
  import"./index-71rg8j43.js";
877
878
  import"./index-8d2z6503.js";
878
- import"./index-fd57gfnn.js";
879
- import"./index-fvfq9gva.js";
879
+ import"./index-hs862sjk.js";
880
+ import"./index-hp320128.js";
880
881
  import {
881
882
  __toESM
882
883
  } from "./index-22jkk6wg.js";
@@ -3623,7 +3624,7 @@ function startHostStallProfilerSwitch() {
3623
3624
  // package.json
3624
3625
  var package_default = {
3625
3626
  name: "@cortexkit/pi-magic-context",
3626
- version: "0.49.86",
3627
+ version: "0.49.89",
3627
3628
  type: "module",
3628
3629
  description: "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
3629
3630
  main: "dist/index.js",
@@ -5167,6 +5168,10 @@ function hasLengthCappedOutput(value) {
5167
5168
  }
5168
5169
  return Object.values(value).some((item) => hasLengthCappedOutput(item));
5169
5170
  }
5171
+ function isLatestAssistantLengthCapped(messages) {
5172
+ const latest = getLatestAssistantMessage(messages);
5173
+ return hasLengthCappedOutput(latest?.info?.finish ? { finish: latest.info.finish } : null) || Array.isArray(latest?.parts) && latest.parts.some((part) => isRecord(part) && part.type === "step-finish" && hasLengthCappedOutput(part));
5174
+ }
5170
5175
  function describeAssistantSettlement(output) {
5171
5176
  if (isRecord(output) && isRecord(output.tokenLog)) {
5172
5177
  return `finish=${String(output.tokenLog.finish_reason ?? "unknown")}, reasoning=${typeof output.reasoning === "string" && output.reasoning.length > 0}`;
@@ -6177,6 +6182,24 @@ function messageId(message) {
6177
6182
  const id = infoOf(message).id;
6178
6183
  return typeof id === "string" ? id : null;
6179
6184
  }
6185
+ function inFlightAtAbort(messages, initialBaseline) {
6186
+ const reply = messages.slice().reverse().find((message) => {
6187
+ const id = messageId(message);
6188
+ return id !== null && !initialBaseline.has(id) && infoOf(message).role === "assistant";
6189
+ });
6190
+ const parts = reply?.parts;
6191
+ const ids = new Set;
6192
+ if (Array.isArray(parts)) {
6193
+ for (const part of parts) {
6194
+ if (part?.type !== "tool" || typeof part.callID !== "string")
6195
+ continue;
6196
+ const state = part.state;
6197
+ if (state?.status === "pending" || state?.status === "running" || state?.status === "error" && state.error === "Tool execution aborted" && state.metadata?.interrupted === true)
6198
+ ids.add(part.callID);
6199
+ }
6200
+ }
6201
+ return ids;
6202
+ }
6180
6203
  function recordedAssistantError(message) {
6181
6204
  const info = infoOf(message);
6182
6205
  if (info.error != null)
@@ -6401,7 +6424,7 @@ async function promptAsyncAndWaitForIdle(client, request, options = {}) {
6401
6424
  finalizing = true;
6402
6425
  sessionLog2(sessionId, "dreamer token budget: finalize fired", budget.snapshot());
6403
6426
  budgetAbortedSessions.add(sessionId);
6404
- registerBudgetFinalizeChild(sessionId, budget);
6427
+ const countRefusals = registerBudgetFinalizeChild(sessionId, budget);
6405
6428
  if (!session.abort)
6406
6429
  throw new DreamTokenBudgetExceeded(sessionId, budget.snapshot().spent);
6407
6430
  await session.abort({ path: { id: sessionId } });
@@ -6415,7 +6438,14 @@ async function promptAsyncAndWaitForIdle(client, request, options = {}) {
6415
6438
  if (await readStatus(session, sessionId, dir, signal) !== "idle") {
6416
6439
  throw new DreamTokenBudgetExceeded(sessionId, budget.snapshot().spent);
6417
6440
  }
6418
- completionBaseline = new Set((await readMessages(session, sessionId, dir, signal)).map(messageId).filter((value) => value !== null));
6441
+ const cancelled = await readMessages(session, sessionId, dir, signal);
6442
+ completionBaseline = new Set((cancelled.length ? cancelled : messages).map(messageId).filter((value) => value !== null));
6443
+ const exemptCallIds = inFlightAtAbort(cancelled, initialBaseline);
6444
+ countRefusals(exemptCallIds);
6445
+ sessionLog2(sessionId, "dreamer token budget: counting tool refusals", {
6446
+ snapshot: cancelled.length ? "read" : "unreadable",
6447
+ exemptCallIds: [...exemptCallIds]
6448
+ });
6419
6449
  const finalizeResponse = await session.promptAsync?.({
6420
6450
  ...request,
6421
6451
  body: {
@@ -19193,7 +19223,11 @@ async function runRetrospectiveTask(config, ctx, helpers) {
19193
19223
  });
19194
19224
  },
19195
19225
  validateOutput: (outputMessages) => {
19196
- const text = hiddenHandle ? outputMessages.text : extractLatestAssistantText(outputMessages);
19226
+ const completion = hiddenHandle ? outputMessages : null;
19227
+ if (completion ? completion.lengthCapped : isLatestAssistantLengthCapped(outputMessages)) {
19228
+ throw new Error("Retrospective child returned length-capped output");
19229
+ }
19230
+ const text = completion ? completion.text : extractLatestAssistantText(outputMessages);
19197
19231
  if (!text)
19198
19232
  throw new Error("Retrospective child returned no output.");
19199
19233
  return text;
@@ -21778,6 +21812,9 @@ class PiSubagentRunner {
21778
21812
  let lastEventTimestamp = 0;
21779
21813
  const accumulatedMessages = [];
21780
21814
  accountingMessages = accumulatedMessages;
21815
+ let finalizeDelivered = false;
21816
+ let exemptRepliesRemaining = 2;
21817
+ let preSteerToolCalls;
21781
21818
  const captureFinalAssistant = (messages) => {
21782
21819
  const result = extractFinalAssistant(messages);
21783
21820
  finalAssistantText = result.text;
@@ -21809,9 +21846,9 @@ class PiSubagentRunner {
21809
21846
  if (e.type === "agent_end" && Array.isArray(e.messages))
21810
21847
  mappingMessages = e.messages;
21811
21848
  }
21812
- if (rpcBudget && e.type === "response" && event.success === false) {
21849
+ if (rpcBudget && e.type === "response") {
21813
21850
  const reply = event;
21814
- if (reply.command === "prompt" || reply.command === "steer" && !sawAgentEnd) {
21851
+ if (reply.success === false && (reply.command === "prompt" || reply.command === "steer" && !sawAgentEnd)) {
21815
21852
  terminateChild(child);
21816
21853
  settle({
21817
21854
  ok: false,
@@ -21821,6 +21858,9 @@ class PiSubagentRunner {
21821
21858
  });
21822
21859
  return;
21823
21860
  }
21861
+ if (reply.success === true && reply.command === "steer" && reply.id === "dreamer-finalize" && reply.data?.disposition === "handled") {
21862
+ sessionLog2(options.accountingSessionId ?? "subagent", "Pi dreamer finalize: steer was handled by an input extension");
21863
+ }
21824
21864
  }
21825
21865
  telemetry.observe(event);
21826
21866
  if (budget && e.type === "message_end") {
@@ -21843,6 +21883,9 @@ class PiSubagentRunner {
21843
21883
  });
21844
21884
  return;
21845
21885
  }
21886
+ if (decision === "finalize" || preSteerToolCalls) {
21887
+ preSteerToolCalls = finalizeDelivered || exemptRepliesRemaining-- === 0 ? undefined : extractToolInvocations([message]);
21888
+ }
21846
21889
  if (decision === "finalize" && rpcBudget) {
21847
21890
  try {
21848
21891
  if (!budgetGuardFile)
@@ -21865,21 +21908,30 @@ class PiSubagentRunner {
21865
21908
  })}
21866
21909
  `);
21867
21910
  }
21911
+ } else if (preSteerToolCalls && message?.role === "user" && Array.isArray(message.content) && message.content.some((part) => {
21912
+ const text = part;
21913
+ return text?.type === "text" && text.text === TOKEN_BUDGET_FINALIZE_MESSAGE;
21914
+ })) {
21915
+ finalizeDelivered = true;
21868
21916
  }
21869
21917
  }
21870
21918
  const resultParts = event.result?.content;
21871
21919
  if (budget?.snapshot().finalizeFired && e.type === "tool_execution_end" && resultParts?.some((part) => part.text === TOKEN_BUDGET_TOOL_REFUSAL)) {
21872
- const refusal = budget.refuseTool();
21873
- if (refusal?.hardStopped) {
21874
- terminateChild(child);
21875
- settle({
21876
- ok: false,
21877
- reason: "token_budget",
21878
- error: "MC-D11: Pi dreamer made two calls after finalize",
21879
- durationMs: Date.now() - startTime,
21880
- meta: { tokenBudget: budget.snapshot() }
21881
- });
21882
- return;
21920
+ if (e.toolCallId && preSteerToolCalls?.has(e.toolCallId)) {
21921
+ sessionLog2(options.accountingSessionId ?? "subagent", "Pi dreamer finalize: refusal spared for a call issued before steer delivery was confirmed", { toolCallId: e.toolCallId });
21922
+ } else {
21923
+ const refusal = budget.refuseTool();
21924
+ if (refusal?.hardStopped) {
21925
+ terminateChild(child);
21926
+ settle({
21927
+ ok: false,
21928
+ reason: "token_budget",
21929
+ error: "MC-D11: Pi dreamer made two calls after finalize",
21930
+ durationMs: Date.now() - startTime,
21931
+ meta: { tokenBudget: budget.snapshot() }
21932
+ });
21933
+ return;
21934
+ }
21883
21935
  }
21884
21936
  }
21885
21937
  if (cap !== undefined && telemetry.steps > cap) {
@@ -27582,9 +27634,11 @@ function outgoingContextRefusal(estimate, limit, protectedToolTokens = 0) {
27582
27634
  }
27583
27635
  class EmergencyFailClosedError extends Error {
27584
27636
  code;
27637
+ noticeHandled;
27585
27638
  constructor(message, options) {
27586
27639
  super(message, options);
27587
27640
  this.code = options?.code ?? "EMERGENCY_FAIL_CLOSED";
27641
+ this.noticeHandled = options?.noticeHandled;
27588
27642
  this.name = "EmergencyFailClosedError";
27589
27643
  }
27590
27644
  }
@@ -30240,6 +30294,43 @@ var searchWorkers = new WeakMap;
30240
30294
  var liveSearchWorkers = new Set;
30241
30295
  var MAX_IDLE_SEARCH_WORKERS = 4;
30242
30296
  var SEARCH_WORKER_IDLE_MS = 5 * 60000;
30297
+ var MAX_SEARCH_WORKER_CACHE_TTL_MS = 60 * 60000;
30298
+ function scheduleSearchWorkerExpiry(db, slot) {
30299
+ const arm = (delay) => {
30300
+ slot.idleTimer = setTimeout(check, delay);
30301
+ slot.idleTimer.unref?.();
30302
+ };
30303
+ const check = () => {
30304
+ const now = Date.now();
30305
+ let expires = now;
30306
+ try {
30307
+ const read = db.prepare("SELECT cache_ttl, last_response_time FROM session_meta WHERE session_id = ?");
30308
+ for (const session of slot.searchedSessions) {
30309
+ const row = read.get(session);
30310
+ if (!row) {
30311
+ slot.searchedSessions.delete(session);
30312
+ continue;
30313
+ }
30314
+ if (!row.cache_ttl || !row.last_response_time || row.last_response_time > now)
30315
+ continue;
30316
+ let ttl;
30317
+ try {
30318
+ ttl = Math.min(parseCacheTtl(row.cache_ttl), MAX_SEARCH_WORKER_CACHE_TTL_MS);
30319
+ } catch {
30320
+ continue;
30321
+ }
30322
+ if (ttl <= SEARCH_WORKER_IDLE_MS)
30323
+ continue;
30324
+ expires = Math.max(expires, row.last_response_time + ttl);
30325
+ }
30326
+ } catch {}
30327
+ if (expires > now)
30328
+ arm(expires - now);
30329
+ else
30330
+ slot.dispose();
30331
+ };
30332
+ arm(SEARCH_WORKER_IDLE_MS);
30333
+ }
30243
30334
  var DETACHED_SEARCH_LIMIT_MS = 30000;
30244
30335
  var AUTO_SEARCH_WORKER_CLOSE_DEADLINE_MS = 2000;
30245
30336
  var workersCreated = 0;
@@ -30274,6 +30365,7 @@ async function acquireSearchWorker(db, key, entry, input, signal) {
30274
30365
  const shutdown = createWorkerShutdown(worker, "auto-search", AUTO_SEARCH_WORKER_CLOSE_DEADLINE_MS);
30275
30366
  slot = {
30276
30367
  worker,
30368
+ searchedSessions: new Set,
30277
30369
  dispose() {
30278
30370
  this.disposed = true;
30279
30371
  clearTimeout(this.idleTimer);
@@ -30442,8 +30534,8 @@ async function executeAutoSearchWorker(db, sessionId, projectPath, query, option
30442
30534
  if (dispose || !detachable)
30443
30535
  slot.dispose();
30444
30536
  else if (!slot.disposed) {
30445
- slot.idleTimer = setTimeout(() => slot.dispose(), SEARCH_WORKER_IDLE_MS);
30446
- slot.idleTimer.unref?.();
30537
+ slot.searchedSessions.add(sessionId);
30538
+ scheduleSearchWorkerExpiry(db, slot);
30447
30539
  }
30448
30540
  const free = slot.release;
30449
30541
  slot.busy = undefined;
@@ -34457,13 +34549,19 @@ function extractToastTitle(text) {
34457
34549
  }
34458
34550
  async function sendStatusNotification(_client, sessionId, text, params) {
34459
34551
  try {
34460
- const { pushNotification } = await importPluginModule(() => import("./rpc-notifications-889zvhn2.js"));
34461
- pushNotification("toast", {
34462
- title: extractToastTitle(text),
34552
+ const { pushLiveNotification, pushNotification } = await importPluginModule(() => import("./rpc-notifications-qc5ha504.js"));
34553
+ const toast = {
34554
+ title: params.toastTitle ?? extractToastTitle(text),
34463
34555
  message: text,
34464
- variant: inferToastVariant(text),
34556
+ variant: params.toastVariant ?? inferToastVariant(text),
34465
34557
  duration: params.toastDurationMs ?? 5000
34466
- }, sessionId);
34558
+ };
34559
+ if (params.liveOnly) {
34560
+ if (!pushLiveNotification("toast", toast, sessionId))
34561
+ return "skipped";
34562
+ } else {
34563
+ pushNotification("toast", toast, sessionId);
34564
+ }
34467
34565
  notifyDelivered(sessionId, params);
34468
34566
  return "sent";
34469
34567
  } catch (error) {
@@ -34479,15 +34577,47 @@ var lastHistorianAlertBySession2 = new Map;
34479
34577
  var loggedStoredValidationFailures = new Map;
34480
34578
  var STORED_COMPARTMENT_FAILURE_BACKOFF_MS = 30 * 60 * 1000;
34481
34579
 
34580
+ // ../plugin/src/shared/recomp-outcome.ts
34581
+ var RECOMP_PAUSED_HEADING = "## Magic Recomp — Paused";
34582
+
34583
+ // ../plugin/src/hooks/magic-context/compartment-runner-recomp-carry.ts
34584
+ function compartmentToInput(c, sequence) {
34585
+ return {
34586
+ sequence,
34587
+ startMessage: c.startMessage,
34588
+ endMessage: c.endMessage,
34589
+ startMessageId: c.startMessageId,
34590
+ endMessageId: c.endMessageId,
34591
+ startBlockIndex: c.startBlockIndex,
34592
+ endBlockIndex: c.endBlockIndex,
34593
+ title: c.title,
34594
+ content: c.content,
34595
+ p1: c.p1,
34596
+ p2: c.p2,
34597
+ p3: c.p3,
34598
+ p4: c.p4,
34599
+ importance: c.importance,
34600
+ episodeType: c.episodeType
34601
+ };
34602
+ }
34603
+
34482
34604
  // ../plugin/src/hooks/magic-context/compartment-runner-recomp.ts
34483
- function insertRecompCompartmentRows(db, sessionId, compartments, now) {
34484
- const stmt = db.prepare("INSERT INTO compartments (session_id, sequence, start_message, end_message, start_message_id, end_message_id, title, content, p1, p2, p3, p4, importance, episode_type, legacy, created_at, harness, start_block_index, end_block_index) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
34605
+ function insertRecompCompartmentRows(db, sessionId, compartments, now, carriedRows) {
34606
+ const stmt = db.prepare(`INSERT INTO compartments (session_id, sequence, start_message, end_message,
34607
+ start_message_id, end_message_id, title, content, p1, p2, p3, p4, importance,
34608
+ episode_type, legacy, created_at, harness, start_block_index, end_block_index, rebase_status)
34609
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
34485
34610
  for (const c of compartments) {
34486
34611
  const hasTiers = typeof c.p1 === "string" && c.p1.length > 0;
34487
- stmt.run(sessionId, c.sequence, c.startMessage, c.endMessage, c.startMessageId, c.endMessageId, c.title, c.content, c.p1 ?? null, c.p2 ?? null, c.p3 ?? null, c.p4 ?? null, typeof c.importance === "number" ? c.importance : 50, c.episodeType ?? null, hasTiers ? 0 : 1, now, getHarness2(), c.startBlockIndex ?? null, c.endBlockIndex ?? null);
34612
+ const carried = carriedRows?.get(c.sequence);
34613
+ stmt.run(sessionId, c.sequence, c.startMessage, c.endMessage, c.startMessageId, c.endMessageId, c.title, c.content, c.p1 ?? null, c.p2 ?? null, c.p3 ?? null, c.p4 ?? null, typeof c.importance === "number" ? c.importance : 50, c.episodeType ?? null, carried?.legacy ?? (hasTiers ? 0 : 1), now, getHarness2(), c.startBlockIndex ?? null, c.endBlockIndex ?? null, carried?.rebaseStatus ?? "ok");
34488
34614
  }
34489
34615
  }
34490
- function promoteRecompStagingWithM0Mutation(db, sessionId, holderId) {
34616
+ function promoteRecompStagingWithM0Mutation(db, sessionId, holderId, carriedRows) {
34617
+ const promoted = promoteRecompStaging(db, sessionId, holderId, undefined, carriedRows);
34618
+ return typeof promoted === "string" ? null : promoted;
34619
+ }
34620
+ function promoteRecompStaging(db, sessionId, holderId, stopped, carriedRows) {
34491
34621
  const now = Date.now();
34492
34622
  db.exec("BEGIN IMMEDIATE");
34493
34623
  const transactionStartedAt = performance.now();
@@ -34496,18 +34626,40 @@ function promoteRecompStagingWithM0Mutation(db, sessionId, holderId) {
34496
34626
  if (!isCompartmentLeaseHeld(db, sessionId, holderId)) {
34497
34627
  db.exec("ROLLBACK");
34498
34628
  finished = true;
34499
- return null;
34629
+ return "lease-lost";
34500
34630
  }
34501
34631
  const staging = getRecompStaging(db, sessionId);
34502
- if (!staging || staging.compartments.length === 0) {
34632
+ const staged = staging?.compartments.at(-1);
34633
+ if (!staging || !staged) {
34503
34634
  db.exec("ROLLBACK");
34504
34635
  finished = true;
34505
- return null;
34636
+ return "staging-removed";
34637
+ }
34638
+ let carried = null;
34639
+ if (stopped) {
34640
+ const live = readLiveRanges(db, sessionId);
34641
+ const stagedEnd = resolvedOrdinal(sessionId, staged.endMessageId) ?? staged.endMessage;
34642
+ if (live.some((row) => row.end > stagedEnd)) {
34643
+ if (stopped.allowCarry)
34644
+ carried = readAlignedLiveTail(db, sessionId, live, staging, stagedEnd);
34645
+ if (!carried) {
34646
+ if (stopped.discardIfShort) {
34647
+ clearRecompStaging(db, sessionId);
34648
+ db.exec("COMMIT");
34649
+ finished = true;
34650
+ return "discarded";
34651
+ }
34652
+ db.exec("ROLLBACK");
34653
+ finished = true;
34654
+ return "would-shrink";
34655
+ }
34656
+ }
34506
34657
  }
34658
+ const compartments = carried ? [...staging.compartments, ...carried.compartments] : staging.compartments;
34507
34659
  deleteChunkEmbedBackoffForSession2(db, sessionId);
34508
34660
  db.prepare("DELETE FROM compartments WHERE session_id = ?").run(sessionId);
34509
34661
  db.prepare("DELETE FROM session_facts WHERE session_id = ?").run(sessionId);
34510
- insertRecompCompartmentRows(db, sessionId, staging.compartments, now);
34662
+ insertRecompCompartmentRows(db, sessionId, compartments, now, carried?.rows ?? carriedRows);
34511
34663
  queueM0Mutation(db, {
34512
34664
  sessionId,
34513
34665
  mutationType: "recomp_boundary_change",
@@ -34521,7 +34673,12 @@ function promoteRecompStagingWithM0Mutation(db, sessionId, holderId) {
34521
34673
  finished = true;
34522
34674
  invalidateAutoEmbedSession(sessionId);
34523
34675
  logSlowWriteTransaction("historian-publish:recomp", transactionStartedAt);
34524
- return { compartments: staging.compartments, facts: staging.facts };
34676
+ return {
34677
+ compartments,
34678
+ facts: staging.facts,
34679
+ carriedCount: carried?.compartments.length ?? 0,
34680
+ carriedThrough: carried?.end ?? null
34681
+ };
34525
34682
  } finally {
34526
34683
  if (!finished) {
34527
34684
  try {
@@ -34530,6 +34687,69 @@ function promoteRecompStagingWithM0Mutation(db, sessionId, holderId) {
34530
34687
  }
34531
34688
  }
34532
34689
  }
34690
+ function resolvedOrdinal(sessionId, id) {
34691
+ return id ? readRawSessionMessageOrdinalById2(sessionId, id) : null;
34692
+ }
34693
+ function readLiveRanges(db, sessionId) {
34694
+ const rows = db.prepare(`SELECT sequence, start_message, start_message_id, end_message, end_message_id FROM compartments
34695
+ WHERE session_id = ? ORDER BY sequence`).all(sessionId);
34696
+ return rows.map((row) => {
34697
+ const resolvedEnd = resolvedOrdinal(sessionId, row.end_message_id);
34698
+ return { ...row, end: resolvedEnd ?? row.end_message, resolvedEnd };
34699
+ });
34700
+ }
34701
+ function readAlignedLiveTail(db, sessionId, live, staging, stagedEnd) {
34702
+ let next = 1;
34703
+ let seam;
34704
+ for (const row of live) {
34705
+ const start = resolvedOrdinal(sessionId, row.start_message_id);
34706
+ if ((start ?? row.start_message) !== next || row.end < next)
34707
+ return null;
34708
+ if (seam !== undefined && (start === null || row.resolvedEnd === null))
34709
+ return null;
34710
+ if (row.end === stagedEnd)
34711
+ seam = row.sequence;
34712
+ next = row.end + 1;
34713
+ }
34714
+ if (seam === undefined)
34715
+ return null;
34716
+ const seamSequence = seam;
34717
+ const tail = getCompartments(db, sessionId).filter((row) => row.sequence > seamSequence);
34718
+ if (!tail.length || tail.length !== live.filter((row) => row.sequence > seamSequence).length)
34719
+ return null;
34720
+ return {
34721
+ compartments: tail.map((row, index) => compartmentToInput(row, staging.compartments.length + index)),
34722
+ rows: new Map(tail.map((row, index) => [staging.compartments.length + index, row])),
34723
+ end: next - 1
34724
+ };
34725
+ }
34726
+ function getResumableFullStaging(db, sessionId, rawMessageCount) {
34727
+ const staging = getRecompStaging(db, sessionId);
34728
+ let reason = null;
34729
+ if (getRecompPartialRange(db, sessionId)) {
34730
+ reason = "the staged passes were for a range rebuild";
34731
+ } else if (staging) {
34732
+ reason = validateStoredCompartments(staging.compartments);
34733
+ if (!reason) {
34734
+ const ordinals = readRawSessionMessageIdOrdinalsForRange2(sessionId, 1, Math.min(rawMessageCount, staging.lastEndMessage));
34735
+ if (staging.compartments.some(({ startMessage, endMessage, startMessageId, endMessageId }) => ordinals.get(startMessageId) !== startMessage || ordinals.get(endMessageId) !== endMessage)) {
34736
+ reason = "staged endpoints no longer match the raw history";
34737
+ }
34738
+ }
34739
+ }
34740
+ if (!reason)
34741
+ return staging;
34742
+ clearRecompStaging(db, sessionId);
34743
+ sessionLog2(sessionId, `recomp discarded staging: ${reason}`);
34744
+ return null;
34745
+ }
34746
+ var PUBLISH_LEASE_LOST = `## Magic Recomp — Skipped
34747
+
34748
+ Another process acquired the compartment-state lease before recomp could publish. No state was written.`;
34749
+ var STAGING_REMOVED = `## Magic Recomp — Failed
34750
+
34751
+ The unfinished rebuild was removed because the session's history changed. Nothing was published.
34752
+ Run /ctx-recomp again.`;
34533
34753
  async function executeContextRecompInternal(deps) {
34534
34754
  const {
34535
34755
  client,
@@ -34572,6 +34792,12 @@ Session ordinals are warming in the background. Retry shortly; no history was re
34572
34792
  updateSessionMeta(db, sessionId, { compartmentInProgress: true });
34573
34793
  try {
34574
34794
  const rawMessageCount = getRawSessionMessageCount2(sessionId);
34795
+ const existingStaging = getResumableFullStaging(db, sessionId, rawMessageCount);
34796
+ if (rawMessageCount <= 0) {
34797
+ return `## Magic Recomp
34798
+
34799
+ No raw history exists, so nothing was rebuilt.`;
34800
+ }
34575
34801
  const boundarySnapshot = resolveOpenCodeProtectedTailBoundary({
34576
34802
  db,
34577
34803
  sessionId,
@@ -34582,21 +34808,21 @@ Session ordinals are warming in the background. Retry shortly; no history was re
34582
34808
  usageSource: "provisional-zero"
34583
34809
  });
34584
34810
  const protectedTailStart = Math.min(boundarySnapshot.protectedTailStart, rawMessageCount + 1);
34585
- if (rawMessageCount <= 0) {
34586
- return `## Magic Recomp
34811
+ if (!existingStaging && protectedTailStart === 1) {
34812
+ return `## Magic Recomp — Skipped
34587
34813
 
34588
- No raw history exists, so nothing was rebuilt.`;
34814
+ Nothing to rebuild yet: every message is still in the recent part that is kept raw.`;
34589
34815
  }
34590
34816
  const parentSessionResponse = await client?.session.get({ path: { id: sessionId } }).catch(() => null);
34591
34817
  const parentSession = normalizeSDKResponse(parentSessionResponse, null, { preferResponseOnMissingData: true });
34592
34818
  const sessionDirectory = parentSession?.directory ?? directory;
34593
- const existingStaging = getRecompStaging(db, sessionId);
34594
34819
  let candidateCompartments = existingStaging?.compartments ?? [];
34595
34820
  let candidateFacts = existingStaging?.facts ?? [];
34596
34821
  let offset = existingStaging ? existingStaging.lastEndMessage + 1 : 1;
34597
34822
  let passCount = existingStaging?.passCount ?? 0;
34598
34823
  let currentTokenBudget = historianChunkTokens;
34599
34824
  let passAttempt = 1;
34825
+ let hadModelFailureOrBudgetReduction = false;
34600
34826
  const resumed = existingStaging !== null;
34601
34827
  if (resumed) {
34602
34828
  await sendStatusNotification(client, sessionId, `## Magic Recomp — Resumed
@@ -34621,19 +34847,53 @@ Found ${existingStaging.compartments.length} staged compartment(s) from ${existi
34621
34847
  } catch {}
34622
34848
  };
34623
34849
  emitProgress("Preparing…");
34624
- async function promoteAndFinalize(reason) {
34850
+ async function promoteAndFinalize(reason, heading = "Partial", failure = "recomp_unavailable", sentence, deterministicStop = false) {
34625
34851
  if (passCount === 0 || candidateCompartments.length === 0)
34626
34852
  return null;
34627
34853
  const mergedError = validateStoredCompartments(candidateCompartments);
34628
34854
  if (mergedError)
34629
34855
  return null;
34630
- saveRecompStagingPass(db, sessionId, passCount, candidateCompartments, candidateFacts);
34631
34856
  const lastCompartmentEnd = candidateCompartments[candidateCompartments.length - 1]?.endMessage ?? 0;
34632
34857
  const compartmentTagKeys = lastCompartmentEnd > 0 ? await getRawSessionTagKeysThrough2(sessionId, lastCompartmentEnd, { db }) : null;
34633
- const promoted = promoteRecompStagingWithM0Mutation(db, sessionId, leaseHolderId);
34634
- if (!promoted)
34635
- return null;
34636
- afterPublish("compression-depth", () => clearCompressionDepth(db, sessionId));
34858
+ const promoted = promoteRecompStaging(db, sessionId, leaseHolderId, {
34859
+ allowCarry: heading === "Complete",
34860
+ discardIfShort: deterministicStop && passAttempt === 1 && !hadModelFailureOrBudgetReduction && resumed && passCount === existingStaging.passCount
34861
+ });
34862
+ if (promoted === "would-shrink" || promoted === "discarded") {
34863
+ const detail = renderUserFacingFailure(failure, "markdown", {
34864
+ sentence,
34865
+ ...failure !== "historian_window_too_small" ? { action: "" } : {}
34866
+ });
34867
+ if (promoted === "discarded") {
34868
+ return [
34869
+ "## Magic Recomp — Failed",
34870
+ "",
34871
+ `The rebuild could not get past message ${offset}. ${detail}`,
34872
+ "The unfinished rebuild was discarded.",
34873
+ "Your current history is unchanged."
34874
+ ].join(`
34875
+ `);
34876
+ }
34877
+ const continueFrom = `Run /ctx-recomp again to continue from message ${lastCompartmentEnd + 1}.`;
34878
+ return [
34879
+ RECOMP_PAUSED_HEADING,
34880
+ "",
34881
+ resumed ? `Messages 1-${lastCompartmentEnd} of ${totalMessages} are rebuilt and kept for the next run. ${detail}` : `Rebuilt messages 1-${lastCompartmentEnd} of ${totalMessages}, then stopped. ${detail}`,
34882
+ "Your current history is unchanged.",
34883
+ deterministicStop ? `${continueFrom} If it stops at the same place again, the unfinished rebuild is discarded and your history stays as it is.` : continueFrom
34884
+ ].join(`
34885
+ `);
34886
+ }
34887
+ if (promoted === "lease-lost")
34888
+ return PUBLISH_LEASE_LOST;
34889
+ if (promoted === "staging-removed")
34890
+ return STAGING_REMOVED;
34891
+ afterPublish("compression-depth", () => {
34892
+ if (promoted.carriedCount > 0)
34893
+ clearCompressionDepthRange(db, sessionId, 1, lastCompartmentEnd);
34894
+ else
34895
+ clearCompressionDepth(db, sessionId);
34896
+ });
34637
34897
  if (deps.preserveInjectionCacheUntilConsumed !== true) {
34638
34898
  clearInjectionCache(sessionId);
34639
34899
  }
@@ -34653,9 +34913,10 @@ Found ${existingStaging.compartments.length} staged compartment(s) from ${existi
34653
34913
  afterPublish("drop-queue", () => queueDropsForCompartmentalizedMessages(db, sessionId, lastCompartmentEnd, compartmentTagKeys));
34654
34914
  }
34655
34915
  afterPublish("publication-signal", () => deps.onCompartmentStatePublished?.(sessionId));
34656
- if (lastCompartmentEnd > 0) {
34916
+ const publishedEnd = promoted.carriedThrough ?? lastCompartmentEnd;
34917
+ if (publishedEnd > 0) {
34657
34918
  afterPublish("compaction-marker", () => {
34658
- const markerUpdated = (deps.compactionMarkerStrategy?.publish ?? updateCompactionMarkerAfterPublication)(db, sessionId, lastCompartmentEnd, deps.directory);
34919
+ const markerUpdated = (deps.compactionMarkerStrategy?.publish ?? updateCompactionMarkerAfterPublication)(db, sessionId, publishedEnd, deps.directory);
34659
34920
  if (markerUpdated) {
34660
34921
  const stalePending = getPendingCompactionMarkerState(db, sessionId);
34661
34922
  if (stalePending) {
@@ -34664,8 +34925,26 @@ Found ${existingStaging.compartments.length} staged compartment(s) from ${existi
34664
34925
  }
34665
34926
  });
34666
34927
  }
34928
+ const rebuilt = promoted.compartments.length - promoted.carriedCount;
34929
+ const rebuiltThrough = `Rebuilt ${rebuilt} history block${rebuilt === 1 ? "" : "s"} through message ${lastCompartmentEnd}.`;
34930
+ if (promoted.carriedCount > 0) {
34931
+ return [
34932
+ "## Magic Recomp — Complete",
34933
+ "",
34934
+ rebuiltThrough,
34935
+ `Kept ${promoted.carriedCount} existing history block${promoted.carriedCount === 1 ? "" : "s"} through message ${publishedEnd}.`
34936
+ ].join(`
34937
+ `);
34938
+ }
34939
+ if (heading === "Complete") {
34940
+ return `## Magic Recomp — Complete
34941
+
34942
+ ${rebuiltThrough} Messages ${offset} to ${protectedTailStart - 1} have nothing to summarize and stay as they are.`;
34943
+ }
34667
34944
  sessionLog2(sessionId, `recomp partial code=${userFacingFailureCode("recomp_unavailable")} reason="${reason}"`);
34668
34945
  return [
34946
+ `## Magic Recomp — ${heading}`,
34947
+ "",
34669
34948
  `Rebuilt ${promoted.compartments.length} history block${promoted.compartments.length === 1 ? "" : "s"} across ${passCount} successful pass${passCount === 1 ? "" : "es"}.`,
34670
34949
  renderUserFacingFailure("recomp_unavailable")
34671
34950
  ].join(`
@@ -34695,12 +34974,9 @@ Found ${existingStaging.compartments.length} staged compartment(s) from ${existi
34695
34974
  compartmentsProduced: 0
34696
34975
  });
34697
34976
  sessionLog2(sessionId, `recomp failed code=${userFacingFailureCode("historian_window_too_small")} reason="${promptFit.reason}"`);
34698
- const partial = await promoteAndFinalize(`the history model's window cannot hold a historian prompt: ${promptFit.reason}`);
34699
- if (partial) {
34700
- return `## Magic Recomp — Partial
34701
-
34702
- ${partial}`;
34703
- }
34977
+ const partial = await promoteAndFinalize(`the history model's window cannot hold a historian prompt: ${promptFit.reason}`, "Partial", "historian_window_too_small");
34978
+ if (partial)
34979
+ return partial;
34704
34980
  return `## Magic Recomp — Failed
34705
34981
 
34706
34982
  ${renderUserFacingFailure("historian_window_too_small")}`;
@@ -34708,26 +34984,22 @@ ${renderUserFacingFailure("historian_window_too_small")}`;
34708
34984
  if (promptFit.trimmed || promptFit.chunkTokens < currentTokenBudget) {
34709
34985
  sessionLog2(sessionId, `recomp prompt fit: ${describeHistorianPromptTrim(promptFit)} requestedChunkTokens=${currentTokenBudget}`);
34710
34986
  }
34987
+ if (promptFit.chunkTokens < currentTokenBudget)
34988
+ hadModelFailureOrBudgetReduction = true;
34711
34989
  const chunk = readSessionChunk2(sessionId, promptFit.chunkTokens, offset, protectedTailStart, { expandTools: deps.historianExpandTools });
34712
34990
  if (!chunk.text || chunk.messageCount === 0 || chunk.endIndex < offset) {
34713
- const promoted = await promoteAndFinalize(`remaining messages ${offset}-${protectedTailStart - 1} were too few or all noise to form a historian chunk`);
34714
- if (promoted) {
34715
- return `## Magic Recomp — Complete
34716
-
34717
- ${promoted}`;
34718
- }
34991
+ const promoted = await promoteAndFinalize(`remaining messages ${offset}-${protectedTailStart - 1} were too few or all noise to form a historian chunk`, "Complete", "recomp_unavailable", `Raw history ${offset}-${protectedTailStart - 1} could not be turned into a valid historian chunk.`, true);
34992
+ if (promoted)
34993
+ return promoted;
34719
34994
  return `## Magic Recomp — Failed
34720
34995
 
34721
34996
  Recomp stopped because raw history ${offset}-${protectedTailStart - 1} could not be turned into a valid historian chunk. Nothing was written.`;
34722
34997
  }
34723
34998
  const chunkCoverageError = validateChunkCoverage(chunk);
34724
34999
  if (chunkCoverageError) {
34725
- const partial = await promoteAndFinalize(`chunk could not be represented safely: ${chunkCoverageError}`);
34726
- if (partial) {
34727
- return `## Magic Recomp — Partial
34728
-
34729
- ${partial}`;
34730
- }
35000
+ const partial = await promoteAndFinalize(`chunk could not be represented safely: ${chunkCoverageError}`, "Partial", "recomp_unavailable", "The next chunk could not be represented safely.", true);
35001
+ if (partial)
35002
+ return partial;
34731
35003
  sessionLog2(sessionId, `recomp failed code=${userFacingFailureCode("recomp_unavailable")} reason="${chunkCoverageError}"`);
34732
35004
  return `## Magic Recomp — Failed
34733
35005
 
@@ -34769,6 +35041,7 @@ Historian pass ${passCount + 1}, attempt ${passAttempt} started for messages ${c
34769
35041
  language: deps.language,
34770
35042
  callbacks: {
34771
35043
  onRepairRetry: async (error) => {
35044
+ hadModelFailureOrBudgetReduction = true;
34772
35045
  emitProgress(`Repair retry (pass ${passCount + 1})…`);
34773
35046
  sessionLog2(sessionId, `recomp retry code=${userFacingFailureCode("recomp_unavailable")} reason="${error}"`);
34774
35047
  await sendStatusNotification(client, sessionId, `## Magic Recomp
@@ -34776,12 +35049,14 @@ Historian pass ${passCount + 1}, attempt ${passAttempt} started for messages ${c
34776
35049
  History compression is retrying this pass. ${renderUserFacingFailure("recomp_unavailable")}`, notifParams());
34777
35050
  },
34778
35051
  onModelFallback: (modelId, index, total) => {
35052
+ hadModelFailureOrBudgetReduction = true;
34779
35053
  const short = modelId.includes("/") ? modelId.split("/").pop() : modelId;
34780
35054
  emitProgress(`Trying fallback ${short} (${index}/${total})…`);
34781
35055
  }
34782
35056
  }
34783
35057
  });
34784
35058
  if (!validatedPass.ok) {
35059
+ hadModelFailureOrBudgetReduction = true;
34785
35060
  const reducedBudget = getReducedRecompTokenBudget(promptFit.chunkTokens);
34786
35061
  if (reducedBudget !== null) {
34787
35062
  const smallerChunk = readSessionChunk2(sessionId, reducedBudget, offset, protectedTailStart, { expandTools: deps.historianExpandTools });
@@ -34807,11 +35082,8 @@ History compression is retrying with a smaller set of messages. ${renderUserFaci
34807
35082
  });
34808
35083
  sessionLog2(sessionId, `recomp failed code=${userFacingFailureCode("recomp_unavailable")} reason="${validatedPass.error}" messageRange=${chunk.startIndex}-${chunk.endIndex}`);
34809
35084
  const partial = await promoteAndFinalize(`history model response did not validate for messages ${chunk.startIndex}-${chunk.endIndex}`);
34810
- if (partial) {
34811
- return `## Magic Recomp — Partial
34812
-
34813
- ${partial}`;
34814
- }
35085
+ if (partial)
35086
+ return partial;
34815
35087
  return `## Magic Recomp — Failed
34816
35088
 
34817
35089
  ${renderUserFacingFailure("recomp_unavailable")}`;
@@ -34838,6 +35110,17 @@ ${renderUserFacingFailure("recomp_unavailable")}`;
34838
35110
  importanceAvg: imp.avg
34839
35111
  });
34840
35112
  }
35113
+ const nextOffset = (validatedPass.compartments?.[validatedPass.compartments.length - 1]?.endMessage ?? chunk.endIndex) + 1;
35114
+ if (nextOffset <= offset) {
35115
+ const reason = `Recomp made no forward progress after messages ${chunk.startIndex}-${chunk.endIndex}.`;
35116
+ const partial = await promoteAndFinalize(reason, "Partial", "recomp_unavailable", reason, true);
35117
+ if (partial)
35118
+ return partial;
35119
+ return `## Magic Recomp — Failed
35120
+
35121
+ ${reason} Nothing was written.`;
35122
+ }
35123
+ const hadStagedPrefix = candidateCompartments.length > 0;
34841
35124
  candidateCompartments = [
34842
35125
  ...candidateCompartments,
34843
35126
  ...validatedPass.compartments ?? []
@@ -34846,19 +35129,14 @@ ${renderUserFacingFailure("recomp_unavailable")}`;
34846
35129
  passCount += 1;
34847
35130
  currentTokenBudget = historianChunkTokens;
34848
35131
  passAttempt = 1;
34849
- saveRecompStagingPass(db, sessionId, passCount, candidateCompartments, candidateFacts);
34850
- const nextOffset = (validatedPass.compartments?.[validatedPass.compartments.length - 1]?.endMessage ?? chunk.endIndex) + 1;
34851
- if (nextOffset <= offset) {
34852
- const partial = await promoteAndFinalize(`historian made no forward progress after messages ${chunk.startIndex}-${chunk.endIndex}`);
34853
- if (partial) {
34854
- return `## Magic Recomp — Partial
34855
-
34856
- ${partial}`;
34857
- }
34858
- return `## Magic Recomp — Failed
34859
-
34860
- Recomp made no forward progress after messages ${chunk.startIndex}-${chunk.endIndex}. Nothing was written.`;
34861
- }
35132
+ const saved = db.transaction(() => {
35133
+ if (hadStagedPrefix && !db.prepare("SELECT 1 FROM recomp_compartments WHERE session_id = ? LIMIT 1").get(sessionId))
35134
+ return false;
35135
+ saveRecompStagingPass(db, sessionId, passCount, candidateCompartments, candidateFacts);
35136
+ return true;
35137
+ }).immediate();
35138
+ if (!saved)
35139
+ return STAGING_REMOVED;
34862
35140
  offset = nextOffset;
34863
35141
  emitProgress();
34864
35142
  }
@@ -34870,15 +35148,15 @@ Recomp made no forward progress after messages ${chunk.startIndex}-${chunk.endIn
34870
35148
 
34871
35149
  ${renderUserFacingFailure("recomp_unavailable")}`;
34872
35150
  }
34873
- saveRecompStagingPass(db, sessionId, passCount, candidateCompartments, candidateFacts);
34874
35151
  const lastCompartmentEnd = candidateCompartments[candidateCompartments.length - 1]?.endMessage ?? 0;
34875
35152
  const compartmentTagKeys = lastCompartmentEnd > 0 ? await getRawSessionTagKeysThrough2(sessionId, lastCompartmentEnd, { db }) : null;
34876
- const promoted = promoteRecompStagingWithM0Mutation(db, sessionId, leaseHolderId);
34877
- if (!promoted) {
35153
+ const promoted = promoteRecompStaging(db, sessionId, leaseHolderId);
35154
+ if (promoted === "staging-removed") {
35155
+ return candidateCompartments.length > 0 ? STAGING_REMOVED : PUBLISH_LEASE_LOST;
35156
+ }
35157
+ if (typeof promoted === "string") {
34878
35158
  sessionLog2(sessionId, "recomp publish skipped: compartment lease no longer held");
34879
- return `## Magic Recomp — Skipped
34880
-
34881
- Another process acquired the compartment-state lease before recomp could publish. No state was written.`;
35159
+ return PUBLISH_LEASE_LOST;
34882
35160
  }
34883
35161
  afterPublish("compression-depth", () => clearCompressionDepth(db, sessionId));
34884
35162
  if (deps.preserveInjectionCacheUntilConsumed !== true) {
@@ -34971,25 +35249,6 @@ function snapRangeToCompartments(compartments, range) {
34971
35249
  tailCompartments: sorted.slice(lastEnclosingIdx + 1)
34972
35250
  };
34973
35251
  }
34974
- function compartmentToInput(c, newSequence) {
34975
- return {
34976
- sequence: newSequence,
34977
- startMessage: c.startMessage,
34978
- endMessage: c.endMessage,
34979
- startMessageId: c.startMessageId,
34980
- endMessageId: c.endMessageId,
34981
- startBlockIndex: c.startBlockIndex,
34982
- endBlockIndex: c.endBlockIndex,
34983
- title: c.title,
34984
- content: c.content,
34985
- p1: c.p1,
34986
- p2: c.p2,
34987
- p3: c.p3,
34988
- p4: c.p4,
34989
- importance: c.importance,
34990
- episodeType: c.episodeType
34991
- };
34992
- }
34993
35252
  async function executePartialRecompInternal(deps, range) {
34994
35253
  const {
34995
35254
  client,
@@ -35009,6 +35268,7 @@ Could not acquire the compartment-state lease for this session.`;
35009
35268
  }
35010
35269
  const leaseHolderId = holderId;
35011
35270
  updateSessionMeta(db, sessionId, { compartmentInProgress: true });
35271
+ let wroteStaging = false;
35012
35272
  try {
35013
35273
  let promoteFinal = function() {
35014
35274
  const newBuilt = candidateCompartments.slice(priorCompartments.length);
@@ -35044,7 +35304,12 @@ Could not acquire the compartment-state lease for this session.`;
35044
35304
  return null;
35045
35305
  }
35046
35306
  saveRecompStagingPass(db, sessionId, passCount + 1, merged, stagedFacts);
35047
- const promoted = promoteRecompStagingWithM0Mutation(db, sessionId, leaseHolderId);
35307
+ wroteStaging = true;
35308
+ const carriedRows = new Map([
35309
+ ...priorCompartments.map((c, idx) => [idx, c]),
35310
+ ...tailCompartments.map((c, idx) => [candidateCompartments.length + idx, c])
35311
+ ]);
35312
+ const promoted = promoteRecompStagingWithM0Mutation(db, sessionId, leaseHolderId, carriedRows);
35048
35313
  if (!promoted) {
35049
35314
  log2("[magic-context] partial recomp promote returned null");
35050
35315
  return null;
@@ -35093,8 +35358,7 @@ ${snapResult.error}`;
35093
35358
  "",
35094
35359
  `An unfinished partial recomp is already staged for range ${storedRange.start}-${storedRange.end}, which does not match the requested range ${snapStart}-${snapEnd}.`,
35095
35360
  "",
35096
- "Resume that range by running `/ctx-recomp` with the same original arguments,",
35097
- "or cancel it by running `/ctx-flush` before starting a new partial recomp."
35361
+ "Finish that range by running `/ctx-recomp` with the same original arguments, or run `/ctx-recomp` without arguments to start a full rebuild."
35098
35362
  ].join(`
35099
35363
  `);
35100
35364
  }
@@ -35102,9 +35366,7 @@ ${snapResult.error}`;
35102
35366
  return [
35103
35367
  "## Magic Recomp — Failed",
35104
35368
  "",
35105
- "An unfinished full recomp is already staged for this session.",
35106
- "Resume it by running `/ctx-recomp` without arguments,",
35107
- "or cancel it before starting a partial recomp."
35369
+ `A full rebuild is paused at message ${existingStaging.lastEndMessage}. Run \`/ctx-recomp\` without arguments to continue it. A partial recomp can start when it completes or is discarded.`
35108
35370
  ].join(`
35109
35371
  `);
35110
35372
  }
@@ -35126,6 +35388,7 @@ ${snapResult.error}`;
35126
35388
  passCount = 0;
35127
35389
  offset = snapStart;
35128
35390
  saveRecompStagingPass(db, sessionId, 0, candidateCompartments, stagedFacts);
35391
+ wroteStaging = true;
35129
35392
  setRecompPartialRange(db, sessionId, { start: snapStart, end: snapEnd });
35130
35393
  }
35131
35394
  let currentTokenBudget = historianChunkTokens;
@@ -35235,6 +35498,7 @@ ${renderUserFacingFailure("recomp_unavailable")}`;
35235
35498
  currentTokenBudget = historianChunkTokens;
35236
35499
  passAttempt = 1;
35237
35500
  saveRecompStagingPass(db, sessionId, passCount, candidateCompartments, stagedFacts);
35501
+ wroteStaging = true;
35238
35502
  const nextOffset = (validatedPass.compartments?.[validatedPass.compartments.length - 1]?.endMessage ?? chunk.endIndex) + 1;
35239
35503
  if (nextOffset <= offset) {
35240
35504
  return `## Magic Recomp — Failed
@@ -35266,9 +35530,7 @@ Partial recomp completed historian passes but the final compartment set failed v
35266
35530
  ${renderUserFacingFailure("recomp_unavailable")}`;
35267
35531
  } finally {
35268
35532
  updateSessionMeta(db, sessionId, { compartmentInProgress: false });
35269
- const leftoverStaging = getRecompStaging(db, sessionId);
35270
- const leftoverRange = getRecompPartialRange(db, sessionId);
35271
- if (leftoverStaging && leftoverRange) {} else if (leftoverStaging && !leftoverRange) {
35533
+ if (wroteStaging && getRecompStaging(db, sessionId) && !getRecompPartialRange(db, sessionId)) {
35272
35534
  log2(`[magic-context] partial recomp cleanup: clearing orphaned staging without range marker for session ${sessionId}`);
35273
35535
  clearRecompStaging(db, sessionId);
35274
35536
  }