@cortexkit/pi-magic-context 0.49.87 → 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 (28) hide show
  1. package/dist/auto-search-worker.js +3 -3
  2. package/dist/chunk-embedding-write-worker.js +5 -5
  3. package/dist/{embedding-backfill-za59jg6b.js → embedding-backfill-yydkxhrp.js} +6 -6
  4. package/dist/embedding-worker.js +2 -2
  5. package/dist/{index-wd5xfz8m.js → index-6x595qtk.js} +75 -12
  6. package/dist/{index-53fgdt6n.js → index-7xsbhw6m.js} +1 -1
  7. package/dist/{index-ex9te7tc.js → index-aahd8x9s.js} +1 -1
  8. package/dist/{index-rqdjb6j3.js → index-fsjsvq78.js} +1 -1
  9. package/dist/{index-xemjzc1v.js → index-hs862sjk.js} +2 -2
  10. package/dist/{index-94z1xzmr.js → index-kezt62gs.js} +1 -1
  11. package/dist/{index-8qdebv92.js → index-kn83b37d.js} +3 -3
  12. package/dist/{index-s3s4px1q.js → index-ndprcb9x.js} +11 -9
  13. package/dist/{index-bkagkxm5.js → index-qtfp61mq.js} +2 -2
  14. package/dist/{index-8x8wtn3t.js → index-rrm9ce0j.js} +108 -13
  15. package/dist/{index-gbc29ysq.js → index-rzwcmbww.js} +1 -1
  16. package/dist/{index-affz2pyv.js → index-w48rf3j6.js} +1 -1
  17. package/dist/{index-4c48169d.js → index-z2bdsba1.js} +9 -9
  18. package/dist/index.js +270 -105
  19. package/dist/migration-worker.js +4 -4
  20. package/dist/{project-embedding-registry-4kwf0m7j.js → project-embedding-registry-f9tzr12g.js} +5 -5
  21. package/dist/raw-ordinal-warmup-worker.js +2 -2
  22. package/dist/{render-2jzjgetc.js → render-mr2bb4yf.js} +6 -6
  23. package/dist/{search-archive-ze1567mj.js → search-archive-abtztrw5.js} +1 -1
  24. package/dist/{search-8dyn724d.js → search-rdqrskte.js} +9 -9
  25. package/dist/subagent-entry.js +13 -13
  26. package/dist/tag-snapshot-worker-pi.js +4 -4
  27. package/dist/{v2-archive-reader-vq596vh8.js → v2-archive-reader-qaecyb4y.js} +1 -1
  28. 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-4c48169d.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-bkagkxm5.js";
596
+ } from "./index-qtfp61mq.js";
597
597
  import {
598
598
  resolveOpenCodeDbPath,
599
599
  assertOpenCodeStoreGeneration,
@@ -654,6 +654,7 @@ import {
654
654
  primeInMemoryTailRawMessageCache2,
655
655
  readRawSessionMessageIdOrdinalsForRange2,
656
656
  hasRawSessionMessageById2,
657
+ readRawSessionMessageOrdinalById2,
657
658
  compareRawSessionMessageOrder2,
658
659
  getRawSessionMessageCount2,
659
660
  getRawSessionTagKeysThrough2,
@@ -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,
@@ -716,7 +717,7 @@ import {
716
717
  openCurrentDatabase,
717
718
  openDatabaseAsync,
718
719
  closeDatabase
719
- } from "./index-wd5xfz8m.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
@@ -806,7 +807,7 @@ import {
806
807
  embedSessionCompartmentChunks2,
807
808
  getEmbeddingCoverageStatus2,
808
809
  getAutoEmbeddingSessionCoverage2
809
- } from "./index-8qdebv92.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-s3s4px1q.js";
845
- import"./index-affz2pyv.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,7 +876,7 @@ import {
875
876
  } from "./index-pdrberjp.js";
876
877
  import"./index-71rg8j43.js";
877
878
  import"./index-8d2z6503.js";
878
- import"./index-xemjzc1v.js";
879
+ import"./index-hs862sjk.js";
879
880
  import"./index-hp320128.js";
880
881
  import {
881
882
  __toESM
@@ -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.87",
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",
@@ -34576,15 +34577,47 @@ var lastHistorianAlertBySession2 = new Map;
34576
34577
  var loggedStoredValidationFailures = new Map;
34577
34578
  var STORED_COMPARTMENT_FAILURE_BACKOFF_MS = 30 * 60 * 1000;
34578
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
+
34579
34604
  // ../plugin/src/hooks/magic-context/compartment-runner-recomp.ts
34580
- function insertRecompCompartmentRows(db, sessionId, compartments, now) {
34581
- 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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
34582
34610
  for (const c of compartments) {
34583
34611
  const hasTiers = typeof c.p1 === "string" && c.p1.length > 0;
34584
- 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");
34585
34614
  }
34586
34615
  }
34587
- 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) {
34588
34621
  const now = Date.now();
34589
34622
  db.exec("BEGIN IMMEDIATE");
34590
34623
  const transactionStartedAt = performance.now();
@@ -34593,18 +34626,40 @@ function promoteRecompStagingWithM0Mutation(db, sessionId, holderId) {
34593
34626
  if (!isCompartmentLeaseHeld(db, sessionId, holderId)) {
34594
34627
  db.exec("ROLLBACK");
34595
34628
  finished = true;
34596
- return null;
34629
+ return "lease-lost";
34597
34630
  }
34598
34631
  const staging = getRecompStaging(db, sessionId);
34599
- if (!staging || staging.compartments.length === 0) {
34632
+ const staged = staging?.compartments.at(-1);
34633
+ if (!staging || !staged) {
34600
34634
  db.exec("ROLLBACK");
34601
34635
  finished = true;
34602
- 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
+ }
34603
34657
  }
34658
+ const compartments = carried ? [...staging.compartments, ...carried.compartments] : staging.compartments;
34604
34659
  deleteChunkEmbedBackoffForSession2(db, sessionId);
34605
34660
  db.prepare("DELETE FROM compartments WHERE session_id = ?").run(sessionId);
34606
34661
  db.prepare("DELETE FROM session_facts WHERE session_id = ?").run(sessionId);
34607
- insertRecompCompartmentRows(db, sessionId, staging.compartments, now);
34662
+ insertRecompCompartmentRows(db, sessionId, compartments, now, carried?.rows ?? carriedRows);
34608
34663
  queueM0Mutation(db, {
34609
34664
  sessionId,
34610
34665
  mutationType: "recomp_boundary_change",
@@ -34618,7 +34673,12 @@ function promoteRecompStagingWithM0Mutation(db, sessionId, holderId) {
34618
34673
  finished = true;
34619
34674
  invalidateAutoEmbedSession(sessionId);
34620
34675
  logSlowWriteTransaction("historian-publish:recomp", transactionStartedAt);
34621
- 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
+ };
34622
34682
  } finally {
34623
34683
  if (!finished) {
34624
34684
  try {
@@ -34627,6 +34687,69 @@ function promoteRecompStagingWithM0Mutation(db, sessionId, holderId) {
34627
34687
  }
34628
34688
  }
34629
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.`;
34630
34753
  async function executeContextRecompInternal(deps) {
34631
34754
  const {
34632
34755
  client,
@@ -34669,6 +34792,12 @@ Session ordinals are warming in the background. Retry shortly; no history was re
34669
34792
  updateSessionMeta(db, sessionId, { compartmentInProgress: true });
34670
34793
  try {
34671
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
+ }
34672
34801
  const boundarySnapshot = resolveOpenCodeProtectedTailBoundary({
34673
34802
  db,
34674
34803
  sessionId,
@@ -34679,21 +34808,21 @@ Session ordinals are warming in the background. Retry shortly; no history was re
34679
34808
  usageSource: "provisional-zero"
34680
34809
  });
34681
34810
  const protectedTailStart = Math.min(boundarySnapshot.protectedTailStart, rawMessageCount + 1);
34682
- if (rawMessageCount <= 0) {
34683
- return `## Magic Recomp
34811
+ if (!existingStaging && protectedTailStart === 1) {
34812
+ return `## Magic Recomp — Skipped
34684
34813
 
34685
- 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.`;
34686
34815
  }
34687
34816
  const parentSessionResponse = await client?.session.get({ path: { id: sessionId } }).catch(() => null);
34688
34817
  const parentSession = normalizeSDKResponse(parentSessionResponse, null, { preferResponseOnMissingData: true });
34689
34818
  const sessionDirectory = parentSession?.directory ?? directory;
34690
- const existingStaging = getRecompStaging(db, sessionId);
34691
34819
  let candidateCompartments = existingStaging?.compartments ?? [];
34692
34820
  let candidateFacts = existingStaging?.facts ?? [];
34693
34821
  let offset = existingStaging ? existingStaging.lastEndMessage + 1 : 1;
34694
34822
  let passCount = existingStaging?.passCount ?? 0;
34695
34823
  let currentTokenBudget = historianChunkTokens;
34696
34824
  let passAttempt = 1;
34825
+ let hadModelFailureOrBudgetReduction = false;
34697
34826
  const resumed = existingStaging !== null;
34698
34827
  if (resumed) {
34699
34828
  await sendStatusNotification(client, sessionId, `## Magic Recomp — Resumed
@@ -34718,19 +34847,53 @@ Found ${existingStaging.compartments.length} staged compartment(s) from ${existi
34718
34847
  } catch {}
34719
34848
  };
34720
34849
  emitProgress("Preparing…");
34721
- async function promoteAndFinalize(reason) {
34850
+ async function promoteAndFinalize(reason, heading = "Partial", failure = "recomp_unavailable", sentence, deterministicStop = false) {
34722
34851
  if (passCount === 0 || candidateCompartments.length === 0)
34723
34852
  return null;
34724
34853
  const mergedError = validateStoredCompartments(candidateCompartments);
34725
34854
  if (mergedError)
34726
34855
  return null;
34727
- saveRecompStagingPass(db, sessionId, passCount, candidateCompartments, candidateFacts);
34728
34856
  const lastCompartmentEnd = candidateCompartments[candidateCompartments.length - 1]?.endMessage ?? 0;
34729
34857
  const compartmentTagKeys = lastCompartmentEnd > 0 ? await getRawSessionTagKeysThrough2(sessionId, lastCompartmentEnd, { db }) : null;
34730
- const promoted = promoteRecompStagingWithM0Mutation(db, sessionId, leaseHolderId);
34731
- if (!promoted)
34732
- return null;
34733
- 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
+ });
34734
34897
  if (deps.preserveInjectionCacheUntilConsumed !== true) {
34735
34898
  clearInjectionCache(sessionId);
34736
34899
  }
@@ -34750,9 +34913,10 @@ Found ${existingStaging.compartments.length} staged compartment(s) from ${existi
34750
34913
  afterPublish("drop-queue", () => queueDropsForCompartmentalizedMessages(db, sessionId, lastCompartmentEnd, compartmentTagKeys));
34751
34914
  }
34752
34915
  afterPublish("publication-signal", () => deps.onCompartmentStatePublished?.(sessionId));
34753
- if (lastCompartmentEnd > 0) {
34916
+ const publishedEnd = promoted.carriedThrough ?? lastCompartmentEnd;
34917
+ if (publishedEnd > 0) {
34754
34918
  afterPublish("compaction-marker", () => {
34755
- const markerUpdated = (deps.compactionMarkerStrategy?.publish ?? updateCompactionMarkerAfterPublication)(db, sessionId, lastCompartmentEnd, deps.directory);
34919
+ const markerUpdated = (deps.compactionMarkerStrategy?.publish ?? updateCompactionMarkerAfterPublication)(db, sessionId, publishedEnd, deps.directory);
34756
34920
  if (markerUpdated) {
34757
34921
  const stalePending = getPendingCompactionMarkerState(db, sessionId);
34758
34922
  if (stalePending) {
@@ -34761,8 +34925,26 @@ Found ${existingStaging.compartments.length} staged compartment(s) from ${existi
34761
34925
  }
34762
34926
  });
34763
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
+ }
34764
34944
  sessionLog2(sessionId, `recomp partial code=${userFacingFailureCode("recomp_unavailable")} reason="${reason}"`);
34765
34945
  return [
34946
+ `## Magic Recomp — ${heading}`,
34947
+ "",
34766
34948
  `Rebuilt ${promoted.compartments.length} history block${promoted.compartments.length === 1 ? "" : "s"} across ${passCount} successful pass${passCount === 1 ? "" : "es"}.`,
34767
34949
  renderUserFacingFailure("recomp_unavailable")
34768
34950
  ].join(`
@@ -34792,12 +34974,9 @@ Found ${existingStaging.compartments.length} staged compartment(s) from ${existi
34792
34974
  compartmentsProduced: 0
34793
34975
  });
34794
34976
  sessionLog2(sessionId, `recomp failed code=${userFacingFailureCode("historian_window_too_small")} reason="${promptFit.reason}"`);
34795
- const partial = await promoteAndFinalize(`the history model's window cannot hold a historian prompt: ${promptFit.reason}`);
34796
- if (partial) {
34797
- return `## Magic Recomp — Partial
34798
-
34799
- ${partial}`;
34800
- }
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;
34801
34980
  return `## Magic Recomp — Failed
34802
34981
 
34803
34982
  ${renderUserFacingFailure("historian_window_too_small")}`;
@@ -34805,26 +34984,22 @@ ${renderUserFacingFailure("historian_window_too_small")}`;
34805
34984
  if (promptFit.trimmed || promptFit.chunkTokens < currentTokenBudget) {
34806
34985
  sessionLog2(sessionId, `recomp prompt fit: ${describeHistorianPromptTrim(promptFit)} requestedChunkTokens=${currentTokenBudget}`);
34807
34986
  }
34987
+ if (promptFit.chunkTokens < currentTokenBudget)
34988
+ hadModelFailureOrBudgetReduction = true;
34808
34989
  const chunk = readSessionChunk2(sessionId, promptFit.chunkTokens, offset, protectedTailStart, { expandTools: deps.historianExpandTools });
34809
34990
  if (!chunk.text || chunk.messageCount === 0 || chunk.endIndex < offset) {
34810
- const promoted = await promoteAndFinalize(`remaining messages ${offset}-${protectedTailStart - 1} were too few or all noise to form a historian chunk`);
34811
- if (promoted) {
34812
- return `## Magic Recomp — Complete
34813
-
34814
- ${promoted}`;
34815
- }
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;
34816
34994
  return `## Magic Recomp — Failed
34817
34995
 
34818
34996
  Recomp stopped because raw history ${offset}-${protectedTailStart - 1} could not be turned into a valid historian chunk. Nothing was written.`;
34819
34997
  }
34820
34998
  const chunkCoverageError = validateChunkCoverage(chunk);
34821
34999
  if (chunkCoverageError) {
34822
- const partial = await promoteAndFinalize(`chunk could not be represented safely: ${chunkCoverageError}`);
34823
- if (partial) {
34824
- return `## Magic Recomp — Partial
34825
-
34826
- ${partial}`;
34827
- }
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;
34828
35003
  sessionLog2(sessionId, `recomp failed code=${userFacingFailureCode("recomp_unavailable")} reason="${chunkCoverageError}"`);
34829
35004
  return `## Magic Recomp — Failed
34830
35005
 
@@ -34866,6 +35041,7 @@ Historian pass ${passCount + 1}, attempt ${passAttempt} started for messages ${c
34866
35041
  language: deps.language,
34867
35042
  callbacks: {
34868
35043
  onRepairRetry: async (error) => {
35044
+ hadModelFailureOrBudgetReduction = true;
34869
35045
  emitProgress(`Repair retry (pass ${passCount + 1})…`);
34870
35046
  sessionLog2(sessionId, `recomp retry code=${userFacingFailureCode("recomp_unavailable")} reason="${error}"`);
34871
35047
  await sendStatusNotification(client, sessionId, `## Magic Recomp
@@ -34873,12 +35049,14 @@ Historian pass ${passCount + 1}, attempt ${passAttempt} started for messages ${c
34873
35049
  History compression is retrying this pass. ${renderUserFacingFailure("recomp_unavailable")}`, notifParams());
34874
35050
  },
34875
35051
  onModelFallback: (modelId, index, total) => {
35052
+ hadModelFailureOrBudgetReduction = true;
34876
35053
  const short = modelId.includes("/") ? modelId.split("/").pop() : modelId;
34877
35054
  emitProgress(`Trying fallback ${short} (${index}/${total})…`);
34878
35055
  }
34879
35056
  }
34880
35057
  });
34881
35058
  if (!validatedPass.ok) {
35059
+ hadModelFailureOrBudgetReduction = true;
34882
35060
  const reducedBudget = getReducedRecompTokenBudget(promptFit.chunkTokens);
34883
35061
  if (reducedBudget !== null) {
34884
35062
  const smallerChunk = readSessionChunk2(sessionId, reducedBudget, offset, protectedTailStart, { expandTools: deps.historianExpandTools });
@@ -34904,11 +35082,8 @@ History compression is retrying with a smaller set of messages. ${renderUserFaci
34904
35082
  });
34905
35083
  sessionLog2(sessionId, `recomp failed code=${userFacingFailureCode("recomp_unavailable")} reason="${validatedPass.error}" messageRange=${chunk.startIndex}-${chunk.endIndex}`);
34906
35084
  const partial = await promoteAndFinalize(`history model response did not validate for messages ${chunk.startIndex}-${chunk.endIndex}`);
34907
- if (partial) {
34908
- return `## Magic Recomp — Partial
34909
-
34910
- ${partial}`;
34911
- }
35085
+ if (partial)
35086
+ return partial;
34912
35087
  return `## Magic Recomp — Failed
34913
35088
 
34914
35089
  ${renderUserFacingFailure("recomp_unavailable")}`;
@@ -34935,6 +35110,17 @@ ${renderUserFacingFailure("recomp_unavailable")}`;
34935
35110
  importanceAvg: imp.avg
34936
35111
  });
34937
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;
34938
35124
  candidateCompartments = [
34939
35125
  ...candidateCompartments,
34940
35126
  ...validatedPass.compartments ?? []
@@ -34943,19 +35129,14 @@ ${renderUserFacingFailure("recomp_unavailable")}`;
34943
35129
  passCount += 1;
34944
35130
  currentTokenBudget = historianChunkTokens;
34945
35131
  passAttempt = 1;
34946
- saveRecompStagingPass(db, sessionId, passCount, candidateCompartments, candidateFacts);
34947
- const nextOffset = (validatedPass.compartments?.[validatedPass.compartments.length - 1]?.endMessage ?? chunk.endIndex) + 1;
34948
- if (nextOffset <= offset) {
34949
- const partial = await promoteAndFinalize(`historian made no forward progress after messages ${chunk.startIndex}-${chunk.endIndex}`);
34950
- if (partial) {
34951
- return `## Magic Recomp — Partial
34952
-
34953
- ${partial}`;
34954
- }
34955
- return `## Magic Recomp — Failed
34956
-
34957
- Recomp made no forward progress after messages ${chunk.startIndex}-${chunk.endIndex}. Nothing was written.`;
34958
- }
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;
34959
35140
  offset = nextOffset;
34960
35141
  emitProgress();
34961
35142
  }
@@ -34967,15 +35148,15 @@ Recomp made no forward progress after messages ${chunk.startIndex}-${chunk.endIn
34967
35148
 
34968
35149
  ${renderUserFacingFailure("recomp_unavailable")}`;
34969
35150
  }
34970
- saveRecompStagingPass(db, sessionId, passCount, candidateCompartments, candidateFacts);
34971
35151
  const lastCompartmentEnd = candidateCompartments[candidateCompartments.length - 1]?.endMessage ?? 0;
34972
35152
  const compartmentTagKeys = lastCompartmentEnd > 0 ? await getRawSessionTagKeysThrough2(sessionId, lastCompartmentEnd, { db }) : null;
34973
- const promoted = promoteRecompStagingWithM0Mutation(db, sessionId, leaseHolderId);
34974
- 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") {
34975
35158
  sessionLog2(sessionId, "recomp publish skipped: compartment lease no longer held");
34976
- return `## Magic Recomp — Skipped
34977
-
34978
- Another process acquired the compartment-state lease before recomp could publish. No state was written.`;
35159
+ return PUBLISH_LEASE_LOST;
34979
35160
  }
34980
35161
  afterPublish("compression-depth", () => clearCompressionDepth(db, sessionId));
34981
35162
  if (deps.preserveInjectionCacheUntilConsumed !== true) {
@@ -35068,25 +35249,6 @@ function snapRangeToCompartments(compartments, range) {
35068
35249
  tailCompartments: sorted.slice(lastEnclosingIdx + 1)
35069
35250
  };
35070
35251
  }
35071
- function compartmentToInput(c, newSequence) {
35072
- return {
35073
- sequence: newSequence,
35074
- startMessage: c.startMessage,
35075
- endMessage: c.endMessage,
35076
- startMessageId: c.startMessageId,
35077
- endMessageId: c.endMessageId,
35078
- startBlockIndex: c.startBlockIndex,
35079
- endBlockIndex: c.endBlockIndex,
35080
- title: c.title,
35081
- content: c.content,
35082
- p1: c.p1,
35083
- p2: c.p2,
35084
- p3: c.p3,
35085
- p4: c.p4,
35086
- importance: c.importance,
35087
- episodeType: c.episodeType
35088
- };
35089
- }
35090
35252
  async function executePartialRecompInternal(deps, range) {
35091
35253
  const {
35092
35254
  client,
@@ -35106,6 +35268,7 @@ Could not acquire the compartment-state lease for this session.`;
35106
35268
  }
35107
35269
  const leaseHolderId = holderId;
35108
35270
  updateSessionMeta(db, sessionId, { compartmentInProgress: true });
35271
+ let wroteStaging = false;
35109
35272
  try {
35110
35273
  let promoteFinal = function() {
35111
35274
  const newBuilt = candidateCompartments.slice(priorCompartments.length);
@@ -35141,7 +35304,12 @@ Could not acquire the compartment-state lease for this session.`;
35141
35304
  return null;
35142
35305
  }
35143
35306
  saveRecompStagingPass(db, sessionId, passCount + 1, merged, stagedFacts);
35144
- 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);
35145
35313
  if (!promoted) {
35146
35314
  log2("[magic-context] partial recomp promote returned null");
35147
35315
  return null;
@@ -35190,8 +35358,7 @@ ${snapResult.error}`;
35190
35358
  "",
35191
35359
  `An unfinished partial recomp is already staged for range ${storedRange.start}-${storedRange.end}, which does not match the requested range ${snapStart}-${snapEnd}.`,
35192
35360
  "",
35193
- "Resume that range by running `/ctx-recomp` with the same original arguments,",
35194
- "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."
35195
35362
  ].join(`
35196
35363
  `);
35197
35364
  }
@@ -35199,9 +35366,7 @@ ${snapResult.error}`;
35199
35366
  return [
35200
35367
  "## Magic Recomp — Failed",
35201
35368
  "",
35202
- "An unfinished full recomp is already staged for this session.",
35203
- "Resume it by running `/ctx-recomp` without arguments,",
35204
- "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.`
35205
35370
  ].join(`
35206
35371
  `);
35207
35372
  }
@@ -35223,6 +35388,7 @@ ${snapResult.error}`;
35223
35388
  passCount = 0;
35224
35389
  offset = snapStart;
35225
35390
  saveRecompStagingPass(db, sessionId, 0, candidateCompartments, stagedFacts);
35391
+ wroteStaging = true;
35226
35392
  setRecompPartialRange(db, sessionId, { start: snapStart, end: snapEnd });
35227
35393
  }
35228
35394
  let currentTokenBudget = historianChunkTokens;
@@ -35332,6 +35498,7 @@ ${renderUserFacingFailure("recomp_unavailable")}`;
35332
35498
  currentTokenBudget = historianChunkTokens;
35333
35499
  passAttempt = 1;
35334
35500
  saveRecompStagingPass(db, sessionId, passCount, candidateCompartments, stagedFacts);
35501
+ wroteStaging = true;
35335
35502
  const nextOffset = (validatedPass.compartments?.[validatedPass.compartments.length - 1]?.endMessage ?? chunk.endIndex) + 1;
35336
35503
  if (nextOffset <= offset) {
35337
35504
  return `## Magic Recomp — Failed
@@ -35363,9 +35530,7 @@ Partial recomp completed historian passes but the final compartment set failed v
35363
35530
  ${renderUserFacingFailure("recomp_unavailable")}`;
35364
35531
  } finally {
35365
35532
  updateSessionMeta(db, sessionId, { compartmentInProgress: false });
35366
- const leftoverStaging = getRecompStaging(db, sessionId);
35367
- const leftoverRange = getRecompPartialRange(db, sessionId);
35368
- if (leftoverStaging && leftoverRange) {} else if (leftoverStaging && !leftoverRange) {
35533
+ if (wroteStaging && getRecompStaging(db, sessionId) && !getRecompPartialRange(db, sessionId)) {
35369
35534
  log2(`[magic-context] partial recomp cleanup: clearing orphaned staging without range marker for session ${sessionId}`);
35370
35535
  clearRecompStaging(db, sessionId);
35371
35536
  }