@cortexkit/opencode-magic-context 0.49.33 → 0.49.34

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 (53) hide show
  1. package/dist/auto-search-worker.js +1 -1
  2. package/dist/chunk-embedding-write-worker.js +1 -1
  3. package/dist/{context-jyzkstnr.js → context-p3xrarzt.js} +10 -10
  4. package/dist/features/magic-context/compaction-marker.d.ts +22 -6
  5. package/dist/features/magic-context/compaction-marker.d.ts.map +1 -1
  6. package/dist/features/magic-context/storage-meta-persisted.d.ts +7 -0
  7. package/dist/features/magic-context/storage-meta-persisted.d.ts.map +1 -1
  8. package/dist/hooks/magic-context/compaction-marker-manager.d.ts +5 -5
  9. package/dist/hooks/magic-context/compaction-marker-manager.d.ts.map +1 -1
  10. package/dist/hooks/magic-context/compaction-marker-publication.d.ts +9 -0
  11. package/dist/hooks/magic-context/compaction-marker-publication.d.ts.map +1 -0
  12. package/dist/hooks/magic-context/inject-compartments.d.ts.map +1 -1
  13. package/dist/{index-94ef0qe2.js → index-04z754rd.js} +1 -1
  14. package/dist/{index-qr2mb02j.js → index-0677w9sd.js} +2 -2
  15. package/dist/{index-43vqx0za.js → index-07vskjn8.js} +3 -3
  16. package/dist/{index-0fe4q77z.js → index-7g9dr8gy.js} +34 -2
  17. package/dist/{index-3fkk2gwj.js → index-97spytxq.js} +11 -11
  18. package/dist/{index-4s4zq97n.js → index-9gpw8hrm.js} +1 -1
  19. package/dist/{index-2xh37qn5.js → index-atekmqef.js} +241 -53
  20. package/dist/{index-hbt0sbv2.js → index-fm36bjv4.js} +1 -1
  21. package/dist/{index-dq5xzeb9.js → index-ftr84kkv.js} +2 -2
  22. package/dist/{index-b7w46fp2.js → index-hbx7m8he.js} +4 -4
  23. package/dist/{index-3jmx3fae.js → index-m1x9ghk5.js} +1 -1
  24. package/dist/index.js +14 -14
  25. package/dist/{message-index-bounded-zq7a5nm6.js → message-index-bounded-qh91fdr3.js} +2 -2
  26. package/dist/migration-worker.js +1 -1
  27. package/dist/raw-ordinal-warmup-worker.js +2 -2
  28. package/dist/{read-session-chunk-1ndphmb8.js → read-session-chunk-kaghtr75.js} +1 -1
  29. package/dist/{recomp-orchestrator-skqzzvby.js → recomp-orchestrator-0y983w7h.js} +5 -5
  30. package/dist/{search-archive-sr07c6aj.js → search-archive-1kw2rp19.js} +2 -2
  31. package/dist/{search-040pac3a.js → search-p684j8ww.js} +4 -4
  32. package/dist/{transform-postprocess-phase-zx1peqma.js → transform-postprocess-phase-ph38mhrs.js} +6 -6
  33. package/dist/v2/auto-search-worker.js +1 -1
  34. package/dist/v2/chunk-embedding-write-worker.js +1 -1
  35. package/dist/v2/{context-3c4z2wj5.js → context-s60hcatx.js} +8 -8
  36. package/dist/v2/{message-index-bounded-jvgz7vk9.js → message-index-bounded-4htdr1j6.js} +2 -2
  37. package/dist/v2/migration-worker.js +1 -1
  38. package/dist/v2/raw-ordinal-warmup-worker.js +2 -2
  39. package/dist/v2/{read-session-chunk-djzgm4jg.js → read-session-chunk-1fa9qzwb.js} +1 -1
  40. package/dist/v2/{recomp-orchestrator-qfqdvbta.js → recomp-orchestrator-7q9nvxte.js} +4 -4
  41. package/dist/v2/{search-archive-n3dhns4r.js → search-archive-xfp51s0g.js} +2 -2
  42. package/dist/v2/{search-q3wkpe8t.js → search-wf8rqxhm.js} +3 -3
  43. package/dist/v2/{server-n14edf07.js → server-ajxhrgjv.js} +1 -1
  44. package/dist/v2/{server-rr4cbkr0.js → server-grakwy1v.js} +1 -1
  45. package/dist/v2/{server-d01pe8q5.js → server-jw5qe9y8.js} +1 -1
  46. package/dist/v2/{server-hwag0khr.js → server-m1pfg2d4.js} +1 -1
  47. package/dist/v2/{server-rb8m4vry.js → server-qvy4qavp.js} +34 -2
  48. package/dist/v2/{server-aqbm9c8d.js → server-z2wft9zv.js} +242 -55
  49. package/dist/v2/server.js +2 -2
  50. package/dist/v2/{wrapup-orchestrator-ga5vfmwr.js → wrapup-orchestrator-wxf7n5k6.js} +4 -4
  51. package/dist/{wrapup-orchestrator-dy8r3gp8.js → wrapup-orchestrator-ys2nrkkb.js} +6 -6
  52. package/package.json +1 -1
  53. package/src/shared/sqlite-transaction-mode-guard.test.ts +2 -0
@@ -9,7 +9,7 @@ import {
9
9
  } from "./index-b88dwwrh.js";
10
10
  import {
11
11
  cleanUserText2
12
- } from "./index-0fe4q77z.js";
12
+ } from "./index-7g9dr8gy.js";
13
13
  import {
14
14
  recordMessageFtsRowid2,
15
15
  recordIndexedMessageTime2,
@@ -65,7 +65,10 @@ import {
65
65
  getOverflowState,
66
66
  clearEmergencyRecovery,
67
67
  getPersistedCompactionMarkerState,
68
+ getCompactionMarkerPublicationState,
69
+ compareAndSetCompactionMarkerPublicationState,
68
70
  setPersistedCompactionMarkerState,
71
+ getDeferredClearedCompactionMarkerState,
69
72
  parseStrippedPlaceholderState,
70
73
  serializeStrippedPlaceholderState,
71
74
  THINKING_BINDING_RECOVERY_FROZEN_PREFIX,
@@ -98,7 +101,7 @@ import {
98
101
  getRawSessionTagKeysThrough2,
99
102
  getLegacyProtectedTailStartOrdinal2,
100
103
  readSessionChunk2
101
- } from "./index-0fe4q77z.js";
104
+ } from "./index-7g9dr8gy.js";
102
105
  import {
103
106
  getHarness2,
104
107
  harnessOwnsOpenCodeStore2
@@ -174,7 +177,7 @@ import {
174
177
  LATEST_SUPPORTED_VERSION,
175
178
  getPersistedSchemaVersion,
176
179
  openDatabase
177
- } from "./index-hbt0sbv2.js";
180
+ } from "./index-fm36bjv4.js";
178
181
  import {
179
182
  inRootAsyncContext2,
180
183
  Database2,
@@ -254,7 +257,7 @@ import {
254
257
  toMessageIndexSource,
255
258
  clearIndexedMessagesInTransaction,
256
259
  indexSourcesAfterOrdinal
257
- } from "./index-4s4zq97n.js";
260
+ } from "./index-9gpw8hrm.js";
258
261
  import {
259
262
  stripWellFormedLeadingTagPrefix,
260
263
  stripTagPrefix,
@@ -13405,6 +13408,80 @@ function getOpenCodeMessageById(sessionId, messageId) {
13405
13408
  const row = db.prepare(`SELECT id FROM message WHERE session_id = ? AND id = ? LIMIT 1`).get(sessionId, messageId);
13406
13409
  return row ?? null;
13407
13410
  }
13411
+ function planCompactionMarker(args, boundary) {
13412
+ const identity = `${args.sessionId}\x00${args.endMessageId}`;
13413
+ return {
13414
+ boundaryMessageId: boundary.id,
13415
+ summaryMessageId: generateMessageId(boundary.timeCreated + 1, 1n, `${identity}\x00summary-message`),
13416
+ compactionPartId: generatePartId(boundary.timeCreated, 1n, `${identity}\x00compaction-part`),
13417
+ summaryPartId: generatePartId(boundary.timeCreated + 1, 2n, `${identity}\x00summary-part`)
13418
+ };
13419
+ }
13420
+ function isCompactionMarkerIntentAbsent(marker, targetEndMessageId) {
13421
+ if (!targetEndMessageId)
13422
+ return false;
13423
+ const db = getWritableOpenCodeDb();
13424
+ return !db.prepare(`SELECT 1 FROM message WHERE id IN (?, ?)
13425
+ UNION ALL SELECT 1 FROM part WHERE id IN (?, ?) LIMIT 1`).get(targetEndMessageId, marker.summaryMessageId, marker.compactionPartId, marker.summaryPartId);
13426
+ }
13427
+ function withCompactionMarkerPublicationLock(operation) {
13428
+ return runMarkerWriteTransaction(getWritableOpenCodeDb(), "compaction-marker-replace", operation);
13429
+ }
13430
+ function inspectCompactionMarkerPublication(sessionId, recognized, summaryText) {
13431
+ const db = getWritableOpenCodeDb();
13432
+ const basis = readMarkerCandidateBasis2(db, sessionId);
13433
+ if (!basis)
13434
+ return { kind: "deferred" };
13435
+ const pairs = [];
13436
+ for (const id of basis.ids) {
13437
+ const rows = db.prepare(`SELECT m.id AS summaryId, p.message_id AS boundaryId, p.id AS partId
13438
+ FROM message m JOIN part p ON p.message_id = json_extract(m.data, '$.parentID')
13439
+ AND +p.session_id = m.session_id
13440
+ WHERE m.id = ? AND m.session_id = ? AND json_extract(m.data, '$.summary') = 1
13441
+ AND COALESCE(json_extract(m.data, '$.finish'), '') <> ''
13442
+ AND json_extract(p.data, '$.type') = 'compaction'`).all(id, sessionId);
13443
+ pairs.push(...rows);
13444
+ }
13445
+ if (pairs.length > 1)
13446
+ return { kind: "ambiguous" };
13447
+ if (pairs.length === 0) {
13448
+ for (const marker of recognized) {
13449
+ if (db.prepare(`SELECT 1 FROM message WHERE id = ?
13450
+ UNION ALL SELECT 1 FROM part WHERE id IN (?, ?) LIMIT 1`).get(marker.summaryMessageId, marker.compactionPartId, marker.summaryPartId))
13451
+ return { kind: "ambiguous" };
13452
+ }
13453
+ return { kind: "verified", marker: null };
13454
+ }
13455
+ const pair = pairs[0];
13456
+ const marker = recognized.find((item) => item.summaryMessageId === pair.summaryId && item.boundaryMessageId === pair.boundaryId && item.compactionPartId === pair.partId);
13457
+ if (!marker)
13458
+ return { kind: "ambiguous" };
13459
+ for (const other of recognized) {
13460
+ if (other.summaryMessageId === marker.summaryMessageId && other.compactionPartId === marker.compactionPartId && other.summaryPartId === marker.summaryPartId)
13461
+ continue;
13462
+ if (db.prepare(`SELECT 1 FROM message WHERE id = ?
13463
+ UNION ALL SELECT 1 FROM part WHERE id IN (?, ?) LIMIT 1`).get(other.summaryMessageId, other.compactionPartId, other.summaryPartId))
13464
+ return { kind: "ambiguous" };
13465
+ }
13466
+ const row = db.prepare(`SELECT c.data AS compactionData FROM message m
13467
+ JOIN message b ON b.id = ? AND b.session_id = m.session_id
13468
+ JOIN part c ON c.id = ? AND c.message_id = b.id AND c.session_id = m.session_id
13469
+ JOIN part t ON t.id = ? AND t.message_id = m.id AND t.session_id = m.session_id
13470
+ WHERE m.id = ? AND m.session_id = ?
13471
+ AND json_extract(b.data, '$.role') = 'user'
13472
+ AND json_extract(m.data, '$.role') = 'assistant'
13473
+ AND json_extract(m.data, '$.parentID') = b.id
13474
+ AND json_extract(m.data, '$.summary') = 1
13475
+ AND json_extract(m.data, '$.finish') = 'stop'
13476
+ AND json_extract(m.data, '$.error') IS NULL
13477
+ AND json_extract(m.data, '$.providerID') = 'magic-context'
13478
+ AND json_extract(m.data, '$.modelID') = 'magic-context'
13479
+ AND json_extract(t.data, '$.type') = 'text' AND json_extract(t.data, '$.text') = ?
13480
+ AND (SELECT COUNT(*) FROM part p WHERE p.message_id = m.id AND +p.session_id = m.session_id) = 1`).get(marker.boundaryMessageId, marker.compactionPartId, marker.summaryPartId, marker.summaryMessageId, sessionId, summaryText);
13481
+ if (!row || !isMcCanonicalCompactionPartData(JSON.parse(row.compactionData)) || findBoundaryUserMessage(sessionId, marker.boundaryMessageId)?.id !== marker.boundaryMessageId)
13482
+ return { kind: "ambiguous" };
13483
+ return { kind: "verified", marker };
13484
+ }
13408
13485
  var LEGACY_MARKER_LINEAGE_SQL = `SELECT m.id
13409
13486
  FROM message m
13410
13487
  WHERE +m.session_id = ? AND m.id IN (SELECT value FROM json_each(?)) AND m.id <> ?
@@ -13454,10 +13531,11 @@ function injectCompactionMarkerFromBasis(args, validatedBasis) {
13454
13531
  return null;
13455
13532
  }
13456
13533
  const boundaryTime = boundary.timeCreated;
13457
- const markerIdentity = `${args.sessionId}\x00${args.endMessageId}`;
13458
- const summaryMsgId = generateMessageId(boundaryTime + 1, 1n, `${markerIdentity}\x00summary-message`);
13459
- const compactionPartId = generatePartId(boundaryTime, 1n, `${markerIdentity}\x00compaction-part`);
13460
- const summaryPartId = generatePartId(boundaryTime + 1, 2n, `${markerIdentity}\x00summary-part`);
13534
+ const {
13535
+ summaryMessageId: summaryMsgId,
13536
+ compactionPartId,
13537
+ summaryPartId
13538
+ } = planCompactionMarker(args, boundary);
13461
13539
  const summaryMsgData = JSON.stringify({
13462
13540
  role: "assistant",
13463
13541
  parentID: boundary.id,
@@ -13617,10 +13695,12 @@ function listSessionCompactionMarkers(sessionId) {
13617
13695
  markers.sort((left, right) => left.timeCreated - right.timeCreated || left.compactionPartId.localeCompare(right.compactionPartId));
13618
13696
  return markers.map(({ timeCreated: _, ...marker }) => marker);
13619
13697
  }
13620
- function removeForeignCompactionMarker(sessionId, marker, protectedSummaryMessageId) {
13698
+ function removeForeignCompactionMarker(sessionId, marker, protectedSummaryMessageId, shouldRemove) {
13621
13699
  try {
13622
13700
  const db = getWritableOpenCodeDb("removal");
13623
13701
  runMarkerRemovalTransaction(db, () => {
13702
+ if (shouldRemove && !shouldRemove())
13703
+ return;
13624
13704
  const deletePartsOfMessage = db.prepare("DELETE FROM part WHERE +session_id = ? AND message_id = ?");
13625
13705
  const deleteMessage = db.prepare("DELETE FROM message WHERE session_id = ? AND id = ?");
13626
13706
  for (const summaryMessageId of marker.summaryMessageIds) {
@@ -13815,24 +13895,118 @@ function removeCompactionMarker(state) {
13815
13895
  }
13816
13896
  }
13817
13897
 
13818
- // src/hooks/magic-context/compaction-marker-manager.ts
13819
- var MARKER_SUMMARY_TEXT = "[Compacted by magic-context — session history is managed by the plugin]";
13820
- function dropMarkerSummaryTag(db, sessionId, summaryMessageId) {
13821
- const tagNumber = getTagNumberByMessageId2(db, sessionId, `${summaryMessageId}:p0`);
13822
- if (tagNumber !== null)
13823
- updateTagStatus2(db, sessionId, tagNumber, "dropped");
13898
+ // src/hooks/magic-context/compaction-marker-publication.ts
13899
+ function samePair(left, right) {
13900
+ return left.boundaryMessageId === right.boundaryMessageId && left.summaryMessageId === right.summaryMessageId && left.compactionPartId === right.compactionPartId && left.summaryPartId === right.summaryPartId;
13824
13901
  }
13825
- function persistMarkerStateAndDropReplacedTag(db, sessionId, state, replacedSummaryMessageId) {
13826
- let transactionStartedAt = 0;
13827
- db.transaction(() => {
13828
- transactionStartedAt = performance.now();
13829
- setPersistedCompactionMarkerState(db, sessionId, state);
13830
- if (replacedSummaryMessageId !== null) {
13831
- dropMarkerSummaryTag(db, sessionId, replacedSummaryMessageId);
13902
+ function publishRecoverableCompactionMarker(db, args, targetIsCurrent) {
13903
+ const { sessionId } = args;
13904
+ let raw = "";
13905
+ let previous = null;
13906
+ let oldSummary = null;
13907
+ let intended;
13908
+ let reason = "publication-failed";
13909
+ let recovered;
13910
+ let cut = "uncertain";
13911
+ let writingState = false;
13912
+ const persist = (state) => {
13913
+ writingState = true;
13914
+ db.transaction(() => {
13915
+ raw = compareAndSetCompactionMarkerPublicationState(db, sessionId, raw, state, null);
13916
+ if (previous && previous.summaryMessageId !== state.summaryMessageId) {
13917
+ const tag = getTagNumberByMessageId2(db, sessionId, `${previous.summaryMessageId}:p0`);
13918
+ if (tag !== null)
13919
+ updateTagStatus2(db, sessionId, tag, "dropped");
13920
+ }
13921
+ }).immediate();
13922
+ writingState = false;
13923
+ previous = state;
13924
+ };
13925
+ try {
13926
+ cut = getCompactionMarkerPublicationState(db, sessionId).pending ? "uncertain" : "definitely-no-cut";
13927
+ const result = withCompactionMarkerPublicationLock(() => {
13928
+ const snapshot = getCompactionMarkerPublicationState(db, sessionId);
13929
+ if (snapshot.pending)
13930
+ cut = "uncertain";
13931
+ raw = snapshot.raw;
13932
+ previous = getPersistedCompactionMarkerState(db, sessionId) ?? getDeferredClearedCompactionMarkerState(db, sessionId);
13933
+ oldSummary = previous?.summaryMessageId ?? null;
13934
+ if (snapshot.pending && (snapshot.pending.boundaryOrdinal > args.endOrdinal || snapshot.pending.boundaryOrdinal === args.endOrdinal && snapshot.pending.targetEndMessageId !== args.endMessageId) && !isCompactionMarkerIntentAbsent(snapshot.pending, snapshot.pending.targetEndMessageId))
13935
+ throw new Error("a newer marker publication intent is pending");
13936
+ const boundary = findBoundaryUserMessage(sessionId, args.endMessageId);
13937
+ if (!targetIsCurrent() || !boundary || boundary.id !== args.resolvedBoundary?.id || boundary.timeCreated !== args.resolvedBoundary.timeCreated)
13938
+ throw new Error("marker publication frontier changed before publication");
13939
+ intended = {
13940
+ ...planCompactionMarker(args, boundary),
13941
+ boundaryOrdinal: args.endOrdinal,
13942
+ targetEndMessageId: args.endMessageId
13943
+ };
13944
+ let pending = snapshot.pending;
13945
+ if (pending) {
13946
+ const pendingTarget = pending.targetEndMessageId;
13947
+ const pendingBoundary = pendingTarget ? findBoundaryUserMessage(sessionId, pendingTarget) : null;
13948
+ const compartments = pendingTarget ? getCompartmentsByEndMessageId(db, sessionId, pendingTarget) : [];
13949
+ const validTarget = pending.targetEndMessageId === args.endMessageId && pending.boundaryOrdinal === args.endOrdinal || compartments.length === 1 && compartments[0].endMessage === pending.boundaryOrdinal;
13950
+ if (!validTarget || !pendingBoundary || !pendingTarget || !samePair(pending, planCompactionMarker({ ...args, endMessageId: pendingTarget }, pendingBoundary)))
13951
+ pending = null;
13952
+ }
13953
+ const inspection = inspectCompactionMarkerPublication(sessionId, [intended, ...previous ? [previous] : [], ...pending ? [pending] : []], args.summaryText);
13954
+ if (inspection.kind === "deferred") {
13955
+ reason = "candidate-preparation";
13956
+ return {
13957
+ kind: cut === "uncertain" ? "uncertain" : "deferred",
13958
+ error: new Error("marker candidate preparation pending")
13959
+ };
13960
+ }
13961
+ if (inspection.kind === "ambiguous") {
13962
+ reason = "ambiguous-left-alone";
13963
+ return {
13964
+ kind: cut,
13965
+ error: new Error("unverified or ambiguous host marker pairs; left alone")
13966
+ };
13967
+ }
13968
+ cut = "definitely-no-cut";
13969
+ const host = inspection.marker;
13970
+ if (host && (pending && samePair(host, pending) || samePair(host, intended))) {
13971
+ const adopted = pending && samePair(host, pending) ? pending : intended;
13972
+ recovered = adopted === pending ? "pending-intent-recovered" : "adopted-existing-pair";
13973
+ cut = "uncertain";
13974
+ if (samePair(host, intended))
13975
+ return { kind: "committed", marker: host };
13976
+ persist(adopted);
13977
+ }
13978
+ writingState = true;
13979
+ raw = compareAndSetCompactionMarkerPublicationState(db, sessionId, raw, previous, intended);
13980
+ writingState = false;
13981
+ cut = "uncertain";
13982
+ const replacement = replaceCompactionMarker(host, {
13983
+ ...args,
13984
+ resolvedBoundary: boundary
13985
+ });
13986
+ if (recovered && replacement.kind !== "committed")
13987
+ return { kind: "uncertain", error: replacement.error };
13988
+ if (replacement.kind !== "committed")
13989
+ cut = replacement.kind === "uncertain" ? "uncertain" : "definitely-no-cut";
13990
+ return replacement;
13991
+ });
13992
+ if (result.kind === "committed") {
13993
+ if (!intended)
13994
+ throw new Error("committed marker has no publication intent");
13995
+ persist(intended);
13996
+ reason = recovered ?? "published";
13832
13997
  }
13833
- }).immediate();
13834
- logSlowWriteTransaction("marker-drain", transactionStartedAt);
13998
+ return result;
13999
+ } catch (error) {
14000
+ if (writingState)
14001
+ reason = "state-write-failed";
14002
+ return { kind: cut, error: error instanceof Error ? error : new Error(String(error)) };
14003
+ } finally {
14004
+ sessionLog2(sessionId, `compaction-marker publication reason=${reason} oldSummary=${oldSummary ?? "none"} newSummary=${intended?.summaryMessageId ?? "none"} target=${args.endMessageId} at=${Date.now()}`);
14005
+ }
13835
14006
  }
14007
+
14008
+ // src/hooks/magic-context/compaction-marker-manager.ts
14009
+ var MARKER_SUMMARY_TEXT = "[Compacted by magic-context — session history is managed by the plugin]";
13836
14010
  function markerUpdateDefinitelyDidNotCut(outcome) {
13837
14011
  return outcome.kind === "already-current" || outcome.kind === "deferred" || outcome.kind === "stale-skip" || outcome.kind === "retryable-failure" && outcome.cut === "definitely-no-cut";
13838
14012
  }
@@ -13901,7 +14075,7 @@ function boundaryWouldDiscardUncoveredMessage(db, sessionId, ordinal, boundaryMe
13901
14075
  return false;
13902
14076
  }
13903
14077
  function applyDeferredCompactionMarker(db, sessionId, pending, directory, trustedBoundary) {
13904
- let cut = "definitely-no-cut";
14078
+ let cut = "uncertain";
13905
14079
  let stepStartedAt = performance.now();
13906
14080
  const stepMs = [];
13907
14081
  const endStep = (name) => {
@@ -13910,41 +14084,61 @@ function applyDeferredCompactionMarker(db, sessionId, pending, directory, truste
13910
14084
  stepStartedAt = now;
13911
14085
  };
13912
14086
  try {
14087
+ cut = getCompactionMarkerPublicationState(db, sessionId).pending ? "uncertain" : "definitely-no-cut";
14088
+ const unresolvedIntentFailure = () => {
14089
+ const alreadyUncertain = cut === "uncertain";
14090
+ cut = "uncertain";
14091
+ if (getCompactionMarkerPublicationState(db, sessionId).pending || alreadyUncertain) {
14092
+ return {
14093
+ kind: "retryable-failure",
14094
+ cut,
14095
+ error: new Error("unresolved marker publication intent; retaining retry state")
14096
+ };
14097
+ }
14098
+ cut = "definitely-no-cut";
14099
+ return null;
14100
+ };
13913
14101
  const responseFencesTarget = trustedBoundary !== undefined && Number.isSafeInteger(trustedBoundary.rowVersion) && trustedBoundary.rowVersion > 0 && trustedBoundary.ordinal === pending.ordinal && trustedBoundary.endMessageId === pending.endMessageId;
13914
14102
  const validation = responseFencesTarget ? "ok" : validatePendingTarget(db, sessionId, pending);
13915
14103
  endStep("validate");
13916
14104
  if (validation !== "ok") {
14105
+ const unresolved = unresolvedIntentFailure();
14106
+ if (unresolved)
14107
+ return unresolved;
13917
14108
  sessionLog2(sessionId, `compaction-marker drain: stale-skip (${validation}) for ordinal ${pending.ordinal} endMessageId=${pending.endMessageId}`);
13918
14109
  return { kind: "stale-skip", reason: validation };
13919
14110
  }
13920
14111
  const existing = getPersistedCompactionMarkerState(db, sessionId);
13921
14112
  if (existing && existingMarkerAlreadyCoversTarget(sessionId, existing, pending.ordinal, pending.endMessageId)) {
13922
- return { kind: "already-current" };
14113
+ if (!unresolvedIntentFailure())
14114
+ return { kind: "already-current" };
13923
14115
  }
13924
14116
  const boundary = findBoundaryUserMessage(sessionId, pending.endMessageId);
13925
14117
  endStep("boundary");
13926
14118
  if (!boundary) {
13927
- return {
14119
+ return unresolvedIntentFailure() ?? {
13928
14120
  kind: "retryable-failure",
13929
14121
  cut: "definitely-no-cut",
13930
14122
  error: new Error(`no user boundary found at or before endMessageId ${pending.endMessageId} (ordinal ${pending.ordinal}); preserving existing marker`)
13931
14123
  };
13932
14124
  }
13933
14125
  if (boundaryWouldDiscardUncoveredMessage(db, sessionId, pending.ordinal, boundary.id)) {
14126
+ const unresolved = unresolvedIntentFailure();
14127
+ if (unresolved)
14128
+ return unresolved;
13934
14129
  sessionLog2(sessionId, `compaction-marker drain: stale-skip (partial-message-boundary) for ordinal ${pending.ordinal} endMessageId=${pending.endMessageId}`);
13935
14130
  return { kind: "stale-skip", reason: "partial-message-boundary" };
13936
14131
  }
13937
14132
  endStep("discardCheck");
13938
- const removedSummaryMessageId = existing?.summaryMessageId ?? null;
13939
14133
  cut = "uncertain";
13940
- const replacement = replaceCompactionMarker(existing, {
14134
+ const replacement = publishRecoverableCompactionMarker(db, {
13941
14135
  sessionId,
13942
14136
  endOrdinal: pending.ordinal,
13943
14137
  endMessageId: pending.endMessageId,
13944
14138
  summaryText: MARKER_SUMMARY_TEXT,
13945
14139
  directory: directory ?? process.cwd(),
13946
14140
  resolvedBoundary: boundary
13947
- });
14141
+ }, () => JSON.stringify(getPersistedCompactionMarkerState(db, sessionId)) === JSON.stringify(existing) && (responseFencesTarget || validatePendingTarget(db, sessionId, pending) === "ok"));
13948
14142
  endStep("replace");
13949
14143
  if (replacement.kind === "deferred")
13950
14144
  return { kind: "deferred", reason: "candidate-preparation" };
@@ -13955,14 +14149,8 @@ function applyDeferredCompactionMarker(db, sessionId, pending, directory, truste
13955
14149
  error: replacement.error
13956
14150
  };
13957
14151
  }
13958
- const result = replacement.marker;
13959
- persistMarkerStateAndDropReplacedTag(db, sessionId, {
13960
- ...result,
13961
- boundaryOrdinal: pending.ordinal,
13962
- targetEndMessageId: pending.endMessageId
13963
- }, removedSummaryMessageId);
13964
14152
  endStep("persist");
13965
- sessionLog2(sessionId, `compaction-marker drain: applied at ordinal ${pending.ordinal}, boundary user msg ${result.boundaryMessageId} ${stepMs.join(" ")}`);
14153
+ sessionLog2(sessionId, `compaction-marker drain: applied at ordinal ${pending.ordinal}, boundary user msg ${replacement.marker.boundaryMessageId} ${stepMs.join(" ")}`);
13966
14154
  return {
13967
14155
  kind: "applied",
13968
14156
  markerOrdinal: pending.ordinal
@@ -13983,8 +14171,7 @@ function updateCompactionMarkerAfterPublication(db, sessionId, lastCompartmentEn
13983
14171
  return false;
13984
14172
  }
13985
14173
  const existing = getPersistedCompactionMarkerState(db, sessionId);
13986
- const removedSummaryMessageId = existing?.summaryMessageId ?? null;
13987
- if (existing) {
14174
+ if (existing && !getCompactionMarkerPublicationState(db, sessionId).pending) {
13988
14175
  if (existingMarkerAlreadyCoversTarget(sessionId, existing, lastCompartmentEnd, targetEndMessageId)) {
13989
14176
  return true;
13990
14177
  }
@@ -13997,22 +14184,15 @@ function updateCompactionMarkerAfterPublication(db, sessionId, lastCompartmentEn
13997
14184
  if (boundaryWouldDiscardUncoveredMessage(db, sessionId, lastCompartmentEnd, boundary.id)) {
13998
14185
  return false;
13999
14186
  }
14000
- const replacement = replaceCompactionMarker(existing, {
14187
+ const replacement = publishRecoverableCompactionMarker(db, {
14001
14188
  sessionId,
14002
14189
  endOrdinal: lastCompartmentEnd,
14003
14190
  endMessageId: targetEndMessageId,
14004
14191
  summaryText: MARKER_SUMMARY_TEXT,
14005
14192
  directory: directory ?? process.cwd(),
14006
14193
  resolvedBoundary: boundary
14007
- });
14194
+ }, () => JSON.stringify(getPersistedCompactionMarkerState(db, sessionId)) === JSON.stringify(existing) && getCompartmentEndMessageIdForOrdinal(db, sessionId, lastCompartmentEnd) === targetEndMessageId);
14008
14195
  if (replacement.kind === "committed") {
14009
- const result = replacement.marker;
14010
- persistMarkerStateAndDropReplacedTag(db, sessionId, {
14011
- ...result,
14012
- boundaryOrdinal: lastCompartmentEnd,
14013
- targetEndMessageId
14014
- }, removedSummaryMessageId);
14015
- sessionLog2(sessionId, `compaction-marker: injected at ordinal ${lastCompartmentEnd}, boundary user msg ${result.boundaryMessageId}`);
14016
14196
  return true;
14017
14197
  }
14018
14198
  return false;
@@ -14030,13 +14210,13 @@ function removeCompactionMarkerForSession(db, sessionId) {
14030
14210
  }
14031
14211
  }
14032
14212
  }
14033
- function reconcileForkOrphanedCompactionMarkers(db, sessionId) {
14034
- if (getHarness2() !== "opencode") {
14213
+ function reconcileForkOrphanedCompactionMarkers(db, sessionId, isCacheBusting) {
14214
+ if (!isCacheBusting || getHarness2() !== "opencode") {
14035
14215
  return { removed: 0, failed: false };
14036
14216
  }
14037
14217
  try {
14038
14218
  const owned = getPersistedCompactionMarkerState(db, sessionId);
14039
- if (!owned) {
14219
+ if (!owned || getCompactionMarkerPublicationState(db, sessionId).pending) {
14040
14220
  return { removed: 0, failed: false };
14041
14221
  }
14042
14222
  const markers = listSessionCompactionMarkers(sessionId);
@@ -14057,7 +14237,15 @@ function reconcileForkOrphanedCompactionMarkers(db, sessionId) {
14057
14237
  if (!currentOwned || marker.compactionPartId === currentOwned.compactionPartId) {
14058
14238
  continue;
14059
14239
  }
14060
- const ok = removeForeignCompactionMarker(sessionId, marker, currentOwned.summaryMessageId);
14240
+ let protectedByState = false;
14241
+ const ok = removeForeignCompactionMarker(sessionId, marker, currentOwned.summaryMessageId, () => db.transaction(() => {
14242
+ const publication = getCompactionMarkerPublicationState(db, sessionId);
14243
+ const latestOwned = getPersistedCompactionMarkerState(db, sessionId);
14244
+ protectedByState = Boolean(publication.pending || !latestOwned || marker.compactionPartId === latestOwned.compactionPartId || marker.summaryMessageIds.includes(latestOwned.summaryMessageId) || compareOpenCodeMessagesByCanonicalOrder(sessionId, marker.boundaryMessageId, latestOwned.boundaryMessageId) !== 1);
14245
+ return !protectedByState;
14246
+ }).deferred());
14247
+ if (protectedByState)
14248
+ continue;
14061
14249
  if (ok) {
14062
14250
  removed += 1;
14063
14251
  sessionLog2(sessionId, `compaction-marker hygiene: removed fork-orphaned marker part=${marker.compactionPartId} boundary=${marker.boundaryMessageId} (outranked owned boundary ${currentOwned.boundaryMessageId})`);
@@ -14902,8 +15090,8 @@ function prepareCompartmentInjection(db, sessionId, messages, isCacheBusting, co
14902
15090
  resultEndMessageId = trimEndMessageId;
14903
15091
  } else {
14904
15092
  const degradedCount = noteDegradedRebuild(sessionId);
14905
- if (degradedCount === 1) {
14906
- reconcileForkOrphanedCompactionMarkers(db, sessionId);
15093
+ if (isCacheBusting) {
15094
+ reconcileForkOrphanedCompactionMarkers(db, sessionId, isCacheBusting);
14907
15095
  }
14908
15096
  let reAnchored = false;
14909
15097
  if (degradedCount >= REANCHOR_MIN_DEGRADED_PASSES && isCacheBusting) {
@@ -1279,7 +1279,7 @@ function finishDatabaseOpen(db, dbPath, explicitDbPath, latestSupportedVersion)
1279
1279
  state.running = startMessageFtsRowidMapBackfill2(db, signal).then(async () => {
1280
1280
  if (signal.aborted || !readsOpenCodeStore)
1281
1281
  return;
1282
- const { readRawSessionMessagePage, readRawSessionMessages } = await importPluginModule(() => import("./read-session-chunk-1ndphmb8.js"));
1282
+ const { readRawSessionMessagePage, readRawSessionMessages } = await importPluginModule(() => import("./read-session-chunk-kaghtr75.js"));
1283
1283
  const { startMessageTimeBackfill } = await importPluginModule(() => import("./message-time-backfill-4qva0b4f.js"));
1284
1284
  if (signal.aborted)
1285
1285
  return;
@@ -3,12 +3,12 @@ import {
3
3
  } from "./index-h7tgn49j.js";
4
4
  import {
5
5
  clearEmergencyRecovery
6
- } from "./index-0fe4q77z.js";
6
+ } from "./index-7g9dr8gy.js";
7
7
  import {
8
8
  requestPendingMaterialization,
9
9
  dropSlot,
10
10
  executeContextRecomp
11
- } from "./index-2xh37qn5.js";
11
+ } from "./index-atekmqef.js";
12
12
  import {
13
13
  renderUserFacingFailure,
14
14
  userFacingFailureCode
@@ -140,11 +140,11 @@ import {
140
140
  peekNoteNudgeText,
141
141
  markNoteNudgeDelivered,
142
142
  getActiveCompartmentRun
143
- } from "./index-2xh37qn5.js";
143
+ } from "./index-atekmqef.js";
144
144
  import {
145
145
  cleanSearchText,
146
146
  matchedSearchSnippet
147
- } from "./index-4s4zq97n.js";
147
+ } from "./index-9gpw8hrm.js";
148
148
  import {
149
149
  stripSystemInjection,
150
150
  isTextPart,
@@ -242,7 +242,7 @@ import {
242
242
  extractToolCallObservation,
243
243
  ToolMutationBatch,
244
244
  createToolDropTarget
245
- } from "./index-0fe4q77z.js";
245
+ } from "./index-7g9dr8gy.js";
246
246
  import {
247
247
  isValidLanguageCode
248
248
  } from "./index-nxrsns5x.js";
@@ -260,7 +260,7 @@ import {
260
260
  import {
261
261
  getMessageIndexEpoch,
262
262
  isMessageIndexSearchable
263
- } from "./index-94ef0qe2.js";
263
+ } from "./index-04z754rd.js";
264
264
  import {
265
265
  userFacingFailureCode
266
266
  } from "./index-as2amvn3.js";
@@ -17,7 +17,7 @@ import {
17
17
  import {
18
18
  hasRawMessageProvider2,
19
19
  readRawSessionMessageIdOrdinalsForRange2
20
- } from "./index-0fe4q77z.js";
20
+ } from "./index-7g9dr8gy.js";
21
21
 
22
22
  // src/tools/ctx-expand/search-archive.ts
23
23
  var archiveReadsOnThisThread = 0;
package/dist/index.js CHANGED
@@ -28,7 +28,7 @@ import {
28
28
  detectOverflow,
29
29
  isAnthropicFamilyRoute,
30
30
  readRawSessionMessages2
31
- } from "./index-0fe4q77z.js";
31
+ } from "./index-7g9dr8gy.js";
32
32
  import {
33
33
  setHarness2
34
34
  } from "./index-pavzsdc6.js";
@@ -99,7 +99,7 @@ import {
99
99
  checkCompactionMarkerConsistency,
100
100
  clearInjectionCache,
101
101
  clearNoteNudgeTriggerOnly
102
- } from "./index-2xh37qn5.js";
102
+ } from "./index-atekmqef.js";
103
103
  import"./index-sd3egckz.js";
104
104
  import {
105
105
  hasTrustedAbsoluteWall,
@@ -186,7 +186,7 @@ import {
186
186
  parameterDescriptionsFor,
187
187
  MagicContextRpcServer,
188
188
  applyHiddenSubagentTemperature
189
- } from "./index-3fkk2gwj.js";
189
+ } from "./index-97spytxq.js";
190
190
  import {
191
191
  resolveOpenCodeDbPath,
192
192
  openCodeDbPathExists,
@@ -210,7 +210,7 @@ import {
210
210
  openDatabaseAsync,
211
211
  isDatabasePersisted,
212
212
  getDatabasePersistenceError
213
- } from "./index-hbt0sbv2.js";
213
+ } from "./index-fm36bjv4.js";
214
214
  import {
215
215
  setHomeProjectPermission,
216
216
  ProjectIdentityError,
@@ -253,7 +253,7 @@ import"./index-wfybj1dw.js";
253
253
  import {
254
254
  getDefaultSubcConnectionFile,
255
255
  SubcModuleTransport
256
- } from "./index-qr2mb02j.js";
256
+ } from "./index-0677w9sd.js";
257
257
  import"./index-qt1qqasc.js";
258
258
  import"./index-rrv26qjz.js";
259
259
  import {
@@ -292,7 +292,7 @@ import {
292
292
  import"./index-v7287tzq.js";
293
293
  import {
294
294
  deleteIndexedMessage
295
- } from "./index-4s4zq97n.js";
295
+ } from "./index-9gpw8hrm.js";
296
296
  import"./index-as2amvn3.js";
297
297
  import {
298
298
  pushNotification2
@@ -309,13 +309,13 @@ import {
309
309
  clearToolPermissionDenied,
310
310
  collectForeignTextParts,
311
311
  resetDegradedCacheCount2
312
- } from "./index-b7w46fp2.js";
312
+ } from "./index-hbx7m8he.js";
313
313
  import {
314
314
  scheduleClearAndReindex
315
- } from "./index-94ef0qe2.js";
315
+ } from "./index-04z754rd.js";
316
316
  import {
317
317
  runManagedRecomp2
318
- } from "./index-dq5xzeb9.js";
318
+ } from "./index-ftr84kkv.js";
319
319
  import {
320
320
  isValidSemver,
321
321
  compareSemverCore
@@ -323,9 +323,9 @@ import {
323
323
  import"./index-fmsr7v69.js";
324
324
  import {
325
325
  runManagedWrapup2
326
- } from "./index-43vqx0za.js";
326
+ } from "./index-07vskjn8.js";
327
327
  import"./index-kaqs6h31.js";
328
- import"./index-3jmx3fae.js";
328
+ import"./index-m1x9ghk5.js";
329
329
  import {
330
330
  isDreamerRunnable,
331
331
  isSmartNoteSurfaceAvailable,
@@ -8193,7 +8193,7 @@ var require_src2 = __commonJS(function(exports, module) {
8193
8193
  // package.json
8194
8194
  var package_default = {
8195
8195
  name: "@cortexkit/opencode-magic-context",
8196
- version: "0.49.33",
8196
+ version: "0.49.34",
8197
8197
  type: "module",
8198
8198
  description: "OpenCode plugin for Magic Context — cross-session memory and context management",
8199
8199
  main: "dist/index.js",
@@ -12047,7 +12047,7 @@ async function setup(context) {
12047
12047
  if (claimStorageBackupWarningCheck() && isMagicContextStorageOutsideEngram(storageDir)) {
12048
12048
  log2(`[magic-context] Magic Context storage is at ${storageDir}, outside the folder Engram backs up (~/.local/share/cortexkit/magic-context). It is not included in CortexKit backups.`);
12049
12049
  }
12050
- const { registerContext } = await import("./context-jyzkstnr.js");
12050
+ const { registerContext } = await import("./context-p3xrarzt.js");
12051
12051
  setHarness2("opencode2");
12052
12052
  bindStaleBuildNotice({}, import.meta.url, "opencode2");
12053
12053
  const duties = await registerContext(context);
@@ -12520,7 +12520,7 @@ var server = async (ctx) => {
12520
12520
  rustReplayParticipant: () => magicContextRuntime.magicContext?.getRustReplayParticipant?.() ?? null,
12521
12521
  onStorageBusyRefusal: async (sessionId, message) => {
12522
12522
  const { sendStatusNotification } = await importPluginModule(() => import("./send-session-notification-vz86nt79.js"));
12523
- const { abortSessionFailClosed } = await importPluginModule(() => import("./transform-postprocess-phase-zx1peqma.js"));
12523
+ const { abortSessionFailClosed } = await importPluginModule(() => import("./transform-postprocess-phase-ph38mhrs.js"));
12524
12524
  await sendStatusNotification(ctx.client, sessionId, message, {
12525
12525
  toastDurationMs: 15000
12526
12526
  });
@@ -16,7 +16,7 @@ import"./index-cpjk5jd2.js";
16
16
  import"./index-rverk2vz.js";
17
17
  import"./index-58e3y90n.js";
18
18
  import"./index-y1qwzvxn.js";
19
- import"./index-0fe4q77z.js";
19
+ import"./index-7g9dr8gy.js";
20
20
  import"./index-s1n8dd2n.js";
21
21
  import {
22
22
  MESSAGE_INDEX_MAX_FTS_BYTES,
@@ -25,7 +25,7 @@ import {
25
25
  markMessageIndexDirty,
26
26
  getIndexableContent,
27
27
  indexSingleMessage
28
- } from "./index-4s4zq97n.js";
28
+ } from "./index-9gpw8hrm.js";
29
29
  import"./index-v15ne3a3.js";
30
30
  import"./index-t5pck3ss.js";
31
31
 
@@ -19,7 +19,7 @@ import"./index-fb3zxn06.js";
19
19
  import {
20
20
  setSqlitePragmaConfig,
21
21
  initializeDatabase
22
- } from "./index-hbt0sbv2.js";
22
+ } from "./index-fm36bjv4.js";
23
23
  import"./index-v0p37hm2.js";
24
24
  import"./index-cpjk5jd2.js";
25
25
  import"./index-rverk2vz.js";