@cortexkit/opencode-magic-context 0.49.100 → 0.49.102

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 (75) hide show
  1. package/dist/agents/dreamer.d.ts +3 -2
  2. package/dist/agents/dreamer.d.ts.map +1 -1
  3. package/dist/agents/permissions.d.ts +2 -0
  4. package/dist/agents/permissions.d.ts.map +1 -1
  5. package/dist/agents/smart-notes-dreamer-gate.fixture.d.ts +3 -1
  6. package/dist/agents/smart-notes-dreamer-gate.fixture.d.ts.map +1 -1
  7. package/dist/{context-k2tdh146.js → context-4fjwzqqa.js} +214 -30
  8. package/dist/features/magic-context/dreamer/curate-memory-safety.d.ts +1 -0
  9. package/dist/features/magic-context/dreamer/curate-memory-safety.d.ts.map +1 -1
  10. package/dist/features/magic-context/dreamer/task-executor.d.ts.map +1 -1
  11. package/dist/features/magic-context/dreamer/task-prompts.d.ts +7 -1
  12. package/dist/features/magic-context/dreamer/task-prompts.d.ts.map +1 -1
  13. package/dist/hooks/magic-context/host-served-rows.d.ts +7 -0
  14. package/dist/hooks/magic-context/host-served-rows.d.ts.map +1 -1
  15. package/dist/hooks/magic-context/transform.d.ts.map +1 -1
  16. package/dist/{index-0eyxarpb.js → index-2b7g81z7.js} +66 -21
  17. package/dist/{index-mfx7hzyc.js → index-4dywj733.js} +1 -1
  18. package/dist/{index-6hjbeeth.js → index-fbg61b3d.js} +2 -2
  19. package/dist/{index-qjcye18f.js → index-k4c0majv.js} +1 -1
  20. package/dist/{index-txthzqrm.js → index-k7yytqrd.js} +95 -53
  21. package/dist/{index-ajmy0v5j.js → index-ke0mkz7g.js} +13 -0
  22. package/dist/{index-n3tebmah.js → index-mx4j316q.js} +2 -2
  23. package/dist/{index-zyb7tndy.js → index-sgsaf60r.js} +4 -4
  24. package/dist/{index-0tqhr9zs.js → index-tbhbxb09.js} +3 -3
  25. package/dist/{index-z1hc2g06.js → index-y33x200y.js} +1 -1
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +30 -29
  28. package/dist/plugin/subagent-tool-policy.d.ts.map +1 -1
  29. package/dist/plugin/tool-registry.d.ts.map +1 -1
  30. package/dist/raw-ordinal-warmup-worker.js +2 -2
  31. package/dist/{recomp-orchestrator-e7n124g0.js → recomp-orchestrator-cvsfmctf.js} +4 -4
  32. package/dist/{render-argap54x.js → render-2a83mgrp.js} +2 -2
  33. package/dist/{search-archive-ads5mh9s.js → search-archive-f5dzec0e.js} +2 -2
  34. package/dist/{store-reader-01e8t5j0.js → store-reader-c5fwa9qx.js} +1 -1
  35. package/dist/{store-235fjtsn.js → store-wpx314rk.js} +2 -2
  36. package/dist/tools/ctx-memory/constants.d.ts +2 -0
  37. package/dist/tools/ctx-memory/constants.d.ts.map +1 -1
  38. package/dist/tools/ctx-memory/tools.d.ts +1 -0
  39. package/dist/tools/ctx-memory/tools.d.ts.map +1 -1
  40. package/dist/{transform-postprocess-phase-2y0st4gk.js → transform-postprocess-phase-fyw30790.js} +4 -4
  41. package/dist/v2/{context-v56v40cx.js → context-08pwkj6g.js} +289 -65
  42. package/dist/v2/fold/instruction-supersession.d.ts +18 -1
  43. package/dist/v2/fold/instruction-supersession.d.ts.map +1 -1
  44. package/dist/v2/hooks/context.d.ts +2 -1
  45. package/dist/v2/hooks/context.d.ts.map +1 -1
  46. package/dist/v2/hooks/hidden-child.d.ts.map +1 -1
  47. package/dist/v2/hooks/revert-message-state.d.ts +6 -0
  48. package/dist/v2/hooks/revert-message-state.d.ts.map +1 -1
  49. package/dist/v2/hooks/tools.d.ts.map +1 -1
  50. package/dist/v2/raw-ordinal-warmup-worker.js +2 -2
  51. package/dist/v2/{recomp-orchestrator-5gkzamy2.js → recomp-orchestrator-4mrvs5yc.js} +3 -3
  52. package/dist/v2/{render-atxj9eaf.js → render-r2djh67k.js} +2 -2
  53. package/dist/v2/{search-archive-vgwnvdx2.js → search-archive-4bq4ff8q.js} +2 -2
  54. package/dist/v2/{server-wdmcqhv6.js → server-b25kh28g.js} +1 -1
  55. package/dist/v2/{server-rwdp3hw6.js → server-f49pxtwf.js} +37 -4
  56. package/dist/v2/{server-e14d7ebh.js → server-mc5t7k8v.js} +1 -1
  57. package/dist/v2/{server-8vby30m5.js → server-nbdfv1wx.js} +1 -1
  58. package/dist/v2/{server-ysg14rv1.js → server-qg8jyfxa.js} +13 -0
  59. package/dist/v2/{server-08jh9wew.js → server-zzwje0mz.js} +4 -4
  60. package/dist/v2/server.js +2 -2
  61. package/dist/v2/{store-0kjfynwp.js → store-mba47sxn.js} +2 -2
  62. package/dist/v2/{store-reader-w0srb18d.js → store-reader-w7w8vfsy.js} +1 -1
  63. package/dist/v2/store-reader.d.ts +7 -0
  64. package/dist/v2/store-reader.d.ts.map +1 -1
  65. package/dist/v2/{v2-archive-reader-1wc5wb1a.js → v2-archive-reader-avcf7a5n.js} +1 -1
  66. package/dist/v2/{wrapup-orchestrator-ksdn2emb.js → wrapup-orchestrator-zwpjqymz.js} +3 -3
  67. package/dist/{v2-archive-reader-4pk46nc1.js → v2-archive-reader-cnhvhggz.js} +1 -1
  68. package/dist/{wrapup-orchestrator-sc2fsfct.js → wrapup-orchestrator-g1gnymt3.js} +5 -5
  69. package/package.json +1 -1
  70. package/src/agents/dreamer.ts +3 -2
  71. package/src/agents/hidden-agent-registrations.ts +2 -2
  72. package/src/agents/permissions.test.ts +89 -3
  73. package/src/agents/permissions.ts +32 -0
  74. package/src/agents/smart-notes-dreamer-gate.fixture.ts +27 -4
  75. package/src/agents/smart-notes-dreamer-gate.test.ts +5 -1
@@ -127,6 +127,13 @@ import {
127
127
  DREAMER_CLASSIFIER_AGENT,
128
128
  DREAMER_DOCS_AGENT,
129
129
  DREAMER_REVIEWER_AGENT,
130
+ CTX_MEMORY_TOOL_NAME,
131
+ CTX_MEMORY_LIST_TOOL_NAME,
132
+ CTX_MEMORY_CURATE_TOOL_NAME,
133
+ DREAMER_ONLY_MEMORY_TOOL_NAMES,
134
+ CTX_MEMORY_LIST_DESCRIPTION,
135
+ CTX_MEMORY_DESCRIPTION,
136
+ DEFAULT_SEARCH_LIMIT,
130
137
  keptUnderRetention,
131
138
  roleTitle,
132
139
  childCreateInput,
@@ -247,7 +254,7 @@ import {
247
254
  startCompartmentAgent,
248
255
  setRecompStarting2,
249
256
  setRecompTerminal2
250
- } from "./server-rwdp3hw6.js";
257
+ } from "./server-f49pxtwf.js";
251
258
  import {
252
259
  embedPauseBySession,
253
260
  embedRunStateBySession,
@@ -438,7 +445,7 @@ import {
438
445
  saveSourceContent,
439
446
  replaceSourceContent,
440
447
  getSourceContents
441
- } from "./server-8vby30m5.js";
448
+ } from "./server-nbdfv1wx.js";
442
449
  import {
443
450
  cleanSearchText,
444
451
  matchedSearchSnippet,
@@ -882,7 +889,7 @@ import {
882
889
  RAW_MESSAGE_TYPES2,
883
890
  V2StoreReaderPool2,
884
891
  V2StoreReader2
885
- } from "./server-ysg14rv1.js";
892
+ } from "./server-qg8jyfxa.js";
886
893
  import {
887
894
  configureContextDatabasePragmas2
888
895
  } from "./server-fb3zxn06.js";
@@ -1052,7 +1059,7 @@ import {
1052
1059
  readV2RawMessagePagesForConversion2,
1053
1060
  createV2RawMessageReader2,
1054
1061
  createV2RawMessageProvider2
1055
- } from "./server-e14d7ebh.js";
1062
+ } from "./server-mc5t7k8v.js";
1056
1063
  import {
1057
1064
  resolvePromptContext2
1058
1065
  } from "./server-fmsr7v69.js";
@@ -1064,11 +1071,11 @@ import {
1064
1071
  import"./server-s3m2y97h.js";
1065
1072
  import {
1066
1073
  readV2ArchiveOffThread2
1067
- } from "./server-08jh9wew.js";
1074
+ } from "./server-zzwje0mz.js";
1068
1075
  import {
1069
1076
  unresolvedLiveTailRefusal2,
1070
1077
  renderSearchArchiveOffThread2
1071
- } from "./server-wdmcqhv6.js";
1078
+ } from "./server-b25kh28g.js";
1072
1079
  import {
1073
1080
  markHostInstructionRow,
1074
1081
  hostInstructionRow,
@@ -23272,6 +23279,7 @@ ${notice}`, notificationParams));
23272
23279
  }
23273
23280
  }
23274
23281
  reclaim?.markRetired();
23282
+ reclaim?.settle?.();
23275
23283
  const signedThinkingServed = isPrefixBoundThinkingModel(modelForBudget?.providerID, modelForBudget?.modelID) && servesThinkingBlock(messages, modelForBudget?.providerID, modelForBudget?.modelID);
23276
23284
  finishSystemDateRefresh(deps.historyRefreshSessions, dateRequest, postTransformResult.bustedThisPass && !activeThinkingPrefixHold && !signedThinkingServed || postTransformResult.thinkingReleasedForFit === true, signedThinkingServed);
23277
23285
  if (activeThinkingPrefixHold && !postTransformResult.thinkingReleasedForFit && sessionMeta.cachedM0Bytes != null && sessionMeta.cachedM1Bytes != null) {
@@ -26911,7 +26919,7 @@ function registerRpcHandlers(rpcServer, args) {
26911
26919
  const db = readDatabase();
26912
26920
  if (!db)
26913
26921
  return { ok: false, error: "db unavailable" };
26914
- const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-5gkzamy2.js"));
26922
+ const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-4mrvs5yc.js"));
26915
26923
  const { sendIgnoredMessage } = await importPluginModule(() => import("./send-session-notification-vtnk598k.js"));
26916
26924
  log2(`[rpc] recomp requested for session ${sessionId}`);
26917
26925
  if (!args.client && !args.hiddenCompletionExecutor) {
@@ -26996,7 +27004,7 @@ function registerRpcHandlers(rpcServer, args) {
26996
27004
  const db = readDatabase();
26997
27005
  if (!db)
26998
27006
  return { ok: false, error: "db unavailable" };
26999
- const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-ksdn2emb.js"));
27007
+ const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-zwpjqymz.js"));
27000
27008
  const model = await args.readSelectedSessionModel?.(sessionId) ?? liveSessionState.liveModelBySession.get(sessionId);
27001
27009
  const window = resolveOpenCodeWrapupWindow(db, sessionId, model);
27002
27010
  if (!window)
@@ -27074,7 +27082,7 @@ function registerRpcHandlers(rpcServer, args) {
27074
27082
  }
27075
27083
 
27076
27084
  // src/plugin/subagent-tool-policy.ts
27077
- var PRIMARY_ONLY_TOOLS = new Set(["ctx_memory", "ctx_note"]);
27085
+ var PRIMARY_ONLY_TOOLS = new Set(["ctx_memory", "ctx_note", CTX_MEMORY_CURATE_TOOL_NAME]);
27078
27086
  function subagentToolRefusal(db, toolId, sessionId, isInternalChild = () => false) {
27079
27087
  if (PRIMARY_ONLY_TOOLS.has(toolId) && !isInternalChild(sessionId) && getOrCreateSessionMeta(db, sessionId).isSubagent) {
27080
27088
  return `Error: ${toolId} is unavailable in subagent sessions. Use the primary session instead.`;
@@ -28278,6 +28286,82 @@ var coveredOn = (value) => typeof value === "object" && value !== null && value.
28278
28286
  function retiredLiveInstructionIDs(db, sessionID) {
28279
28287
  return decode(readReplayEnvelope(db, sessionID)[namespace]);
28280
28288
  }
28289
+ var throughNamespace = "instructionSupersessionThrough";
28290
+ function decodeThrough(value, sessionID) {
28291
+ if (value === undefined)
28292
+ return { kind: "absent" };
28293
+ const { session, through } = value ?? {};
28294
+ if (typeof session !== "string" || session.length === 0 || typeof through !== "number" || !Number.isSafeInteger(through) || through < -1)
28295
+ throw new Error("Invalid instruction supersession replay state");
28296
+ return session === sessionID ? { kind: "own", through } : { kind: "foreign" };
28297
+ }
28298
+ var pendingLowerings = new WeakMap;
28299
+ function pendingLowering(db, sessionID) {
28300
+ return pendingLowerings.get(db)?.get(sessionID);
28301
+ }
28302
+ function setPendingLowering(db, sessionID, through) {
28303
+ let sessions = pendingLowerings.get(db);
28304
+ if (!sessions)
28305
+ pendingLowerings.set(db, sessions = new Map);
28306
+ sessions.set(sessionID, { through });
28307
+ }
28308
+ function clearPendingLowering(db, sessionID, pending) {
28309
+ const sessions = pendingLowerings.get(db);
28310
+ if (sessions?.get(sessionID) === pending)
28311
+ sessions.delete(sessionID);
28312
+ }
28313
+ function readThrough(db, sessionID) {
28314
+ const stored = decodeThrough(readReplayEnvelope(db, sessionID)[throughNamespace], sessionID);
28315
+ const pending = pendingLowering(db, sessionID);
28316
+ return stored.kind === "own" && pending && pending.through < stored.through ? { kind: "own", through: pending.through } : stored;
28317
+ }
28318
+ function isRetiredThrough(row, through) {
28319
+ return row.seq <= through && isMarkedInstructionUpdate(row);
28320
+ }
28321
+ var revertCounts = new WeakMap;
28322
+ function revertCount(db, sessionID) {
28323
+ return revertCounts.get(db)?.get(sessionID) ?? 0;
28324
+ }
28325
+ function lowerRetiredInstructionThrough(db, sessionID, before) {
28326
+ let sessions = revertCounts.get(db);
28327
+ if (!sessions)
28328
+ revertCounts.set(db, sessions = new Map);
28329
+ sessions.set(sessionID, revertCount(db, sessionID) + 1);
28330
+ return saveLowering(db, sessionID, before);
28331
+ }
28332
+ function saveLowering(db, sessionID, before) {
28333
+ const pending = pendingLowering(db, sessionID);
28334
+ const limit = Math.min(before ?? -1, pending?.through ?? Number.POSITIVE_INFINITY);
28335
+ let failure = "the replay document could not be written";
28336
+ let saved = false;
28337
+ try {
28338
+ saved = updateReplayDocument(db, sessionID, (doc) => {
28339
+ const current = decodeThrough(doc[throughNamespace], sessionID);
28340
+ if (current.kind !== "own" || current.through <= limit)
28341
+ return false;
28342
+ doc.version = 2;
28343
+ doc[throughNamespace] = { session: sessionID, through: limit };
28344
+ return true;
28345
+ });
28346
+ } catch (error) {
28347
+ failure = error;
28348
+ }
28349
+ if (saved) {
28350
+ if (pending)
28351
+ clearPendingLowering(db, sessionID, pending);
28352
+ return true;
28353
+ }
28354
+ if (pending?.through !== limit) {
28355
+ setPendingLowering(db, sessionID, limit);
28356
+ sessionLog2(sessionID, "committed revert: retired instruction rows kept lowered in memory until saved:", failure);
28357
+ }
28358
+ return false;
28359
+ }
28360
+ function retryRetiredInstructionLowering(db, sessionID) {
28361
+ const pending = pendingLowering(db, sessionID);
28362
+ if (pending)
28363
+ saveLowering(db, sessionID, pending.through);
28364
+ }
28281
28365
  function coveredInstructionSupersessionOn(db, sessionID) {
28282
28366
  return coveredOn(readReplayEnvelope(db, sessionID)[coveredNamespace]);
28283
28367
  }
@@ -28332,7 +28416,8 @@ function isMarkedInstructionUpdate(row) {
28332
28416
  const sources = metadata.instructionSources;
28333
28417
  return row.type === "system" && "notice" in metadata && metadata.notice === "instructions" && Array.isArray(sources) && sources.length > 0 && sources.every((source) => typeof source === "string" && source.length > 0);
28334
28418
  }
28335
- function reclaimInstructionRows(db, sessionID, messages, permitted, folded = new Set, covered = [], checkpointSequence, checkpointCoveredThrough) {
28419
+ function reclaimInstructionRows(db, sessionID, messages, permitted, folded = new Map, covered = [], checkpointSequence, checkpointCoveredThrough, localCheckpointSequence) {
28420
+ const builtAfterReverts = revertCount(db, sessionID);
28336
28421
  const instructionRows = (list) => list.flatMap((message) => {
28337
28422
  const row = hostInstructionRow(message.info);
28338
28423
  return row ? [{ message, row }] : [];
@@ -28340,7 +28425,19 @@ function reclaimInstructionRows(db, sessionID, messages, permitted, folded = new
28340
28425
  const coveredRows = coveredSupersessionEnabled ? instructionRows(covered) : [];
28341
28426
  const rows = [...coveredRows, ...instructionRows(messages)];
28342
28427
  const coveredMessages = new Set(coveredRows.map(({ message }) => message));
28343
- const retired = rows.length ? retiredLiveInstructionIDs(db, sessionID) : new Set;
28428
+ const retired = new Set(rows.length ? retiredLiveInstructionIDs(db, sessionID) : []);
28429
+ let stored = { kind: "foreign" };
28430
+ if (rows.length)
28431
+ stored = readThrough(db, sessionID);
28432
+ else if (checkpointSequence !== undefined) {
28433
+ try {
28434
+ stored = readThrough(db, sessionID);
28435
+ } catch {}
28436
+ }
28437
+ const through = stored.kind === "own" ? stored.through : -1;
28438
+ for (const { row } of rows)
28439
+ if (isRetiredThrough(row, through))
28440
+ retired.add(row.id);
28344
28441
  const coveredFollowed = rows.length > 0 && (coveredRows.length > 0 || permitted) && coveredInstructionSupersessionOn(db, sessionID);
28345
28442
  const switchCovered = permitted && rows.length > 0 && !coveredFollowed && coveredSupersessionEnabled;
28346
28443
  const selected = permitted ? supersededInstructionIDs(rows.map(({ row }) => row)) : new Set;
@@ -28353,6 +28450,13 @@ function reclaimInstructionRows(db, sessionID, messages, permitted, folded = new
28353
28450
  const newlyRetired = new Set([...selected].filter((id) => !retired.has(id)));
28354
28451
  const omitted = new Set([...retired, ...newlyRetired]);
28355
28452
  const omits = (message, id) => omitted.has(id) && (!coveredMessages.has(message) || coveredFollowed || switchCovered);
28453
+ let servedFrom = Number.POSITIVE_INFINITY;
28454
+ for (const { message, row } of rows) {
28455
+ if (isMarkedInstructionUpdate(row) && !omits(message, row.id))
28456
+ servedFrom = Math.min(servedFrom, row.seq);
28457
+ }
28458
+ const coverable = (seq) => Math.min(seq, servedFrom - 1);
28459
+ const initialThrough = stored.kind === "absent" && localCheckpointSequence !== undefined ? Math.max(-1, coverable(localCheckpointSequence - 1)) : undefined;
28356
28460
  const edits = [];
28357
28461
  for (const { message, row } of rows) {
28358
28462
  if (!omits(message, row.id))
@@ -28362,33 +28466,81 @@ function reclaimInstructionRows(db, sessionID, messages, permitted, folded = new
28362
28466
  edits.push(message);
28363
28467
  message.parts = [];
28364
28468
  }
28469
+ const decisions = newlyRetired.size > 0 || switchCovered;
28470
+ const pending = pendingLowering(db, sessionID);
28471
+ let wrote;
28365
28472
  return {
28366
28473
  edits,
28367
- hasDecisions: newlyRetired.size > 0 || switchCovered,
28474
+ hasDecisions: decisions,
28368
28475
  record(doc) {
28369
- if (newlyRetired.size === 0 && !switchCovered)
28476
+ if (!decisions)
28370
28477
  return false;
28371
28478
  const current = decode(doc[namespace]);
28372
28479
  if ([...newlyRetired].every((id) => current.has(id)) && (!switchCovered || coveredOn(doc[coveredNamespace])))
28373
28480
  return false;
28374
- for (const id of folded)
28375
- current.delete(id);
28481
+ const storedNow = decodeThrough(doc[throughNamespace], sessionID);
28482
+ let nextThrough = storedNow.kind === "own" ? Math.min(storedNow.through, pending?.through ?? Number.POSITIVE_INFINITY) : undefined;
28483
+ let dropped = -1;
28484
+ if (revertCount(db, sessionID) === builtAfterReverts) {
28485
+ for (const [id, seq] of folded) {
28486
+ if (current.delete(id) && Number.isFinite(seq))
28487
+ dropped = Math.max(dropped, seq);
28488
+ }
28489
+ }
28376
28490
  for (const id of newlyRetired)
28377
28491
  current.add(id);
28492
+ if (coverable(dropped) >= 0)
28493
+ nextThrough = Math.max(nextThrough ?? -1, coverable(dropped));
28378
28494
  doc.version = 2;
28379
28495
  doc[namespace] = [...current];
28380
28496
  if (switchCovered)
28381
28497
  doc[coveredNamespace] = { on: true };
28498
+ wrote = undefined;
28499
+ if (nextThrough !== undefined && (storedNow.kind !== "own" || nextThrough !== storedNow.through)) {
28500
+ doc[throughNamespace] = { session: sessionID, through: nextThrough };
28501
+ wrote = nextThrough;
28502
+ }
28382
28503
  return true;
28383
28504
  },
28384
28505
  markRetired() {
28506
+ if (pending && wrote !== undefined)
28507
+ clearPendingLowering(db, sessionID, pending);
28385
28508
  for (const { message, row } of rows) {
28386
28509
  if (omits(message, row.id))
28387
28510
  markRetiredInstructionRow(message.info);
28388
28511
  }
28512
+ },
28513
+ settle() {
28514
+ if (initialThrough === undefined || revertCount(db, sessionID) !== builtAfterReverts)
28515
+ return;
28516
+ const initial = initialThrough;
28517
+ let failure = "the replay document could not be written";
28518
+ try {
28519
+ const saved = updateReplayDocument(db, sessionID, (doc) => {
28520
+ const now = decodeThrough(doc[throughNamespace], sessionID);
28521
+ const raisable = now.kind === "absent" || now.kind === "own" && wrote !== undefined && now.through === wrote && wrote < initial;
28522
+ if (!raisable)
28523
+ return false;
28524
+ doc.version = 2;
28525
+ doc[throughNamespace] = { session: sessionID, through: initial };
28526
+ return true;
28527
+ });
28528
+ if (saved)
28529
+ return;
28530
+ } catch (error) {
28531
+ failure = error;
28532
+ }
28533
+ let logged = initialFailuresLogged.get(db);
28534
+ if (!logged)
28535
+ initialFailuresLogged.set(db, logged = new Set);
28536
+ if (logged.has(sessionID))
28537
+ return;
28538
+ logged.add(sessionID);
28539
+ sessionLog2(sessionID, "retired instruction rows: value from the checkpoint not saved; a later pass tries again:", failure);
28389
28540
  }
28390
28541
  };
28391
28542
  }
28543
+ var initialFailuresLogged = new WeakMap;
28392
28544
 
28393
28545
  // src/v2/fold/manual-baseline.ts
28394
28546
  var text = (value) => value == null ? null : typeof value === "string" ? value : Buffer.from(value).toString("utf8");
@@ -34163,14 +34315,16 @@ Project memory uses exactly 5 categories. Every memory belongs to one:
34163
34315
  - **NAMING** — naming conventions and canonical names. Not inventories.
34164
34316
 
34165
34317
  **Legacy categories during transition:** older memories may still carry pre-v2 category names. When you touch one, map it to its 5-category home with \`action="update"\` (or \`merge\`): WORKFLOW_RULES→PROJECT_RULES, ARCHITECTURE_DECISIONS→ARCHITECTURE, CONFIG_DEFAULTS→CONFIG_VALUES, ENVIRONMENT→CONFIG_VALUES (paths) or CONSTRAINTS, KNOWN_ISSUES→CONSTRAINTS only if it's an external-system limit. USER_DIRECTIVES / USER_PREFERENCES are NOT project categories. Do not compare project memories with the global user profile or use it to justify an archive.`;
34166
- var CURATE_SYSTEM_PROMPT = `You are a memory-pool curator for the magic-context system. You run during a scheduled dream window to keep a project's cross-session memory store lean and well-formed.
34318
+ function buildCurateSystemPrompt(memoryTool) {
34319
+ const example = (args) => memoryTool === CTX_MEMORY_TOOL_NAME ? args : `${memoryTool}(${args})`;
34320
+ return `You are a memory-pool curator for the magic-context system. You run during a scheduled dream window to keep a project's cross-session memory store lean and well-formed.
34167
34321
 
34168
34322
  ## Memory operations
34169
34323
  - The scoped category snapshot arrives in the first message. Do not list or get it again; track mutation deltas.
34170
- - \`action="merge", ids=[N,M,...], content="...", category="..."\` — consolidate duplicates into one canonical memory
34171
- - \`action="update", ids=[N], content="...", superseded_by=M\` — rewrite content; name where removed detail survives when cutting more than half
34172
- - \`action="write", category="...", content="..."\` — create a memory (SPLITS ONLY — never mint new facts)
34173
- - \`action="archive", ids=[N], superseded_by=M, reason="..."\` — consolidate a redundant memory into the named active same-category survivor
34324
+ - \`${example('action="merge", ids=[N,M,...], content="...", category="..."')}\` — consolidate duplicates into one canonical memory
34325
+ - \`${example('action="update", ids=[N], content="...", superseded_by=M')}\` — rewrite content; name where removed detail survives when cutting more than half
34326
+ - \`${example('action="write", category="...", content="..."')}\` — create a memory (SPLITS ONLY — never mint new facts)
34327
+ - \`${example('action="archive", ids=[N], superseded_by=M, reason="..."')}\` — consolidate a redundant memory into the named active same-category survivor
34174
34328
 
34175
34329
  ## Rules
34176
34330
  1. **Assume the pool is accurate.** A separate verify task checks memories against code. You handle QUALITY only — duplicates, wording, low-value entries — never correctness, and you do NOT read the codebase.
@@ -34181,6 +34335,8 @@ var CURATE_SYSTEM_PROMPT = `You are a memory-pool curator for the magic-context
34181
34335
  6. **Never mint new facts** — that is the historian's job. \`write\` is for splitting a compound memory only.
34182
34336
 
34183
34337
  ${PROJECT_MEMORY_TAXONOMY}`;
34338
+ }
34339
+ var CURATE_SYSTEM_PROMPT = buildCurateSystemPrompt(CTX_MEMORY_CURATE_TOOL_NAME);
34184
34340
  var MAINTAIN_DOCS_SYSTEM_PROMPT = `You are a read-only documentation investigator for the magic-context system. Use read, grep, glob and navigation tools to verify source. Never edit any file or run commands. Return only a proposed change to the project's ARCHITECTURE.md and STRUCTURE.md, not a change log. The protected regions between <!-- mc:protected START ... --> and <!-- mc:protected END --> must remain byte-identical. If the docs are accurate, return [].`;
34185
34341
  var REVIEW_USER_MEMORIES_SYSTEM_PROMPT = `You are a user-profile reviewer for the magic-context system. You run during a scheduled dream window to decide which recurring behavioral observations about the human user are real, persistent patterns worth keeping in their global user profile.
34186
34342
 
@@ -34215,7 +34371,7 @@ The memories below are assumed ACCURATE (a separate verify task keeps them true)
34215
34371
  Work ALL THREE phases below in order (A → B → C) over this category. Do NOT stop after consolidating — a run that only merges and never improves or archives is incomplete.
34216
34372
 
34217
34373
  ### Phase A — Consolidate duplicates
34218
- Group by category, then merge near-identical / superset-subset / same-fact-different-angle clusters into one canonical memory with \`ctx_memory(action="merge", ids=[...], content="...", category="...")\`. Preserve every unique detail; terse present tense; paths/keys verbatim. Every id in a merge MUST share the same category — the system rejects cross-category merges. If two similar memories sit in different categories they are NOT duplicates; do not archive either as a consolidation. One fact per memory.
34374
+ Group by category, then merge near-identical / superset-subset / same-fact-different-angle clusters into one canonical memory with \`${args.memoryTool ?? CTX_MEMORY_CURATE_TOOL_NAME}(action="merge", ids=[...], content="...", category="...")\`. Preserve every unique detail; terse present tense; paths/keys verbatim. Every id in a merge MUST share the same category — the system rejects cross-category merges. If two similar memories sit in different categories they are NOT duplicates; do not archive either as a consolidation. One fact per memory.
34219
34375
 
34220
34376
  ### Phase B — Improve wording
34221
34377
  Rewrite narrative/historical → operational present tense ("X uses Y because Z", not "we switched to Y"); drop session-local context and commit hashes (unless the hash is the point); add specifics where vague. A rewrite that removes more than half the content must name the active same-category memory preserving that detail with \`superseded_by\`. \`write\` is for SPLITS ONLY (update the original down to its first fact, write the second) — a healthy run is net-neutral or net-shrinking, never net-adds facts.
@@ -34344,7 +34500,8 @@ function buildDreamTaskPrompt(task, args) {
34344
34500
  projectPath: args.projectPath,
34345
34501
  category: args.curate?.category ?? "PROJECT_RULES",
34346
34502
  memories: args.curate?.memories ?? [],
34347
- crossChunkCandidates: args.curate?.crossChunkCandidates
34503
+ crossChunkCandidates: args.curate?.crossChunkCandidates,
34504
+ memoryTool: args.curate?.memoryTool
34348
34505
  });
34349
34506
  case "maintain-docs":
34350
34507
  return buildMaintainDocsPrompt(args.projectPath, args.docsChangeSet ?? "", args.existingDocs ?? { architecture: false, structure: false }, args.docsBudget, args.docsCurrentTokens, args.docsContents);
@@ -35279,7 +35436,8 @@ var refusalReasons = new Set(CURATE_SAFETY_REFUSAL_REASONS);
35279
35436
  function parseCurateSafetyRefusal(action, output) {
35280
35437
  if (action !== "archive" && action !== "update")
35281
35438
  return null;
35282
- const refusal = /^Skipped (archive|update) for memory \[ID: -?\d+(?:, -?\d+)*\]: curate safety refusal \(([a-z,-]+)\); refused=[1-9]\d*\.$/.exec(output);
35439
+ const refusal = /^Skipped (archive|update) for memory \[ID: -?\d+(?:, -?\d+)*\]: curate safety refusal \(([a-z,-]+)\); refused=[1-9]\d*\.$/.exec(output.split(`
35440
+ `, 1)[0] ?? "");
35283
35441
  if (refusal?.[1] !== action || !refusal[2])
35284
35442
  return null;
35285
35443
  const reasons = [...new Set(refusal[2].split(","))];
@@ -35330,14 +35488,20 @@ function assessCurateMutationSafety(args) {
35330
35488
  return null;
35331
35489
  }
35332
35490
  function recordCurateSafetyRefusal(sessionId, refusal) {
35333
- const count = (refusalCountsBySession.get(sessionId) ?? 0) + 1;
35334
- refusalCountsBySession.set(sessionId, count);
35491
+ const counts = refusalCountsBySession.get(sessionId) ?? { total: 0, byMemory: new Map };
35492
+ const forMemory = (counts.byMemory.get(refusal.memoryId) ?? 0) + 1;
35493
+ counts.byMemory.set(refusal.memoryId, forMemory);
35494
+ const count = ++counts.total;
35495
+ refusalCountsBySession.set(sessionId, counts);
35335
35496
  const lengths = refusal.originalChars === undefined ? "" : ` original_chars=${refusal.originalChars} replacement_chars=${refusal.replacementChars ?? 0}`;
35336
35497
  log2(`[dreamer] curate safety refusal: session_id=${sessionId} memory_id=${refusal.memoryId} verdict=${refusal.verdict} reason=${refusal.reason}${lengths} refused=${count}`);
35337
35498
  return count;
35338
35499
  }
35500
+ function curateSafetyRefusalsForMemory(sessionId, memoryId) {
35501
+ return refusalCountsBySession.get(sessionId)?.byMemory.get(memoryId) ?? 0;
35502
+ }
35339
35503
  function takeCurateSafetyRefusalCount(sessionId) {
35340
- const count = refusalCountsBySession.get(sessionId) ?? 0;
35504
+ const count = refusalCountsBySession.get(sessionId)?.total ?? 0;
35341
35505
  refusalCountsBySession.delete(sessionId);
35342
35506
  return count;
35343
35507
  }
@@ -40321,7 +40485,7 @@ function inspectCurateMemoryOperations(messages) {
40321
40485
  if (!isRecord(part) || part.type !== "tool")
40322
40486
  continue;
40323
40487
  const toolName = part.tool ?? part.name;
40324
- if (toolName !== "ctx_memory")
40488
+ if (toolName !== CTX_MEMORY_TOOL_NAME && toolName !== CTX_MEMORY_CURATE_TOOL_NAME)
40325
40489
  continue;
40326
40490
  const state = isRecord(part.state) ? part.state : null;
40327
40491
  const input = isRecord(state?.input) ? state.input : null;
@@ -41493,6 +41657,9 @@ async function runAgenticTask(config, ctx, helpers) {
41493
41657
  const curateChunks = curateMemories ? chunkCurateMemories(curateMemories, Math.max(4000, Math.floor(resolveRetrospectiveUsableInputTokens(config, deps) * 2))) : [];
41494
41658
  const batches = task === "curate" ? curateChunks : [{ memories: [], crossChunkCandidates: [] }];
41495
41659
  const curateOperations = emptyCurateMemoryOperations();
41660
+ const harness = getHarness2();
41661
+ const curateMemoryTool = harness === "pi" || harness === "omp" ? CTX_MEMORY_TOOL_NAME : CTX_MEMORY_CURATE_TOOL_NAME;
41662
+ const taskSystemPrompt = task === "maintain-docs" ? MAINTAIN_DOCS_SYSTEM_PROMPT : buildCurateSystemPrompt(curateMemoryTool);
41496
41663
  let curateRefused = 0;
41497
41664
  let run = {
41498
41665
  output: [],
@@ -41513,7 +41680,8 @@ async function runAgenticTask(config, ctx, helpers) {
41513
41680
  curate: curateMemories && curateCategory ? {
41514
41681
  category: curateCategory,
41515
41682
  memories: batch.memories,
41516
- crossChunkCandidates: batch.crossChunkCandidates
41683
+ crossChunkCandidates: batch.crossChunkCandidates,
41684
+ memoryTool: curateMemoryTool
41517
41685
  } : undefined
41518
41686
  });
41519
41687
  if (deps.hiddenCompletionExecutor) {
@@ -41522,7 +41690,7 @@ async function runAgenticTask(config, ctx, helpers) {
41522
41690
  parentSessionId: parent ?? undefined,
41523
41691
  sessionDirectory: docsDir,
41524
41692
  agent: task === "maintain-docs" ? DREAMER_DOCS_AGENT : DREAMER_AGENT,
41525
- system: task === "maintain-docs" ? MAINTAIN_DOCS_SYSTEM_PROMPT : CURATE_SYSTEM_PROMPT,
41693
+ system: taskSystemPrompt,
41526
41694
  prompt: taskPrompt,
41527
41695
  title: `magic-context-dream-${task}`,
41528
41696
  callContext: `dreamer:${task}`,
@@ -41569,7 +41737,7 @@ async function runAgenticTask(config, ctx, helpers) {
41569
41737
  query: { directory: docsDir },
41570
41738
  body: {
41571
41739
  agent: task === "maintain-docs" ? DREAMER_DOCS_AGENT : DREAMER_AGENT,
41572
- system: task === "maintain-docs" ? MAINTAIN_DOCS_SYSTEM_PROMPT : withContentLanguageDirective(CURATE_SYSTEM_PROMPT, config.language ?? deps.language),
41740
+ system: task === "maintain-docs" ? taskSystemPrompt : withContentLanguageDirective(taskSystemPrompt, config.language ?? deps.language),
41573
41741
  ...modelBodyField(config.model),
41574
41742
  parts: [{ type: "text", text: taskPrompt, synthetic: true }]
41575
41743
  }
@@ -43767,8 +43935,10 @@ class V2RevertMessageCleanup {
43767
43935
  const reader = this.openStoreReader();
43768
43936
  try {
43769
43937
  const suffix = reader.revertSuffix(sessionID, cutoff, MAX_STAGED_SUFFIX_ROWS);
43770
- this.staged.set(sessionID, suffix ? { cutoff, host: reader.hostIdentity(), suffix } : {
43938
+ const before = suffix ? suffix.predecessor.seq : reader.sequenceBefore(sessionID, cutoff);
43939
+ this.staged.set(sessionID, suffix ? { cutoff, host: reader.hostIdentity(), suffix, before } : {
43771
43940
  cutoff,
43941
+ before,
43772
43942
  unavailable: "stage did not prove a bounded suffix and retained predecessor"
43773
43943
  });
43774
43944
  } finally {
@@ -43778,6 +43948,10 @@ class V2RevertMessageCleanup {
43778
43948
  this.staged.set(sessionID, { cutoff, unavailable: "host store read failed at stage" });
43779
43949
  }
43780
43950
  }
43951
+ stagedPredecessor(sessionID, to) {
43952
+ const staged = this.staged.peek(sessionID);
43953
+ return staged && staged.cutoff === to ? staged.before : undefined;
43954
+ }
43781
43955
  discardStageProof(sessionID) {
43782
43956
  this.staged.delete(sessionID);
43783
43957
  }
@@ -56436,23 +56610,6 @@ function createCtxExpandTools(deps) {
56436
56610
  ctx_expand: createCtxExpandTool(deps)
56437
56611
  };
56438
56612
  }
56439
- // src/tools/ctx-memory/constants.ts
56440
- var CTX_MEMORY_TOOL_NAME = "ctx_memory";
56441
- var CTX_MEMORY_LIST_TOOL_NAME = "ctx_memory_list";
56442
- var CTX_MEMORY_LIST_DESCRIPTION = "Browse active memories, optionally filter by category.";
56443
- var CTX_MEMORY_DESCRIPTION = `Durable facts about this project, shared with every agent working on it and kept for the months this work lasts.
56444
-
56445
- Your active memories are already in <project-memory> as \`#id: fact\` lines. Write one when you learn something that must not have to be found again — a project rule, an architectural fact, a hard-won constraint, a config value, a naming convention — and especially when it cost you turns to find. One standalone fact per memory, phrased to make sense on its own. A pending intention with its evidence ("do X later, here is what we know") is ctx_note, not memory.
56446
-
56447
- Actions:
56448
- - write: new memory (content + category).
56449
- - update: rewrite one memory whose fact changed (ids: [one], content; category: the current one to keep, a new one to recategorize).
56450
- - archive: retire wrong or obsolete memories (ids: [one or more], optional reason).
56451
- - merge: collapse duplicates into one (ids: [two or more distinct ids of memories in the same category], content).
56452
- - get: fetch by id (ids: 1–20), readable in every status.
56453
- The call form that works on every host sends action, content, category and ids every time: argument-dropping providers only emit required fields. For get and archive pass content="" and any valid category; for write pass ids=[].
56454
- Examples: category="CONFIG_VALUES", content="OpenCode source is at ~/Work/OSS/opencode" · category="CONSTRAINTS", content="Dashboard Tauri build needs RGBA PNGs, not grayscale"`;
56455
- var DEFAULT_SEARCH_LIMIT = 10;
56456
56613
  // src/features/magic-context/memory/memory-visibility.ts
56457
56614
  function createMemoryVisibilityPolicy(db, projectIdentity) {
56458
56615
  const identitySet = resolveWorkspaceIdentitySet(db, projectIdentity);
@@ -56666,13 +56823,28 @@ function preflightCurateMutation(args) {
56666
56823
  if (refusals.length === 0)
56667
56824
  return { skip: null, successor };
56668
56825
  let refused = 0;
56826
+ let steer = false;
56827
+ const leaveAlone = [];
56669
56828
  for (const refusal of refusals) {
56670
56829
  refused = recordCurateSafetyRefusal(args.sessionId, refusal);
56830
+ if (curateSafetyRefusalsForMemory(args.sessionId, refusal.memoryId) >= 3) {
56831
+ leaveAlone.push(refusal.memoryId);
56832
+ } else if (args.toolName === CTX_MEMORY_TOOL_NAME && params.superseded_by === undefined && (refusal.reason === "missing-active-same-category-successor" || refusal.reason === "content-loss")) {
56833
+ steer = true;
56834
+ }
56671
56835
  }
56672
56836
  const memoryIds = refusals.map((refusal) => refusal.memoryId).join(", ");
56673
56837
  const reasons = [...new Set(refusals.map((refusal) => refusal.reason))].join(",");
56838
+ const guidance = [
56839
+ ...steer ? [`Use ${CTX_MEMORY_CURATE_TOOL_NAME} to name the survivor with superseded_by.`] : [],
56840
+ ...leaveAlone.map((id) => `Memory [ID: ${id}] is left as it is for this run. Do not try it again.`)
56841
+ ];
56674
56842
  return {
56675
- skip: `Skipped ${params.action} for memory [ID: ${memoryIds}]: curate safety refusal (${reasons}); refused=${refused}.`,
56843
+ skip: [
56844
+ `Skipped ${params.action} for memory [ID: ${memoryIds}]: curate safety refusal (${reasons}); refused=${refused}.`,
56845
+ ...guidance
56846
+ ].join(`
56847
+ `),
56676
56848
  successor
56677
56849
  };
56678
56850
  }
@@ -56716,12 +56888,16 @@ var ctxMemoryListArgsShape = {
56716
56888
  category: tool.schema.enum([...V2_MEMORY_CATEGORIES]).optional().describe("Filter listed memories to this category (optional)."),
56717
56889
  limit: tool.schema.number().optional().describe("Max results for list (default 10).")
56718
56890
  };
56891
+ var ctxMemoryCurateArgsShape = {
56892
+ ...ctxMemoryArgsShape,
56893
+ superseded_by: tool.schema.number().optional().describe("ID of the active memory in the same project and category that keeps the information.")
56894
+ };
56719
56895
  var ctxMemoryArgsSchema = tool.schema.object({
56720
56896
  ...ctxMemoryArgsShape,
56721
- superseded_by: tool.schema.number().optional(),
56897
+ superseded_by: ctxMemoryCurateArgsShape.superseded_by,
56722
56898
  limit: tool.schema.number().optional()
56723
56899
  }).passthrough();
56724
- function createCtxMemoryTool(deps) {
56900
+ function createCtxMemoryTool(deps, toolName = CTX_MEMORY_TOOL_NAME) {
56725
56901
  const allowedActions = getAllowedActions(deps);
56726
56902
  return tool({
56727
56903
  description: CTX_MEMORY_DESCRIPTION,
@@ -56770,7 +56946,8 @@ function createCtxMemoryTool(deps) {
56770
56946
  const curatePreflight = toolContext.agent === DREAMER_AGENT ? preflightCurateMutation({
56771
56947
  db: deps.db,
56772
56948
  params: args,
56773
- sessionId: toolContext.sessionID
56949
+ sessionId: toolContext.sessionID,
56950
+ toolName
56774
56951
  }) : { skip: null, successor: null };
56775
56952
  if (curatePreflight.skip)
56776
56953
  return curatePreflight.skip;
@@ -57098,6 +57275,22 @@ function createCtxMemoryListTools(deps) {
57098
57275
  [CTX_MEMORY_LIST_TOOL_NAME]: createCtxMemoryListTool(deps)
57099
57276
  };
57100
57277
  }
57278
+ function createDreamerMemoryTools(deps) {
57279
+ const memoryTool = createCtxMemoryTool(deps, CTX_MEMORY_CURATE_TOOL_NAME);
57280
+ return {
57281
+ ...createCtxMemoryListTools(deps),
57282
+ [CTX_MEMORY_CURATE_TOOL_NAME]: tool({
57283
+ description: "Maintain the project memory pool during Curate.",
57284
+ args: ctxMemoryCurateArgsShape,
57285
+ async execute(args, toolContext) {
57286
+ if (toolContext.agent !== DREAMER_AGENT) {
57287
+ return `Error: ${CTX_MEMORY_CURATE_TOOL_NAME} is only available to the dreamer agent.`;
57288
+ }
57289
+ return memoryTool.execute(args, toolContext);
57290
+ }
57291
+ })
57292
+ };
57293
+ }
57101
57294
  // src/features/magic-context/smart-notes/condition-compiler.ts
57102
57295
  import { existsSync as existsSync9 } from "node:fs";
57103
57296
  import { isAbsolute as isAbsolute2 } from "node:path";
@@ -58296,7 +58489,7 @@ async function registerTools(context, db, config, rustToolBackends, isInternalCh
58296
58489
  ...project,
58297
58490
  ...rustToolBackends ? { rustToolBackends } : {}
58298
58491
  }),
58299
- ...createCtxMemoryListTools({
58492
+ ...createDreamerMemoryTools({
58300
58493
  ...project,
58301
58494
  ...rustToolBackends ? { rustToolBackends } : {}
58302
58495
  })
@@ -58314,7 +58507,7 @@ async function registerTools(context, db, config, rustToolBackends, isInternalCh
58314
58507
  const refusal = subagentToolRefusal(db, name, call.sessionID, isInternalChild);
58315
58508
  if (refusal)
58316
58509
  return { content: refusal };
58317
- if (name === "ctx_memory" || name === "ctx_note" || name === "ctx_reduce")
58510
+ if (name === "ctx_memory" || name === "ctx_note" || name === "ctx_reduce" || name === CTX_MEMORY_CURATE_TOOL_NAME && call.agent === DREAMER_AGENT)
58318
58511
  await withAsyncPrivilegedWriter2(db, () => {
58319
58512
  return;
58320
58513
  });
@@ -59002,9 +59195,11 @@ function catalogModels(listed, draftModel) {
59002
59195
  }
59003
59196
  return models;
59004
59197
  }
59005
- function removeDreamerOnlyTools(draft) {
59006
- if (draft.tools)
59007
- delete draft.tools.ctx_memory_list;
59198
+ function removeDreamerOnlyTools(draft, ids = DREAMER_ONLY_MEMORY_TOOL_NAMES) {
59199
+ if (!draft.tools)
59200
+ return;
59201
+ for (const id of ids)
59202
+ delete draft.tools[id];
59008
59203
  }
59009
59204
  function applyV2PromptSurfaceTools(draft, runtime, config, smartNotesEnabled = true) {
59010
59205
  if (!draft.tools)
@@ -59848,6 +60043,27 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
59848
60043
  }
59849
60044
  };
59850
60045
  const usageController = new AbortController;
60046
+ const lowerRetiredInstructionsOnRevert = (database, sessionID, event) => {
60047
+ try {
60048
+ let before = revertMessageCleanup.stagedPredecessor(sessionID, event.data?.to);
60049
+ const commitSeq = event.durable?.seq;
60050
+ if (before === undefined && event.durable?.aggregateID === sessionID && typeof commitSeq === "number" && Number.isSafeInteger(commitSeq)) {
60051
+ const reader = openStoreReader();
60052
+ try {
60053
+ before = reader.highestSequenceBelow(sessionID, commitSeq);
60054
+ } finally {
60055
+ reader.close();
60056
+ }
60057
+ }
60058
+ if (before === undefined) {
60059
+ sessionLog2(sessionID, "committed revert: last kept row unknown; retired instruction rows left as they are");
60060
+ return;
60061
+ }
60062
+ lowerRetiredInstructionThrough(database, sessionID, before);
60063
+ } catch (error) {
60064
+ sessionLog2(sessionID, "committed revert: retired instruction rows not updated:", error);
60065
+ }
60066
+ };
59851
60067
  cleanup.abortUsage = () => {
59852
60068
  usageController.abort();
59853
60069
  httpRefusalCounts.dispose();
@@ -59910,6 +60126,7 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
59910
60126
  const indexDb = db;
59911
60127
  withoutSqliteTransformPass2(() => {
59912
60128
  scheduleClearAndReindex(indexDb, sessionID, pagedRead);
60129
+ lowerRetiredInstructionsOnRevert(indexDb, sessionID, event);
59913
60130
  try {
59914
60131
  if (revertMessageCleanup.pruneOnCommit(indexDb, sessionID, event.data?.to, !compactionOff && !rustModeModuleClient)) {
59915
60132
  tagger.cleanup(sessionID);
@@ -60085,8 +60302,10 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
60085
60302
  draft.result = { summary: hiddenSummary, metadata: { keepID: undefined } };
60086
60303
  return;
60087
60304
  }
60088
- if (compactionOff)
60305
+ if (compactionOff) {
60306
+ removeDreamerOnlyTools(draft, [CTX_MEMORY_CURATE_TOOL_NAME]);
60089
60307
  return;
60308
+ }
60090
60309
  if (nativeFoldReplay)
60091
60310
  rememberHostMedia(draft.messages);
60092
60311
  const reader = openStoreReader();
@@ -60178,11 +60397,13 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
60178
60397
  if (!recorded)
60179
60398
  return messages;
60180
60399
  if (db) {
60181
- foldedInstructionIDs.set(sessionID, new Set([...retiredLiveInstructionIDs(db, sessionID)].filter((id) => recorded({
60182
- type: "system",
60183
- id,
60184
- seq: reader.sequenceForId(sessionID, id) ?? Infinity
60185
- }))));
60400
+ const folded = new Map;
60401
+ for (const id of retiredLiveInstructionIDs(db, sessionID)) {
60402
+ const seq = reader.sequenceForId(sessionID, id) ?? Infinity;
60403
+ if (recorded({ type: "system", id, seq }))
60404
+ folded.set(id, seq);
60405
+ }
60406
+ foldedInstructionIDs.set(sessionID, folded);
60186
60407
  }
60187
60408
  const retired = (row) => recorded(row) || isLeftOutInstruction(leftOut, row);
60188
60409
  return messages.filter((message) => {
@@ -60286,7 +60507,7 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
60286
60507
  const pass = contextPass.getStore();
60287
60508
  if (pass)
60288
60509
  pass.legacyCoveredReclaimPermitted = permitted;
60289
- return reclaimInstructionRows(database, sessionID, messages, permitted, foldedInstructionIDs.get(sessionID), covered, pass?.checkpointSequence, pass?.checkpointCoveredThrough);
60510
+ return reclaimInstructionRows(database, sessionID, messages, permitted, foldedInstructionIDs.get(sessionID), covered, pass?.checkpointSequence, pass?.checkpointCoveredThrough, pass?.localCheckpointSequence);
60290
60511
  },
60291
60512
  compactionOff,
60292
60513
  storeGeneration: "v2",
@@ -60678,6 +60899,7 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
60678
60899
  let messageTimes;
60679
60900
  let instructionRows = new Map;
60680
60901
  let legacyInstructions;
60902
+ retryRetiredInstructionLowering(db, draft.sessionID);
60681
60903
  const reader = openStoreReader();
60682
60904
  let checkpoint;
60683
60905
  let submitted;
@@ -60688,8 +60910,10 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
60688
60910
  try {
60689
60911
  syntheticIDs = await readSyntheticProvenance(reader, draft.messages);
60690
60912
  const cut = reader.latestCompaction(draft.sessionID);
60691
- if (!rustModeModuleClient)
60913
+ if (!rustModeModuleClient) {
60692
60914
  pass.checkpointSequence = cut?.seq;
60915
+ pass.localCheckpointSequence = cut && isLocalCheckpoint(cut) ? cut.seq : undefined;
60916
+ }
60693
60917
  if (nativeFoldReplay)
60694
60918
  draftSourceIdentity = await nativeFoldReplay.observeSource(draft.sessionID, reader);
60695
60919
  const boundaryRepair = !rustModeModuleClient && db && !compactionOff ? revertMessageCleanup.retireProvenHistory(db, draft.sessionID, reader) ?? checkHistoryBoundary(db, reader, draft.sessionID) : undefined;