@cortexkit/opencode-magic-context 0.49.99 → 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 (130) 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/auto-search-worker.js +1 -1
  8. package/dist/chunk-embedding-write-worker.js +1 -1
  9. package/dist/{context-z77a2jpx.js → context-4fjwzqqa.js} +497 -52
  10. package/dist/features/magic-context/dreamer/curate-memory-safety.d.ts +1 -0
  11. package/dist/features/magic-context/dreamer/curate-memory-safety.d.ts.map +1 -1
  12. package/dist/features/magic-context/dreamer/task-executor.d.ts.map +1 -1
  13. package/dist/features/magic-context/dreamer/task-prompts.d.ts +7 -1
  14. package/dist/features/magic-context/dreamer/task-prompts.d.ts.map +1 -1
  15. package/dist/features/magic-context/overflow-detection.d.ts +7 -0
  16. package/dist/features/magic-context/overflow-detection.d.ts.map +1 -1
  17. package/dist/hooks/magic-context/emergency-drop.d.ts +8 -1
  18. package/dist/hooks/magic-context/emergency-drop.d.ts.map +1 -1
  19. package/dist/hooks/magic-context/final-wire-token-estimate.d.ts +4 -0
  20. package/dist/hooks/magic-context/final-wire-token-estimate.d.ts.map +1 -1
  21. package/dist/hooks/magic-context/heuristic-cleanup.d.ts +1 -0
  22. package/dist/hooks/magic-context/heuristic-cleanup.d.ts.map +1 -1
  23. package/dist/hooks/magic-context/host-served-rows.d.ts +7 -0
  24. package/dist/hooks/magic-context/host-served-rows.d.ts.map +1 -1
  25. package/dist/hooks/magic-context/image-token-estimate.d.ts +1 -0
  26. package/dist/hooks/magic-context/image-token-estimate.d.ts.map +1 -1
  27. package/dist/hooks/magic-context/provider-refusal-count.d.ts +84 -0
  28. package/dist/hooks/magic-context/provider-refusal-count.d.ts.map +1 -0
  29. package/dist/hooks/magic-context/signed-thinking-hold.d.ts +2 -0
  30. package/dist/hooks/magic-context/signed-thinking-hold.d.ts.map +1 -1
  31. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts +1 -0
  32. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts.map +1 -1
  33. package/dist/hooks/magic-context/transform.d.ts.map +1 -1
  34. package/dist/{index-9q7wzca8.js → index-2b7g81z7.js} +70 -25
  35. package/dist/{index-xw608ytx.js → index-3cgh0ght.js} +1 -1
  36. package/dist/{index-mfx7hzyc.js → index-4dywj733.js} +1 -1
  37. package/dist/{index-dnxnj42p.js → index-634cww4x.js} +4 -4
  38. package/dist/{index-h1xvt8fw.js → index-63kp05sy.js} +1 -1
  39. package/dist/{index-5xrj3zp4.js → index-fbg61b3d.js} +3 -3
  40. package/dist/{index-tyjx0dwz.js → index-jjy4shhy.js} +1 -1
  41. package/dist/{index-0wj3jr8n.js → index-k4c0majv.js} +3 -3
  42. package/dist/{index-5nf2a14a.js → index-k7yytqrd.js} +364 -76
  43. package/dist/{index-ajmy0v5j.js → index-ke0mkz7g.js} +13 -0
  44. package/dist/{index-8hhmv0ff.js → index-kjhgxkdx.js} +1 -1
  45. package/dist/{index-4qc8d9by.js → index-mx4j316q.js} +21 -14
  46. package/dist/{index-9eqt7755.js → index-rakm1eay.js} +2 -2
  47. package/dist/{index-w6kcwhhj.js → index-rjxg7a7m.js} +212 -4
  48. package/dist/{index-xbna9akt.js → index-sgsaf60r.js} +5 -5
  49. package/dist/{index-507a56zb.js → index-tbhbxb09.js} +5 -5
  50. package/dist/{index-em72jhc0.js → index-y33x200y.js} +2 -2
  51. package/dist/{index-kjdys7e2.js → index-zg5r2syy.js} +1 -1
  52. package/dist/index.d.ts.map +1 -1
  53. package/dist/index.js +154 -41
  54. package/dist/{message-index-bounded-6y7p974x.js → message-index-bounded-289186ah.js} +3 -3
  55. package/dist/migration-worker.js +1 -1
  56. package/dist/plugin/messages-transform.d.ts +1 -0
  57. package/dist/plugin/messages-transform.d.ts.map +1 -1
  58. package/dist/plugin/provider-refusal-v1.d.ts +15 -0
  59. package/dist/plugin/provider-refusal-v1.d.ts.map +1 -0
  60. package/dist/plugin/subagent-tool-policy.d.ts.map +1 -1
  61. package/dist/plugin/tool-registry.d.ts.map +1 -1
  62. package/dist/raw-ordinal-warmup-worker.js +4 -4
  63. package/dist/{read-session-chunk-9ejnbe07.js → read-session-chunk-frnwxnjg.js} +2 -2
  64. package/dist/{recomp-orchestrator-9k91tkyx.js → recomp-orchestrator-cvsfmctf.js} +8 -8
  65. package/dist/{render-9712q3gp.js → render-2a83mgrp.js} +7 -7
  66. package/dist/{search-archive-5jr011gc.js → search-archive-f5dzec0e.js} +5 -5
  67. package/dist/{search-yhaxy3e6.js → search-fxtb4844.js} +6 -6
  68. package/dist/{storage-tags-vd3sgd4s.js → storage-tags-2d2ba8e9.js} +1 -1
  69. package/dist/{store-reader-01e8t5j0.js → store-reader-c5fwa9qx.js} +1 -1
  70. package/dist/{store-235fjtsn.js → store-wpx314rk.js} +2 -2
  71. package/dist/tools/ctx-memory/constants.d.ts +2 -0
  72. package/dist/tools/ctx-memory/constants.d.ts.map +1 -1
  73. package/dist/tools/ctx-memory/tools.d.ts +1 -0
  74. package/dist/tools/ctx-memory/tools.d.ts.map +1 -1
  75. package/dist/{transform-postprocess-phase-mf5js6cs.js → transform-postprocess-phase-fyw30790.js} +9 -9
  76. package/dist/v2/auto-search-worker.js +1 -1
  77. package/dist/v2/chunk-embedding-write-worker.js +1 -1
  78. package/dist/v2/{context-4fej2dzv.js → context-08pwkj6g.js} +872 -139
  79. package/dist/v2/fold/instruction-supersession.d.ts +18 -1
  80. package/dist/v2/fold/instruction-supersession.d.ts.map +1 -1
  81. package/dist/v2/hooks/context.d.ts +2 -1
  82. package/dist/v2/hooks/context.d.ts.map +1 -1
  83. package/dist/v2/hooks/hidden-child.d.ts.map +1 -1
  84. package/dist/v2/hooks/http-refusal-count.d.ts +41 -0
  85. package/dist/v2/hooks/http-refusal-count.d.ts.map +1 -0
  86. package/dist/v2/hooks/overflow-recovery.d.ts +3 -0
  87. package/dist/v2/hooks/overflow-recovery.d.ts.map +1 -1
  88. package/dist/v2/hooks/revert-message-state.d.ts +6 -0
  89. package/dist/v2/hooks/revert-message-state.d.ts.map +1 -1
  90. package/dist/v2/hooks/tools.d.ts.map +1 -1
  91. package/dist/v2/hooks/types.d.ts +5 -0
  92. package/dist/v2/hooks/types.d.ts.map +1 -1
  93. package/dist/v2/{message-index-bounded-wj5rs9az.js → message-index-bounded-p69v4wpy.js} +3 -3
  94. package/dist/v2/migration-worker.js +1 -1
  95. package/dist/v2/raw-ordinal-warmup-worker.js +4 -4
  96. package/dist/v2/{read-session-chunk-89ep8br4.js → read-session-chunk-qzw3vedr.js} +2 -2
  97. package/dist/v2/{recomp-orchestrator-9wap1z1d.js → recomp-orchestrator-4mrvs5yc.js} +7 -7
  98. package/dist/v2/{render-bzzypsgy.js → render-r2djh67k.js} +7 -7
  99. package/dist/v2/{search-ymm2crs3.js → search-51qr14ed.js} +5 -5
  100. package/dist/v2/{search-archive-4yr4hw2m.js → search-archive-4bq4ff8q.js} +5 -5
  101. package/dist/v2/{server-8xgs110k.js → server-606mnrv4.js} +212 -4
  102. package/dist/v2/{server-7861dnm3.js → server-awth2wsg.js} +1 -1
  103. package/dist/v2/{server-d0h1gjz2.js → server-b25kh28g.js} +3 -3
  104. package/dist/v2/{server-62t1852h.js → server-b25nvm9c.js} +1 -1
  105. package/dist/v2/{server-6mq43ear.js → server-c1vcbszm.js} +1 -1
  106. package/dist/v2/{server-xn7fpv2b.js → server-d2a639dg.js} +3 -3
  107. package/dist/v2/{server-6r3b0re0.js → server-f49pxtwf.js} +41 -8
  108. package/dist/v2/{server-e14d7ebh.js → server-mc5t7k8v.js} +1 -1
  109. package/dist/v2/{server-zedjjdc5.js → server-nbdfv1wx.js} +2 -2
  110. package/dist/v2/{server-e8ybwfv8.js → server-p2wxmjc3.js} +2 -2
  111. package/dist/v2/{server-ysg14rv1.js → server-qg8jyfxa.js} +13 -0
  112. package/dist/v2/{server-h95cdc30.js → server-s3m2y97h.js} +1 -1
  113. package/dist/v2/{server-1bks09js.js → server-zzwje0mz.js} +5 -5
  114. package/dist/v2/server.js +2 -2
  115. package/dist/v2/{storage-tags-8kktww54.js → storage-tags-4t9fb4ch.js} +1 -1
  116. package/dist/v2/{store-0kjfynwp.js → store-mba47sxn.js} +2 -2
  117. package/dist/v2/{store-reader-w0srb18d.js → store-reader-w7w8vfsy.js} +1 -1
  118. package/dist/v2/store-reader.d.ts +7 -0
  119. package/dist/v2/store-reader.d.ts.map +1 -1
  120. package/dist/v2/{v2-archive-reader-veyqp15a.js → v2-archive-reader-avcf7a5n.js} +1 -1
  121. package/dist/v2/{wrapup-orchestrator-89cg7p41.js → wrapup-orchestrator-zwpjqymz.js} +7 -7
  122. package/dist/{v2-archive-reader-3s332fn7.js → v2-archive-reader-cnhvhggz.js} +1 -1
  123. package/dist/{wrapup-orchestrator-41rt7etq.js → wrapup-orchestrator-g1gnymt3.js} +9 -9
  124. package/package.json +1 -1
  125. package/src/agents/dreamer.ts +3 -2
  126. package/src/agents/hidden-agent-registrations.ts +2 -2
  127. package/src/agents/permissions.test.ts +89 -3
  128. package/src/agents/permissions.ts +32 -0
  129. package/src/agents/smart-notes-dreamer-gate.fixture.ts +27 -4
  130. 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-6r3b0re0.js";
257
+ } from "./server-f49pxtwf.js";
251
258
  import {
252
259
  embedPauseBySession,
253
260
  embedRunStateBySession,
@@ -438,12 +445,12 @@ import {
438
445
  saveSourceContent,
439
446
  replaceSourceContent,
440
447
  getSourceContents
441
- } from "./server-zedjjdc5.js";
448
+ } from "./server-nbdfv1wx.js";
442
449
  import {
443
450
  cleanSearchText,
444
451
  matchedSearchSnippet,
445
452
  getLastIndexedOrdinal
446
- } from "./server-6mq43ear.js";
453
+ } from "./server-c1vcbszm.js";
447
454
  import {
448
455
  ensureSessionMetaRow,
449
456
  clearCachedM0M1,
@@ -460,6 +467,7 @@ import {
460
467
  isRecord,
461
468
  contentTagOwnerMessageId,
462
469
  estimateImageTokensFromDataUrl,
470
+ estimateImageTokensFromBase64,
463
471
  estimateToolAttachmentImageTokens,
464
472
  providerVisiblePart,
465
473
  CLEARED_TODO_STATE_JSON,
@@ -595,6 +603,8 @@ import {
595
603
  detectLatestTurnThinkingMismatch,
596
604
  isPrefixBoundThinkingModel,
597
605
  detectOverflow,
606
+ isMeasuredRefusalStatusVeto,
607
+ isProviderSizeRefusal,
598
608
  overflowLimitToStore,
599
609
  isProviderRateLimit,
600
610
  modelAcceptsEmptyContent,
@@ -643,10 +653,12 @@ import {
643
653
  estimateMessageTokens,
644
654
  wireContentBytes,
645
655
  createFinalWireUsageTracker,
656
+ estimateFrozenRequestInputTokens,
646
657
  estimateFinalWireInputTokens,
647
658
  estimateAppendedWireTokens,
648
659
  estimateEmergencyDropReclaimTokens,
649
660
  planEmergencyDrop,
661
+ tagsInEmergencyDropOrder,
650
662
  measureEmergencyTag,
651
663
  snapshotEmergencyServedMass,
652
664
  tagsSinceReading,
@@ -702,7 +714,7 @@ import {
702
714
  adoptNullOwnerToolTag2,
703
715
  getCandidateToolOwners2,
704
716
  pickNearestPriorOwner2
705
- } from "./server-8xgs110k.js";
717
+ } from "./server-606mnrv4.js";
706
718
  import {
707
719
  BoundedSessionMap,
708
720
  getTableColumnNames,
@@ -816,7 +828,7 @@ import {
816
828
  readRawSessionMessageOrdinalById2,
817
829
  readSessionChunk2,
818
830
  readRawSessionSeedTail2
819
- } from "./server-7861dnm3.js";
831
+ } from "./server-awth2wsg.js";
820
832
  import {
821
833
  getMessageIndexEpoch,
822
834
  isMessageIndexSearchable,
@@ -842,7 +854,7 @@ import {
842
854
  resolveMemoriesByIdsForSearch2,
843
855
  unifiedSearch2,
844
856
  formatSearchResults2
845
- } from "./server-xn7fpv2b.js";
857
+ } from "./server-d2a639dg.js";
846
858
  import {
847
859
  startBootDeadline,
848
860
  getUnconfirmedMigrationHolders,
@@ -858,7 +870,7 @@ import {
858
870
  openDatabaseAsync,
859
871
  isDatabasePersisted,
860
872
  getDatabasePersistenceError
861
- } from "./server-62t1852h.js";
873
+ } from "./server-b25nvm9c.js";
862
874
  import {
863
875
  V2_MEMORY_CATEGORIES,
864
876
  CATEGORY_PRIORITY
@@ -877,7 +889,7 @@ import {
877
889
  RAW_MESSAGE_TYPES2,
878
890
  V2StoreReaderPool2,
879
891
  V2StoreReader2
880
- } from "./server-ysg14rv1.js";
892
+ } from "./server-qg8jyfxa.js";
881
893
  import {
882
894
  configureContextDatabasePragmas2
883
895
  } from "./server-fb3zxn06.js";
@@ -1047,7 +1059,7 @@ import {
1047
1059
  readV2RawMessagePagesForConversion2,
1048
1060
  createV2RawMessageReader2,
1049
1061
  createV2RawMessageProvider2
1050
- } from "./server-e14d7ebh.js";
1062
+ } from "./server-mc5t7k8v.js";
1051
1063
  import {
1052
1064
  resolvePromptContext2
1053
1065
  } from "./server-fmsr7v69.js";
@@ -1055,15 +1067,15 @@ import {
1055
1067
  renderMessageByOrdinal2,
1056
1068
  renderVerboseRangeForTool2,
1057
1069
  renderItemByTag2
1058
- } from "./server-e8ybwfv8.js";
1059
- import"./server-h95cdc30.js";
1070
+ } from "./server-p2wxmjc3.js";
1071
+ import"./server-s3m2y97h.js";
1060
1072
  import {
1061
1073
  readV2ArchiveOffThread2
1062
- } from "./server-1bks09js.js";
1074
+ } from "./server-zzwje0mz.js";
1063
1075
  import {
1064
1076
  unresolvedLiveTailRefusal2,
1065
1077
  renderSearchArchiveOffThread2
1066
- } from "./server-d0h1gjz2.js";
1078
+ } from "./server-b25kh28g.js";
1067
1079
  import {
1068
1080
  markHostInstructionRow,
1069
1081
  hostInstructionRow,
@@ -1804,7 +1816,7 @@ __export(exports_coerce, {
1804
1816
  });
1805
1817
 
1806
1818
  // src/v2/hooks/context.ts
1807
- import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
1819
+ import { AsyncLocalStorage as AsyncLocalStorage3 } from "node:async_hooks";
1808
1820
  import { setTimeout as delay } from "node:timers/promises";
1809
1821
 
1810
1822
  // src/config/dependency-notes.ts
@@ -8222,6 +8234,235 @@ function createModuleToolBackends(options) {
8222
8234
  };
8223
8235
  }
8224
8236
 
8237
+ // src/hooks/magic-context/provider-refusal-count.ts
8238
+ import { AsyncLocalStorage } from "node:async_hooks";
8239
+ import { createHash as createHash3 } from "node:crypto";
8240
+ var RUN_END_GRACE_MS = 5000;
8241
+
8242
+ class ProviderRefusalCounts {
8243
+ requests = new BoundedSessionMap(1000);
8244
+ begin(session, startedAt, priorAssistantMessageID) {
8245
+ const previous = this.requests.get(session);
8246
+ let pending = previous?.refused;
8247
+ let refusedDigests = pending === undefined ? undefined : previous?.digests;
8248
+ if (previous)
8249
+ this.settle(session);
8250
+ let historyMatches = false;
8251
+ const request = {
8252
+ startedAt,
8253
+ priorAssistantMessageID,
8254
+ pass: {
8255
+ take: (model) => {
8256
+ const count = pending;
8257
+ pending = undefined;
8258
+ return this.requests.get(session) === request && historyMatches && count?.model === model ? count?.tokens : undefined;
8259
+ },
8260
+ save: (model, tokens) => {
8261
+ if (this.requests.get(session) !== request || request.ambiguousOutcome)
8262
+ return;
8263
+ request.prepared = makeCount(model, tokens);
8264
+ },
8265
+ freeze: (model, measure) => {
8266
+ if (this.requests.get(session) === request && !request.ambiguousOutcome && !request.settled)
8267
+ request.prepared = { model, measure };
8268
+ },
8269
+ observeHistory: (history) => {
8270
+ if (request.settled)
8271
+ return;
8272
+ request.snapshot = history;
8273
+ if (pending !== undefined) {
8274
+ historyMatches = refusedDigests !== undefined && startsWithDigests(history, refusedDigests);
8275
+ if (!historyMatches)
8276
+ pending = undefined;
8277
+ }
8278
+ refusedDigests = undefined;
8279
+ }
8280
+ }
8281
+ };
8282
+ this.requests.set(session, request);
8283
+ return request.pass;
8284
+ }
8285
+ latest(session, replyStartedAt) {
8286
+ const request = this.requests.get(session);
8287
+ if (request?.ambiguousOutcome)
8288
+ return;
8289
+ if (replyStartedAt !== undefined && (!Number.isFinite(replyStartedAt) || request?.startedAt !== undefined && replyStartedAt < request.startedAt))
8290
+ return;
8291
+ return request?.pass;
8292
+ }
8293
+ latestForTerminalFailure(session, assistantMessageID) {
8294
+ const request = this.requests.get(session);
8295
+ if (assistantMessageID !== undefined && assistantMessageID === request?.priorAssistantMessageID)
8296
+ return;
8297
+ return this.latest(session);
8298
+ }
8299
+ forget(session) {
8300
+ this.settle(session);
8301
+ this.requests.delete(session);
8302
+ }
8303
+ retainsHistorySnapshot(session) {
8304
+ return this.requests.get(session)?.snapshot !== undefined;
8305
+ }
8306
+ retainsFrozenDraft(session) {
8307
+ const prepared = this.requests.get(session)?.prepared;
8308
+ return prepared !== undefined && "measure" in prepared;
8309
+ }
8310
+ endRun(session, releaseTransport) {
8311
+ const request = this.requests.get(session);
8312
+ if (!request || request.settled || request.runEndTimer)
8313
+ return;
8314
+ const timer = setTimeout(() => {
8315
+ if (this.requests.peek(session)?.runEndTimer === timer)
8316
+ this.settle(session);
8317
+ releaseTransport?.();
8318
+ }, RUN_END_GRACE_MS);
8319
+ timer.unref();
8320
+ request.runEndTimer = timer;
8321
+ }
8322
+ settle(session) {
8323
+ const request = this.requests.get(session);
8324
+ if (!request)
8325
+ return;
8326
+ clearTimeout(request.runEndTimer);
8327
+ request.runEndTimer = undefined;
8328
+ request.settled = true;
8329
+ request.prepared = undefined;
8330
+ request.snapshot = undefined;
8331
+ }
8332
+ markOutcomeAmbiguous(session) {
8333
+ const request = this.requests.get(session);
8334
+ if (!request)
8335
+ return;
8336
+ request.ambiguousOutcome = true;
8337
+ request.prepared = undefined;
8338
+ request.snapshot = undefined;
8339
+ }
8340
+ discardDraft(session, pass) {
8341
+ const request = this.requests.get(session);
8342
+ if (request?.pass !== pass)
8343
+ return;
8344
+ request.prepared = undefined;
8345
+ request.refused = undefined;
8346
+ }
8347
+ discardPreparation(session, pass) {
8348
+ const request = this.requests.get(session);
8349
+ if (request?.pass !== pass)
8350
+ return;
8351
+ request.prepared = undefined;
8352
+ request.snapshot = undefined;
8353
+ }
8354
+ refusal(session, model, pass, tokens) {
8355
+ const request = this.requests.get(session);
8356
+ if (!request || request.settled || request.ambiguousOutcome || pass !== undefined && request.pass !== pass)
8357
+ return;
8358
+ const exact = pass && makeCount(model, tokens);
8359
+ if (exact) {
8360
+ request.refused = exact;
8361
+ armHistory(request);
8362
+ return;
8363
+ }
8364
+ if (request.refused || model !== undefined && request.prepared?.model !== model)
8365
+ return;
8366
+ const prepared = request.prepared;
8367
+ if (prepared && "measure" in prepared) {
8368
+ request.prepared = undefined;
8369
+ try {
8370
+ request.refused = makeCount(prepared.model, prepared.measure());
8371
+ } catch {}
8372
+ } else
8373
+ request.refused = prepared;
8374
+ armHistory(request);
8375
+ }
8376
+ }
8377
+ function makeCount(model, tokens) {
8378
+ return model && tokens !== undefined && Number.isFinite(tokens) && tokens > 0 ? { model, tokens } : undefined;
8379
+ }
8380
+ function armHistory(request) {
8381
+ if (!request.refused)
8382
+ return;
8383
+ const snapshot = request.snapshot;
8384
+ request.snapshot = undefined;
8385
+ if (request.digests || !snapshot)
8386
+ return;
8387
+ try {
8388
+ const digests = [];
8389
+ for (let index = 0;index < snapshot.ends.length; index++)
8390
+ digests.push(digestMessage(snapshot, index));
8391
+ request.digests = digests;
8392
+ } catch {}
8393
+ }
8394
+ var refusalHistoryDigest = {
8395
+ serialize: (values) => JSON.stringify(values),
8396
+ hash: (text) => createHash3("sha256").update(text).digest("base64")
8397
+ };
8398
+ function digestMessage(history, index) {
8399
+ const start = index === 0 ? 0 : history.ends[index - 1];
8400
+ return refusalHistoryDigest.hash(refusalHistoryDigest.serialize(history.values.slice(start, history.ends[index])));
8401
+ }
8402
+ function startsWithDigests(history, digests) {
8403
+ if (history.ends.length < digests.length)
8404
+ return false;
8405
+ try {
8406
+ for (let index = 0;index < digests.length; index++)
8407
+ if (digestMessage(history, index) !== digests[index])
8408
+ return false;
8409
+ } catch {
8410
+ return false;
8411
+ }
8412
+ return true;
8413
+ }
8414
+ function snapshotRefusalHistory(rows, read) {
8415
+ const values = [];
8416
+ const ends = new Array(rows.length);
8417
+ for (let index = 0;index < rows.length; index++) {
8418
+ read(rows[index], values);
8419
+ ends[index] = values.length;
8420
+ }
8421
+ return { values, ends };
8422
+ }
8423
+ function pushRefusalFields(record, values, skip) {
8424
+ for (const key in record) {
8425
+ if (key !== skip)
8426
+ values.push(key, record[key]);
8427
+ }
8428
+ }
8429
+ function readOpenCodeRefusalMessage(message, values) {
8430
+ values.push(message.info.role);
8431
+ for (const part of message.parts) {
8432
+ if (part === null || typeof part !== "object") {
8433
+ values.push(part);
8434
+ continue;
8435
+ }
8436
+ const record = part;
8437
+ switch (record.type) {
8438
+ case "text":
8439
+ case "reasoning":
8440
+ values.push(record.type, record.text);
8441
+ break;
8442
+ case "tool": {
8443
+ const state = record.state ?? {};
8444
+ values.push("tool", record.tool, state.status, state.input, state.output, state.error, state.attachments);
8445
+ break;
8446
+ }
8447
+ case "file":
8448
+ values.push("file", record.mime, record.url, record.filename);
8449
+ break;
8450
+ default:
8451
+ pushRefusalFields(record, values);
8452
+ }
8453
+ }
8454
+ }
8455
+ var activePass = new AsyncLocalStorage;
8456
+ function withProviderRefusalPass(session, pass, run) {
8457
+ return activePass.run({ session, pass }, run);
8458
+ }
8459
+ function takeProviderRefusedInputTokens(session, model) {
8460
+ const active = activePass.getStore();
8461
+ if (active?.session !== session)
8462
+ return;
8463
+ return active.pass.take(model);
8464
+ }
8465
+
8225
8466
  // src/hooks/magic-context/render-options.ts
8226
8467
  function createM0RenderOptions(controls, contextUsage, modelKey, resolvedContextLimit, projectPath) {
8227
8468
  return {
@@ -9177,14 +9418,12 @@ function applyHeuristicCleanup(sessionId, db, targets, messageTagNumbers, config
9177
9418
  priorInputSample,
9178
9419
  hasPriorDrop: priorInputSample > 0,
9179
9420
  passAlreadyPriced: emergency.passAlreadyPriced === true,
9180
- protectedToolTags: protectedTools
9421
+ protectedToolTags: protectedTools,
9422
+ ...emergency.refusedInputTokens === undefined ? {} : { refusedInputTokens: emergency.refusedInputTokens }
9181
9423
  });
9182
9424
  if (plan.shouldDrop) {
9183
- const toDrop = new Set(plan.tagNumbers);
9184
9425
  const newestEmergencyTags = recentTags;
9185
- for (const tag of tags) {
9186
- if (!toDrop.has(tag.tagNumber))
9187
- continue;
9426
+ for (const tag of tagsInEmergencyDropOrder(tags, plan)) {
9188
9427
  if (tag.status !== "active" || tag.type !== "tool")
9189
9428
  continue;
9190
9429
  const target = targets.get(tag.tagNumber);
@@ -10061,9 +10300,9 @@ function createExistingTagResolver(sessionId, tagger, db) {
10061
10300
  }
10062
10301
 
10063
10302
  // src/hooks/magic-context/transform-stage-logger.ts
10064
- import { AsyncLocalStorage } from "node:async_hooks";
10303
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
10065
10304
  var SLOW_STAGE_MS = 100;
10066
- var passes2 = new AsyncLocalStorage;
10305
+ var passes2 = new AsyncLocalStorage2;
10067
10306
  async function withTransformTimingSummary(run) {
10068
10307
  const pass = {
10069
10308
  stages: [],
@@ -11516,7 +11755,7 @@ async function runPostTransformPhase(args) {
11516
11755
  let isExplicitFlush = pendingMaterializationAtPassStart;
11517
11756
  const deferredMaterializationWasPending = deferredMaterializationAtPassStart;
11518
11757
  const alreadyRanThisTurn = heuristicsAlreadyRanThisTurn(args.lastHeuristicsTurnId, args.sessionId, args.currentTurnId);
11519
- const bands = pressureBands({
11758
+ const readingBands = pressureBands({
11520
11759
  percentage: args.contextUsage.percentage,
11521
11760
  fromEstimate: args.contextUsageFromEstimate === true,
11522
11761
  forceMaterializationPercentage: args.forceMaterializationPercentage,
@@ -11524,6 +11763,13 @@ async function runPostTransformPhase(args) {
11524
11763
  fullFeatureMode: args.fullFeatureMode,
11525
11764
  schedulerDecision: args.schedulerDecision
11526
11765
  });
11766
+ const measuredSizeRefusal = !compactionOff && args.refusedInputTokens !== undefined;
11767
+ const bands = measuredSizeRefusal && !readingBands.forceBandConfirmed ? {
11768
+ ...readingBands,
11769
+ emergencyDropEligible: true,
11770
+ forceBandConfirmed: true,
11771
+ executePressureEligible: true
11772
+ } : readingBands;
11527
11773
  const {
11528
11774
  forceMaterialization,
11529
11775
  emergencyDropEligible,
@@ -11807,7 +12053,7 @@ async function runPostTransformPhase(args) {
11807
12053
  executeReclaim: false,
11808
12054
  subagentExecute: !args.fullFeatureMode && args.schedulerDecision === "execute",
11809
12055
  hardFold: rewritingSignedPrefix || foldBustsServedPrefixThisPass || firstRenderBust || hostCheckpointRide,
11810
- force: forceRide({
12056
+ force: measuredSizeRefusal || forceRide({
11811
12057
  bands,
11812
12058
  percentage: args.contextUsage.percentage,
11813
12059
  fromEstimate: args.contextUsageFromEstimate === true,
@@ -12129,7 +12375,8 @@ async function runPostTransformPhase(args) {
12129
12375
  usagePercentage: args.contextUsage.percentage,
12130
12376
  passAlreadyPriced: emergencyRewriteAlreadyPriced,
12131
12377
  servedBeforePass: servedBeforeRemovals,
12132
- sinceReading: tagsNewerThanReading
12378
+ sinceReading: tagsNewerThanReading,
12379
+ ...args.refusedInputTokens === undefined ? {} : { refusedInputTokens: args.refusedInputTokens }
12133
12380
  } : undefined,
12134
12381
  routine: routineCleanupApplied,
12135
12382
  caveman: cavemanConfig
@@ -13306,12 +13553,12 @@ function systemPromptDates(prompt, sticky) {
13306
13553
  }
13307
13554
 
13308
13555
  // src/hooks/magic-context/system-prompt-diagnostics.ts
13309
- import { createHash as createHash3 } from "node:crypto";
13556
+ import { createHash as createHash4 } from "node:crypto";
13310
13557
  function snapshotSystemPrompt(system, preset) {
13311
13558
  return { elements: system.map((element) => Buffer.from(element)), preset };
13312
13559
  }
13313
13560
  function describeSystemPromptChange(previous, current) {
13314
- const metadata = (element) => element === undefined ? "absent" : `bytes=${element.length},md5=${createHash3("md5").update(element).digest("hex")}`;
13561
+ const metadata = (element) => element === undefined ? "absent" : `bytes=${element.length},md5=${createHash4("md5").update(element).digest("hex")}`;
13315
13562
  const elements = [];
13316
13563
  for (let index = 0;index < Math.max(previous?.elements.length ?? 0, current.elements.length); index++) {
13317
13564
  const before = previous?.elements[index];
@@ -14204,7 +14451,8 @@ function decideSignedThinkingHold(args) {
14204
14451
  const ended = readingEndsHold({
14205
14452
  usagePercentage: args.usagePercentage,
14206
14453
  capPercentage,
14207
- forceBandPressure: args.forceBandPressure
14454
+ forceBandPressure: args.forceBandPressure,
14455
+ refusedInputTokens: args.refusedInputTokens
14208
14456
  });
14209
14457
  if (ended !== null)
14210
14458
  return { held: false, reason: ended, heavyStepsBack, heavyStepTokens, capPercentage };
@@ -14219,7 +14467,8 @@ function decideSignedThinkingHold(args) {
14219
14467
  function readingEndsHold(args) {
14220
14468
  if (!(args.usagePercentage < args.capPercentage))
14221
14469
  return "above_cap";
14222
- return args.forceBandPressure ? "force_band" : null;
14470
+ const refused = args.refusedInputTokens;
14471
+ return args.forceBandPressure || refused !== undefined && Number.isFinite(refused) && refused > 0 ? "force_band" : null;
14223
14472
  }
14224
14473
 
14225
14474
  // src/hooks/magic-context/priced-pass-sizing.ts
@@ -14554,7 +14803,7 @@ function evaluateRequestToolsRelease(args) {
14554
14803
  }
14555
14804
 
14556
14805
  // src/hooks/magic-context/rust-mode-transform.ts
14557
- import { createHash as createHash7, randomUUID as randomUUID2 } from "node:crypto";
14806
+ import { createHash as createHash8, randomUUID as randomUUID2 } from "node:crypto";
14558
14807
 
14559
14808
  // src/features/magic-context/memory/single-store-embedding-drain.ts
14560
14809
  function isWatermarkRow(row) {
@@ -14611,7 +14860,7 @@ function advanceEmbeddedWatermark(db, projectPath, upTo) {
14611
14860
  }
14612
14861
 
14613
14862
  // src/features/magic-context/mural/source-revision.ts
14614
- import { createHash as createHash4 } from "node:crypto";
14863
+ import { createHash as createHash5 } from "node:crypto";
14615
14864
  var statements = new WeakMap;
14616
14865
  function muralSourceRevision(db, projectPath) {
14617
14866
  let statement = statements.get(db);
@@ -14628,7 +14877,7 @@ function muralSourceRevision(db, projectPath) {
14628
14877
  statements.set(db, statement);
14629
14878
  }
14630
14879
  const row = statement.get(projectPath, Date.now());
14631
- return createHash4("sha256").update(row.revision).digest("hex");
14880
+ return createHash5("sha256").update(row.revision).digest("hex");
14632
14881
  }
14633
14882
 
14634
14883
  // src/features/magic-context/install-instance-id.ts
@@ -17005,7 +17254,7 @@ function noteExternalLkgReplay(participant, sessionId, inputMessages, servedMess
17005
17254
  }
17006
17255
 
17007
17256
  // src/hooks/magic-context/rust-served-raw.ts
17008
- import { createHash as createHash6 } from "node:crypto";
17257
+ import { createHash as createHash7 } from "node:crypto";
17009
17258
  class RustServedRawConflict extends EmergencyFailClosedError {
17010
17259
  reason;
17011
17260
  messageIds;
@@ -17019,7 +17268,7 @@ class RustServedRawConflict extends EmergencyFailClosedError {
17019
17268
  }
17020
17269
  function partDigest(part) {
17021
17270
  const serialized = JSON.stringify(part);
17022
- return createHash6("sha256").update(stableStringify(serialized === undefined ? undefined : JSON.parse(serialized))).digest("hex");
17271
+ return createHash7("sha256").update(stableStringify(serialized === undefined ? undefined : JSON.parse(serialized))).digest("hex");
17023
17272
  }
17024
17273
  function records(doc) {
17025
17274
  if (doc.rustServedRaw === undefined)
@@ -17571,10 +17820,10 @@ function messageCacheSignature(message) {
17571
17820
  const parts = Array.isArray(message.parts) ? message.parts : [];
17572
17821
  const serializedParts = JSON.stringify(parts) ?? "null";
17573
17822
  const serializedMessage = JSON.stringify(message) ?? "null";
17574
- return `${messageIdOf(message) ?? ""}:${parts.length}:${Buffer.byteLength(serializedParts)}:${createHash7("sha256").update(serializedMessage).digest("hex")}`;
17823
+ return `${messageIdOf(message) ?? ""}:${parts.length}:${Buffer.byteLength(serializedParts)}:${createHash8("sha256").update(serializedMessage).digest("hex")}`;
17575
17824
  }
17576
17825
  function advanceWireFingerprint(previous, encoded) {
17577
- return createHash7("sha256").update(previous).update("\\0").update(JSON.stringify(encoded) ?? "null").digest("hex");
17826
+ return createHash8("sha256").update(previous).update("\\0").update(JSON.stringify(encoded) ?? "null").digest("hex");
17578
17827
  }
17579
17828
  function buildWireFingerprint(encoded) {
17580
17829
  let fingerprint = "rust-wire-v1";
@@ -19363,7 +19612,7 @@ ${notice}`, {}));
19363
19612
  const id = messageIdOf(message) ?? `index:${todoStart + offset}`;
19364
19613
  const parts = message.parts?.filter((part) => isRecord4(part) && part.type === "tool" && part.tool === "todowrite");
19365
19614
  if (parts?.length) {
19366
- todoCalls.set(id, createHash7("sha256").update(JSON.stringify(parts)).digest("hex"));
19615
+ todoCalls.set(id, createHash8("sha256").update(JSON.stringify(parts)).digest("hex"));
19367
19616
  } else {
19368
19617
  todoCalls.delete(id);
19369
19618
  }
@@ -21654,6 +21903,7 @@ function createTransform(deps) {
21654
21903
  }
21655
21904
  noteServedModel(sessionId, modelForBudget);
21656
21905
  const resolvedProviderID = modelForBudget?.providerID;
21906
+ const refusedInputTokens = takeProviderRefusedInputTokens(sessionId, modelForBudget ? `${modelForBudget.providerID}/${modelForBudget.modelID}` : undefined);
21657
21907
  activeThinkingTurn ||= hasActiveAnthropicThinkingTurn(messages, resolvedProviderID, modelForBudget?.modelID);
21658
21908
  const signedThinkingPrefixBound = activeThinkingTurn && (isPrefixBoundThinkingModel(activeThinkingModel?.providerID, activeThinkingModel?.modelID) || isPrefixBoundThinkingModel(resolvedProviderID, modelForBudget?.modelID));
21659
21909
  const canUseEmptySentinels = modelAcceptsEmptyContent(resolvedProviderID);
@@ -21732,6 +21982,7 @@ function createTransform(deps) {
21732
21982
  messages,
21733
21983
  usagePercentage: contextUsageEarly.percentage,
21734
21984
  executeThresholdPercentage: effectiveExecuteThresholdPercentage,
21985
+ refusedInputTokens,
21735
21986
  forceBandPressure: forceBandConfirmed({
21736
21987
  percentage: contextUsageEarly.percentage,
21737
21988
  fromEstimate: hostOverWindow,
@@ -22538,6 +22789,7 @@ ${notice}`, notificationParams));
22538
22789
  const sizedHoldEnd = activeThinkingPrefixHold && !compactionOff && signedThinkingHold?.held === true ? readingEndsHold({
22539
22790
  usagePercentage: contextUsage.percentage,
22540
22791
  capPercentage: signedThinkingHold.capPercentage,
22792
+ refusedInputTokens,
22541
22793
  forceBandPressure: forceBandConfirmed({
22542
22794
  percentage: contextUsage.percentage,
22543
22795
  fromEstimate: contextUsageFromEstimate,
@@ -22654,6 +22906,7 @@ ${notice}`, notificationParams));
22654
22906
  protectedCutoff,
22655
22907
  protectedCount: protectionWindow.status.protectedCount,
22656
22908
  emergencyCeilingTokens,
22909
+ ...refusedInputTokens === undefined ? {} : { refusedInputTokens },
22657
22910
  pendingCompartmentInjection,
22658
22911
  prefixTrimSourceOrder,
22659
22912
  coveredHostInstructions,
@@ -23026,6 +23279,7 @@ ${notice}`, notificationParams));
23026
23279
  }
23027
23280
  }
23028
23281
  reclaim?.markRetired();
23282
+ reclaim?.settle?.();
23029
23283
  const signedThinkingServed = isPrefixBoundThinkingModel(modelForBudget?.providerID, modelForBudget?.modelID) && servesThinkingBlock(messages, modelForBudget?.providerID, modelForBudget?.modelID);
23030
23284
  finishSystemDateRefresh(deps.historyRefreshSessions, dateRequest, postTransformResult.bustedThisPass && !activeThinkingPrefixHold && !signedThinkingServed || postTransformResult.thinkingReleasedForFit === true, signedThinkingServed);
23031
23285
  if (activeThinkingPrefixHold && !postTransformResult.thinkingReleasedForFit && sessionMeta.cachedM0Bytes != null && sessionMeta.cachedM1Bytes != null) {
@@ -23832,12 +24086,23 @@ function createMessagesTransformHandler(args) {
23832
24086
  const servedSessionId = args.recordServed === false ? null : resolveSessionId2(output);
23833
24087
  if (servedSessionId)
23834
24088
  beginServedRequest(servedSessionId);
24089
+ const refusalCounts = args.providerRefusalCounts;
24090
+ const pass = servedSessionId && refusalCounts && !resolveRust(servedSessionId) ? refusalCounts.begin(servedSessionId, Date.now()) : undefined;
24091
+ if (pass)
24092
+ pass.observeHistory(snapshotRefusalHistory(output.messages, readOpenCodeRefusalMessage));
23835
24093
  let returned = false;
23836
24094
  try {
23837
- const served = await servePass(input, output);
24095
+ const served = await (servedSessionId && pass ? withProviderRefusalPass(servedSessionId, pass, () => servePass(input, output)) : servePass(input, output));
23838
24096
  returned = true;
24097
+ if (pass) {
24098
+ try {
24099
+ refusalCounts?.captureMessages(pass, output.messages);
24100
+ } catch {}
24101
+ }
23839
24102
  return served;
23840
24103
  } catch (error) {
24104
+ if (pass && servedSessionId)
24105
+ refusalCounts?.discardPreparation(servedSessionId, pass);
23841
24106
  if (args.onRefusal && isTransformRefusal(error) && !(error instanceof EmergencyFailClosedError && error.noticeHandled)) {
23842
24107
  const sessionId = servedSessionId ?? resolveSessionId2(output);
23843
24108
  if (sessionId) {
@@ -25067,7 +25332,7 @@ function setSessionWorkMetricsCarry(db, sessionId, source, carry, metrics) {
25067
25332
  import { readFileSync, statSync } from "node:fs";
25068
25333
 
25069
25334
  // src/plugin/embedding-bootstrap-helpers.ts
25070
- import { createHash as createHash8 } from "node:crypto";
25335
+ import { createHash as createHash9 } from "node:crypto";
25071
25336
  var EMBEDDING_AFFECTING_KEYS = new Set([
25072
25337
  "embedding.api_key",
25073
25338
  "embedding.endpoint",
@@ -25116,7 +25381,7 @@ var EMBEDDING_WARNING_TERMS = [
25116
25381
  ];
25117
25382
  var loggedFailureSignatures = new Map;
25118
25383
  function sha256Prefix(value, length = 16) {
25119
- return createHash8("sha256").update(value).digest("hex").slice(0, length);
25384
+ return createHash9("sha256").update(value).digest("hex").slice(0, length);
25120
25385
  }
25121
25386
  function warningLooksEmbeddingRelated(message) {
25122
25387
  const lower = message.toLowerCase();
@@ -26654,7 +26919,7 @@ function registerRpcHandlers(rpcServer, args) {
26654
26919
  const db = readDatabase();
26655
26920
  if (!db)
26656
26921
  return { ok: false, error: "db unavailable" };
26657
- const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-9wap1z1d.js"));
26922
+ const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-4mrvs5yc.js"));
26658
26923
  const { sendIgnoredMessage } = await importPluginModule(() => import("./send-session-notification-vtnk598k.js"));
26659
26924
  log2(`[rpc] recomp requested for session ${sessionId}`);
26660
26925
  if (!args.client && !args.hiddenCompletionExecutor) {
@@ -26739,7 +27004,7 @@ function registerRpcHandlers(rpcServer, args) {
26739
27004
  const db = readDatabase();
26740
27005
  if (!db)
26741
27006
  return { ok: false, error: "db unavailable" };
26742
- const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-89cg7p41.js"));
27007
+ const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-zwpjqymz.js"));
26743
27008
  const model = await args.readSelectedSessionModel?.(sessionId) ?? liveSessionState.liveModelBySession.get(sessionId);
26744
27009
  const window = resolveOpenCodeWrapupWindow(db, sessionId, model);
26745
27010
  if (!window)
@@ -26817,7 +27082,7 @@ function registerRpcHandlers(rpcServer, args) {
26817
27082
  }
26818
27083
 
26819
27084
  // src/plugin/subagent-tool-policy.ts
26820
- 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]);
26821
27086
  function subagentToolRefusal(db, toolId, sessionId, isInternalChild = () => false) {
26822
27087
  if (PRIMARY_ONLY_TOOLS.has(toolId) && !isInternalChild(sessionId) && getOrCreateSessionMeta(db, sessionId).isSubagent) {
26823
27088
  return `Error: ${toolId} is unavailable in subagent sessions. Use the primary session instead.`;
@@ -28021,6 +28286,82 @@ var coveredOn = (value) => typeof value === "object" && value !== null && value.
28021
28286
  function retiredLiveInstructionIDs(db, sessionID) {
28022
28287
  return decode(readReplayEnvelope(db, sessionID)[namespace]);
28023
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
+ }
28024
28365
  function coveredInstructionSupersessionOn(db, sessionID) {
28025
28366
  return coveredOn(readReplayEnvelope(db, sessionID)[coveredNamespace]);
28026
28367
  }
@@ -28075,7 +28416,8 @@ function isMarkedInstructionUpdate(row) {
28075
28416
  const sources = metadata.instructionSources;
28076
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);
28077
28418
  }
28078
- 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);
28079
28421
  const instructionRows = (list) => list.flatMap((message) => {
28080
28422
  const row = hostInstructionRow(message.info);
28081
28423
  return row ? [{ message, row }] : [];
@@ -28083,7 +28425,19 @@ function reclaimInstructionRows(db, sessionID, messages, permitted, folded = new
28083
28425
  const coveredRows = coveredSupersessionEnabled ? instructionRows(covered) : [];
28084
28426
  const rows = [...coveredRows, ...instructionRows(messages)];
28085
28427
  const coveredMessages = new Set(coveredRows.map(({ message }) => message));
28086
- 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);
28087
28441
  const coveredFollowed = rows.length > 0 && (coveredRows.length > 0 || permitted) && coveredInstructionSupersessionOn(db, sessionID);
28088
28442
  const switchCovered = permitted && rows.length > 0 && !coveredFollowed && coveredSupersessionEnabled;
28089
28443
  const selected = permitted ? supersededInstructionIDs(rows.map(({ row }) => row)) : new Set;
@@ -28096,6 +28450,13 @@ function reclaimInstructionRows(db, sessionID, messages, permitted, folded = new
28096
28450
  const newlyRetired = new Set([...selected].filter((id) => !retired.has(id)));
28097
28451
  const omitted = new Set([...retired, ...newlyRetired]);
28098
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;
28099
28460
  const edits = [];
28100
28461
  for (const { message, row } of rows) {
28101
28462
  if (!omits(message, row.id))
@@ -28105,33 +28466,81 @@ function reclaimInstructionRows(db, sessionID, messages, permitted, folded = new
28105
28466
  edits.push(message);
28106
28467
  message.parts = [];
28107
28468
  }
28469
+ const decisions = newlyRetired.size > 0 || switchCovered;
28470
+ const pending = pendingLowering(db, sessionID);
28471
+ let wrote;
28108
28472
  return {
28109
28473
  edits,
28110
- hasDecisions: newlyRetired.size > 0 || switchCovered,
28474
+ hasDecisions: decisions,
28111
28475
  record(doc) {
28112
- if (newlyRetired.size === 0 && !switchCovered)
28476
+ if (!decisions)
28113
28477
  return false;
28114
28478
  const current = decode(doc[namespace]);
28115
28479
  if ([...newlyRetired].every((id) => current.has(id)) && (!switchCovered || coveredOn(doc[coveredNamespace])))
28116
28480
  return false;
28117
- for (const id of folded)
28118
- 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
+ }
28119
28490
  for (const id of newlyRetired)
28120
28491
  current.add(id);
28492
+ if (coverable(dropped) >= 0)
28493
+ nextThrough = Math.max(nextThrough ?? -1, coverable(dropped));
28121
28494
  doc.version = 2;
28122
28495
  doc[namespace] = [...current];
28123
28496
  if (switchCovered)
28124
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
+ }
28125
28503
  return true;
28126
28504
  },
28127
28505
  markRetired() {
28506
+ if (pending && wrote !== undefined)
28507
+ clearPendingLowering(db, sessionID, pending);
28128
28508
  for (const { message, row } of rows) {
28129
28509
  if (omits(message, row.id))
28130
28510
  markRetiredInstructionRow(message.info);
28131
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);
28132
28540
  }
28133
28541
  };
28134
28542
  }
28543
+ var initialFailuresLogged = new WeakMap;
28135
28544
 
28136
28545
  // src/v2/fold/manual-baseline.ts
28137
28546
  var text = (value) => value == null ? null : typeof value === "string" ? value : Buffer.from(value).toString("utf8");
@@ -28178,7 +28587,7 @@ function stageManualBaseline(db, sessionID, render) {
28178
28587
  import { randomUUID as randomUUID4 } from "node:crypto";
28179
28588
 
28180
28589
  // src/v2/fold/owner.ts
28181
- import { createHash as createHash9 } from "node:crypto";
28590
+ import { createHash as createHash10 } from "node:crypto";
28182
28591
 
28183
28592
  // src/v2/fold/summary.ts
28184
28593
  var RAW_HISTORY_ACCOUNT = "Magic Context retains the conversation as raw messages; no summarized history is available yet.";
@@ -28208,7 +28617,7 @@ ${head}
28208
28617
  }
28209
28618
 
28210
28619
  // src/v2/fold/owner.ts
28211
- var foldDigest = (value) => createHash9("sha256").update(value).digest("hex");
28620
+ var foldDigest = (value) => createHash10("sha256").update(value).digest("hex");
28212
28621
  var boundToCheckpoint = (record) => record.cutSeq !== undefined || record.rendered !== undefined || record.answered !== undefined;
28213
28622
 
28214
28623
  class FoldOwner {
@@ -33030,11 +33439,11 @@ class DeletedSessionTombstones {
33030
33439
  }
33031
33440
 
33032
33441
  // src/features/magic-context/dreamer/task-executor.ts
33033
- import { createHash as createHash17 } from "node:crypto";
33442
+ import { createHash as createHash18 } from "node:crypto";
33034
33443
  import { existsSync as existsSync7, readFileSync as readFileSync8 } from "node:fs";
33035
33444
 
33036
33445
  // src/features/magic-context/mural/compress-cues.ts
33037
- import { createHash as createHash10 } from "node:crypto";
33446
+ import { createHash as createHash11 } from "node:crypto";
33038
33447
 
33039
33448
  // src/features/magic-context/dreamer/lease.ts
33040
33449
  var LEASE_DURATION_MS = 2 * 60 * 1000;
@@ -33740,7 +34149,7 @@ async function applyCuesThroughModule(args, chunk, manifestText, signal) {
33740
34149
  log2(`[dreamer] compress-cues: skipped cue for memory ${entry.id} (${failure.reason}; rejection ${rejectionCount}/${CUE_REJECTION_LATCH_THRESHOLD})`);
33741
34150
  }
33742
34151
  }
33743
- const commandId = `mural-cues:${route.moduleCommandId}:${createHash10("sha256").update(chunk.map((candidate) => candidate.memory.id).join(",")).digest("hex").slice(0, 24)}`;
34152
+ const commandId = `mural-cues:${route.moduleCommandId}:${createHash11("sha256").update(chunk.map((candidate) => candidate.memory.id).join(",")).digest("hex").slice(0, 24)}`;
33744
34153
  let response;
33745
34154
  try {
33746
34155
  response = await route.moduleClient.call({
@@ -33906,14 +34315,16 @@ Project memory uses exactly 5 categories. Every memory belongs to one:
33906
34315
  - **NAMING** — naming conventions and canonical names. Not inventories.
33907
34316
 
33908
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.`;
33909
- 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.
33910
34321
 
33911
34322
  ## Memory operations
33912
34323
  - The scoped category snapshot arrives in the first message. Do not list or get it again; track mutation deltas.
33913
- - \`action="merge", ids=[N,M,...], content="...", category="..."\` — consolidate duplicates into one canonical memory
33914
- - \`action="update", ids=[N], content="...", superseded_by=M\` — rewrite content; name where removed detail survives when cutting more than half
33915
- - \`action="write", category="...", content="..."\` — create a memory (SPLITS ONLY — never mint new facts)
33916
- - \`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
33917
34328
 
33918
34329
  ## Rules
33919
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.
@@ -33924,6 +34335,8 @@ var CURATE_SYSTEM_PROMPT = `You are a memory-pool curator for the magic-context
33924
34335
  6. **Never mint new facts** — that is the historian's job. \`write\` is for splitting a compound memory only.
33925
34336
 
33926
34337
  ${PROJECT_MEMORY_TAXONOMY}`;
34338
+ }
34339
+ var CURATE_SYSTEM_PROMPT = buildCurateSystemPrompt(CTX_MEMORY_CURATE_TOOL_NAME);
33927
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 [].`;
33928
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.
33929
34342
 
@@ -33958,7 +34371,7 @@ The memories below are assumed ACCURATE (a separate verify task keeps them true)
33958
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.
33959
34372
 
33960
34373
  ### Phase A — Consolidate duplicates
33961
- 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.
33962
34375
 
33963
34376
  ### Phase B — Improve wording
33964
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.
@@ -34087,7 +34500,8 @@ function buildDreamTaskPrompt(task, args) {
34087
34500
  projectPath: args.projectPath,
34088
34501
  category: args.curate?.category ?? "PROJECT_RULES",
34089
34502
  memories: args.curate?.memories ?? [],
34090
- crossChunkCandidates: args.curate?.crossChunkCandidates
34503
+ crossChunkCandidates: args.curate?.crossChunkCandidates,
34504
+ memoryTool: args.curate?.memoryTool
34091
34505
  });
34092
34506
  case "maintain-docs":
34093
34507
  return buildMaintainDocsPrompt(args.projectPath, args.docsChangeSet ?? "", args.existingDocs ?? { architecture: false, structure: false }, args.docsBudget, args.docsCurrentTokens, args.docsContents);
@@ -34357,7 +34771,7 @@ function applyReviewVerdict(args, leaseKey, parsed, result) {
34357
34771
  }
34358
34772
 
34359
34773
  // src/features/magic-context/dreamer/classify.ts
34360
- import { createHash as createHash11 } from "node:crypto";
34774
+ import { createHash as createHash12 } from "node:crypto";
34361
34775
 
34362
34776
  // src/plugin/rust-tool-backends.ts
34363
34777
  function isRustAuthorityDrainingError(error) {
@@ -34794,7 +35208,7 @@ async function runClassifyThroughModule(args, chunk, anchors, signal, runOnHost)
34794
35208
  if (entry.qualifier)
34795
35209
  modelVariants[entry.model] = entry.qualifier;
34796
35210
  }
34797
- const commandId = `classify:${args.moduleCommandId ?? Date.now()}:${createHash11("sha256").update(chunk.map((candidate) => candidate.id).join(",")).digest("hex").slice(0, 24)}`;
35211
+ const commandId = `classify:${args.moduleCommandId ?? Date.now()}:${createHash12("sha256").update(chunk.map((candidate) => candidate.id).join(",")).digest("hex").slice(0, 24)}`;
34798
35212
  const runTask = (hostCompletion) => args.moduleClient?.call({
34799
35213
  sessionId: args.moduleSessionId,
34800
35214
  projectRoot: args.moduleProjectRoot,
@@ -35022,7 +35436,8 @@ var refusalReasons = new Set(CURATE_SAFETY_REFUSAL_REASONS);
35022
35436
  function parseCurateSafetyRefusal(action, output) {
35023
35437
  if (action !== "archive" && action !== "update")
35024
35438
  return null;
35025
- 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] ?? "");
35026
35441
  if (refusal?.[1] !== action || !refusal[2])
35027
35442
  return null;
35028
35443
  const reasons = [...new Set(refusal[2].split(","))];
@@ -35073,21 +35488,27 @@ function assessCurateMutationSafety(args) {
35073
35488
  return null;
35074
35489
  }
35075
35490
  function recordCurateSafetyRefusal(sessionId, refusal) {
35076
- const count = (refusalCountsBySession.get(sessionId) ?? 0) + 1;
35077
- 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);
35078
35496
  const lengths = refusal.originalChars === undefined ? "" : ` original_chars=${refusal.originalChars} replacement_chars=${refusal.replacementChars ?? 0}`;
35079
35497
  log2(`[dreamer] curate safety refusal: session_id=${sessionId} memory_id=${refusal.memoryId} verdict=${refusal.verdict} reason=${refusal.reason}${lengths} refused=${count}`);
35080
35498
  return count;
35081
35499
  }
35500
+ function curateSafetyRefusalsForMemory(sessionId, memoryId) {
35501
+ return refusalCountsBySession.get(sessionId)?.byMemory.get(memoryId) ?? 0;
35502
+ }
35082
35503
  function takeCurateSafetyRefusalCount(sessionId) {
35083
- const count = refusalCountsBySession.get(sessionId) ?? 0;
35504
+ const count = refusalCountsBySession.get(sessionId)?.total ?? 0;
35084
35505
  refusalCountsBySession.delete(sessionId);
35085
35506
  return count;
35086
35507
  }
35087
35508
 
35088
35509
  // src/features/magic-context/dreamer/docs-proposals.ts
35089
35510
  import { execFileSync } from "node:child_process";
35090
- import { createHash as createHash12 } from "node:crypto";
35511
+ import { createHash as createHash13 } from "node:crypto";
35091
35512
  import {
35092
35513
  existsSync as existsSync4,
35093
35514
  mkdirSync,
@@ -35102,7 +35523,7 @@ import {
35102
35523
  import { tmpdir } from "node:os";
35103
35524
  import { join as join8 } from "node:path";
35104
35525
  var FILES = ["ARCHITECTURE.md", "STRUCTURE.md"];
35105
- var hash = (text) => createHash12("sha256").update(text).digest("hex");
35526
+ var hash = (text) => createHash13("sha256").update(text).digest("hex");
35106
35527
  var proposalDir = (projectDir) => join8(projectDir, ".cortexkit/magic-context/docs-update-proposals");
35107
35528
  function docsBaseHashes(projectDir) {
35108
35529
  return Object.fromEntries(FILES.map((name) => [
@@ -35749,7 +36170,7 @@ function throwIfAborted2(signal) {
35749
36170
  }
35750
36171
 
35751
36172
  // src/features/magic-context/smart-notes/compiler.ts
35752
- import { createHash as createHash13 } from "node:crypto";
36173
+ import { createHash as createHash14 } from "node:crypto";
35753
36174
 
35754
36175
  // src/features/magic-context/smart-notes/compiler-prompt.ts
35755
36176
  var SMART_NOTE_COMPILER_SYSTEM_PROMPT = `You are the Magic Context smart-note compiler for the magic-context system.
@@ -36096,7 +36517,7 @@ function manifestAdvisoryWarnings(code, manifest) {
36096
36517
  return warnings;
36097
36518
  }
36098
36519
  function hashCheck(surfaceCondition, compiledCheck, manifest, checkCron) {
36099
- return createHash13("sha256").update(surfaceCondition ?? "").update("\x00").update(compiledCheck).update("\x00").update(JSON.stringify(manifest)).update("\x00").update(checkCron).digest("hex");
36520
+ return createHash14("sha256").update(surfaceCondition ?? "").update("\x00").update(compiledCheck).update("\x00").update(JSON.stringify(manifest)).update("\x00").update(checkCron).digest("hex");
36100
36521
  }
36101
36522
  function extractJsonObject(output) {
36102
36523
  const fenced = output.match(/```(?:json)?\s*([\s\S]*?)```/i);
@@ -36869,7 +37290,7 @@ function snapshotMaintainDocsFiles(docsDir) {
36869
37290
  }
36870
37291
 
36871
37292
  // src/features/magic-context/dreamer/map-memories.ts
36872
- import { createHash as createHash14 } from "node:crypto";
37293
+ import { createHash as createHash15 } from "node:crypto";
36873
37294
 
36874
37295
  // src/features/magic-context/dreamer/map-memories-prompt.ts
36875
37296
  import { execFile as execFile2 } from "node:child_process";
@@ -37514,7 +37935,7 @@ async function applyParsedBatchMappings(args, batch, parsed, budgetFinalized = f
37514
37935
  name: "memory.set_mapping",
37515
37936
  arguments: {
37516
37937
  memory_project: args.projectIdentity,
37517
- command_id: `${args.moduleRoute.moduleCommandId}:${createHash14("sha256").update(rows.map((row) => row.memory_id).join(",")).digest("hex").slice(0, 16)}`,
37938
+ command_id: `${args.moduleRoute.moduleCommandId}:${createHash15("sha256").update(rows.map((row) => row.memory_id).join(",")).digest("hex").slice(0, 16)}`,
37518
37939
  rows
37519
37940
  }
37520
37941
  }
@@ -38848,7 +39269,7 @@ function insertDreamRun(db, run) {
38848
39269
  }
38849
39270
 
38850
39271
  // src/features/magic-context/dreamer/verify.ts
38851
- import { createHash as createHash16 } from "node:crypto";
39272
+ import { createHash as createHash17 } from "node:crypto";
38852
39273
 
38853
39274
  // src/features/magic-context/dreamer/verify-diff.ts
38854
39275
  import { execFile as execFile3 } from "node:child_process";
@@ -38972,7 +39393,7 @@ Read only these changed line ranges if they may affect the claim.`
38972
39393
  import path6 from "node:path";
38973
39394
 
38974
39395
  // src/features/magic-context/dreamer/verify-state.ts
38975
- import { createHash as createHash15 } from "node:crypto";
39396
+ import { createHash as createHash16 } from "node:crypto";
38976
39397
  import { readFile, realpath as realpath2 } from "node:fs/promises";
38977
39398
  import path5 from "node:path";
38978
39399
  function verificationMetadata(memory) {
@@ -38985,7 +39406,7 @@ function verificationMetadata(memory) {
38985
39406
  }
38986
39407
  async function verificationFilesFingerprint(directory, files) {
38987
39408
  const root = await resolveGitTopLevel(directory) ?? path5.resolve(directory);
38988
- const hash = createHash15("sha256");
39409
+ const hash = createHash16("sha256");
38989
39410
  for (const file of [...new Set(files)].sort()) {
38990
39411
  const absolute = path5.resolve(root, file);
38991
39412
  const withinRoot = (candidate) => {
@@ -38998,7 +39419,7 @@ async function verificationFilesFingerprint(directory, files) {
38998
39419
  try {
38999
39420
  if (!withinRoot(await realpath2(absolute)))
39000
39421
  return null;
39001
- hash.update(createHash15("sha256").update(await readFile(absolute)).digest("hex"));
39422
+ hash.update(createHash16("sha256").update(await readFile(absolute)).digest("hex"));
39002
39423
  } catch (error) {
39003
39424
  if (error.code !== "ENOENT")
39004
39425
  return null;
@@ -39803,7 +40224,7 @@ async function applyParsedVerifyManifest(args, batch, parsed, headAtPrompt, budg
39803
40224
  name: "memory.set_verification",
39804
40225
  arguments: {
39805
40226
  memory_project: args.projectIdentity,
39806
- command_id: `${args.moduleRoute.moduleCommandId}:${createHash16("sha256").update(rows.map((row) => row.memory_id).join(",")).digest("hex").slice(0, 16)}`,
40227
+ command_id: `${args.moduleRoute.moduleCommandId}:${createHash17("sha256").update(rows.map((row) => row.memory_id).join(",")).digest("hex").slice(0, 16)}`,
39807
40228
  rows
39808
40229
  }
39809
40230
  }
@@ -40064,7 +40485,7 @@ function inspectCurateMemoryOperations(messages) {
40064
40485
  if (!isRecord(part) || part.type !== "tool")
40065
40486
  continue;
40066
40487
  const toolName = part.tool ?? part.name;
40067
- if (toolName !== "ctx_memory")
40488
+ if (toolName !== CTX_MEMORY_TOOL_NAME && toolName !== CTX_MEMORY_CURATE_TOOL_NAME)
40068
40489
  continue;
40069
40490
  const state = isRecord(part.state) ? part.state : null;
40070
40491
  const input = isRecord(state?.input) ? state.input : null;
@@ -40717,7 +41138,7 @@ function parseFrictionGateVerdict(verdict) {
40717
41138
  }
40718
41139
  function computeRetrospectiveWindowKey(flagged) {
40719
41140
  const anchors = flagged.map((message) => `${message.sessionId}:${message.ts}`).sort().join("|");
40720
- return createHash17("sha256").update(anchors).digest("hex").slice(0, 32);
41141
+ return createHash18("sha256").update(anchors).digest("hex").slice(0, 32);
40721
41142
  }
40722
41143
  function renderFrictionWindow(messages, flaggedOrdinals, radius = 2) {
40723
41144
  const flagged = new Set(flaggedOrdinals);
@@ -41236,6 +41657,9 @@ async function runAgenticTask(config, ctx, helpers) {
41236
41657
  const curateChunks = curateMemories ? chunkCurateMemories(curateMemories, Math.max(4000, Math.floor(resolveRetrospectiveUsableInputTokens(config, deps) * 2))) : [];
41237
41658
  const batches = task === "curate" ? curateChunks : [{ memories: [], crossChunkCandidates: [] }];
41238
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);
41239
41663
  let curateRefused = 0;
41240
41664
  let run = {
41241
41665
  output: [],
@@ -41256,7 +41680,8 @@ async function runAgenticTask(config, ctx, helpers) {
41256
41680
  curate: curateMemories && curateCategory ? {
41257
41681
  category: curateCategory,
41258
41682
  memories: batch.memories,
41259
- crossChunkCandidates: batch.crossChunkCandidates
41683
+ crossChunkCandidates: batch.crossChunkCandidates,
41684
+ memoryTool: curateMemoryTool
41260
41685
  } : undefined
41261
41686
  });
41262
41687
  if (deps.hiddenCompletionExecutor) {
@@ -41265,7 +41690,7 @@ async function runAgenticTask(config, ctx, helpers) {
41265
41690
  parentSessionId: parent ?? undefined,
41266
41691
  sessionDirectory: docsDir,
41267
41692
  agent: task === "maintain-docs" ? DREAMER_DOCS_AGENT : DREAMER_AGENT,
41268
- system: task === "maintain-docs" ? MAINTAIN_DOCS_SYSTEM_PROMPT : CURATE_SYSTEM_PROMPT,
41693
+ system: taskSystemPrompt,
41269
41694
  prompt: taskPrompt,
41270
41695
  title: `magic-context-dream-${task}`,
41271
41696
  callContext: `dreamer:${task}`,
@@ -41312,7 +41737,7 @@ async function runAgenticTask(config, ctx, helpers) {
41312
41737
  query: { directory: docsDir },
41313
41738
  body: {
41314
41739
  agent: task === "maintain-docs" ? DREAMER_DOCS_AGENT : DREAMER_AGENT,
41315
- 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),
41316
41741
  ...modelBodyField(config.model),
41317
41742
  parts: [{ type: "text", text: taskPrompt, synthetic: true }]
41318
41743
  }
@@ -42773,10 +43198,10 @@ function readForkHistoryGap(db, openReader, sessionID) {
42773
43198
  }
42774
43199
 
42775
43200
  // src/v2/hooks/generate.ts
42776
- import { createHash as createHash18 } from "node:crypto";
43201
+ import { createHash as createHash19 } from "node:crypto";
42777
43202
  var typedArrayName = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag)?.get;
42778
43203
  function hostPrefixDigest(messages, end) {
42779
- const hash = createHash18("sha256");
43204
+ const hash = createHash19("sha256");
42780
43205
  const chunks = [];
42781
43206
  let pendingCodeUnits = 0;
42782
43207
  const batchCodeUnits = 16 * 1024 * 1024;
@@ -42974,10 +43399,197 @@ function hiddenTerminalError(event) {
42974
43399
  return;
42975
43400
  }
42976
43401
 
43402
+ // src/v2/hooks/http-refusal-count.ts
43403
+ class V2HttpRefusalCounts {
43404
+ counts;
43405
+ requests = new WeakMap;
43406
+ associated = new WeakSet;
43407
+ inFlight = new Map;
43408
+ constructor(counts) {
43409
+ this.counts = counts;
43410
+ }
43411
+ capture({ sessionID, model, request }) {
43412
+ const pass = this.counts.latest(sessionID);
43413
+ if (!pass)
43414
+ return;
43415
+ this.release(sessionID);
43416
+ this.associated.add(request);
43417
+ if (request.signal.aborted)
43418
+ return;
43419
+ const attempt = { sessionID, model: `${model.providerID}/${model.id}`, pass };
43420
+ this.requests.set(request, attempt);
43421
+ this.inFlight.set(sessionID, request);
43422
+ const abort = () => this.releaseNonSizeAttempt(request);
43423
+ request.signal.addEventListener("abort", abort, { once: true });
43424
+ attempt.detachAbort = () => request.signal.removeEventListener("abort", abort);
43425
+ try {
43426
+ attempt.body = request.clone();
43427
+ } catch {}
43428
+ }
43429
+ async observe(draft, errorBody) {
43430
+ const attempt = this.detach(draft.request);
43431
+ if (!attempt) {
43432
+ if (draft.response.ok)
43433
+ this.accept(draft.sessionID);
43434
+ return this.associated.has(draft.request);
43435
+ }
43436
+ const model = `${draft.model.providerID}/${draft.model.id}`;
43437
+ if (draft.sessionID !== attempt.sessionID || model !== attempt.model) {
43438
+ cancelBody(attempt);
43439
+ return true;
43440
+ }
43441
+ if (draft.response.ok) {
43442
+ cancelBody(attempt);
43443
+ this.accept(draft.sessionID);
43444
+ return true;
43445
+ }
43446
+ if (!isProviderSizeRefusal({ status: draft.response.status, responseBody: errorBody })) {
43447
+ this.counts.discardPreparation(attempt.sessionID, attempt.pass);
43448
+ cancelBody(attempt);
43449
+ return true;
43450
+ }
43451
+ this.counts.discardDraft(attempt.sessionID, attempt.pass);
43452
+ try {
43453
+ const body = await attempt.body?.json();
43454
+ const tokens = countFullRequest(body);
43455
+ if (tokens !== undefined)
43456
+ this.counts.refusal(attempt.sessionID, attempt.model, attempt.pass, tokens);
43457
+ } catch {} finally {
43458
+ cancelBody(attempt);
43459
+ this.counts.discardPreparation(attempt.sessionID, attempt.pass);
43460
+ }
43461
+ return true;
43462
+ }
43463
+ accept(sessionID) {
43464
+ this.counts.forget(sessionID);
43465
+ this.release(sessionID);
43466
+ }
43467
+ endRun(sessionID) {
43468
+ const request = this.inFlight.get(sessionID);
43469
+ this.counts.endRun(sessionID, () => {
43470
+ if (request)
43471
+ this.discard(request);
43472
+ });
43473
+ }
43474
+ release(sessionID, nonSizeFailure = false) {
43475
+ const request = this.inFlight.get(sessionID);
43476
+ if (!request)
43477
+ return;
43478
+ if (nonSizeFailure)
43479
+ this.releaseNonSizeAttempt(request);
43480
+ else
43481
+ this.discard(request);
43482
+ }
43483
+ dispose() {
43484
+ for (const request of this.inFlight.values())
43485
+ this.discard(request);
43486
+ }
43487
+ detach(request) {
43488
+ const attempt = this.requests.get(request);
43489
+ if (!attempt)
43490
+ return;
43491
+ this.requests.delete(request);
43492
+ if (this.inFlight.get(attempt.sessionID) === request)
43493
+ this.inFlight.delete(attempt.sessionID);
43494
+ attempt.detachAbort?.();
43495
+ return attempt;
43496
+ }
43497
+ discard(request) {
43498
+ const attempt = this.detach(request);
43499
+ if (!attempt)
43500
+ return;
43501
+ cancelBody(attempt);
43502
+ }
43503
+ releaseNonSizeAttempt(request) {
43504
+ const attempt = this.detach(request);
43505
+ if (!attempt)
43506
+ return;
43507
+ this.counts.discardPreparation(attempt.sessionID, attempt.pass);
43508
+ cancelBody(attempt);
43509
+ }
43510
+ }
43511
+ function cancelBody(attempt) {
43512
+ const body = attempt?.body?.body;
43513
+ if (body && !body.locked)
43514
+ body.cancel().catch(() => {});
43515
+ }
43516
+ function readOpenCode2RefusalMessage(message, values) {
43517
+ values.push(message.role);
43518
+ for (const part of message.content) {
43519
+ switch (part.type) {
43520
+ case "text":
43521
+ case "reasoning":
43522
+ values.push(part.type, part.text);
43523
+ break;
43524
+ case "tool-call":
43525
+ values.push("tool-call", part.name, part.input);
43526
+ break;
43527
+ case "tool-result":
43528
+ values.push("tool-result", part.name, part.result);
43529
+ break;
43530
+ case "media": {
43531
+ const media = isRecord(part.media) ? part.media : {};
43532
+ const source = isRecord(media.source) ? media.source : {};
43533
+ values.push("media", source.type, source.mediaType, source.data, source.url);
43534
+ break;
43535
+ }
43536
+ default:
43537
+ pushRefusalFields(part, values);
43538
+ }
43539
+ }
43540
+ }
43541
+ function countFullRequest(body) {
43542
+ if (!body || typeof body !== "object")
43543
+ return;
43544
+ const request = body;
43545
+ if (request.previous_response_id || request.conversation || request.cachedContent)
43546
+ return;
43547
+ const transcript = request.messages ?? request.input ?? request.contents;
43548
+ if (!Array.isArray(transcript))
43549
+ return;
43550
+ if (request.tools !== undefined && !Array.isArray(request.tools))
43551
+ return;
43552
+ let images = 0;
43553
+ const text = JSON.stringify({
43554
+ transcript,
43555
+ system: request.system ?? request.instructions ?? request.systemInstruction,
43556
+ tools: request.tools
43557
+ }, (_key, value) => {
43558
+ if (!isRecord(value))
43559
+ return value;
43560
+ const tokens = httpImageTokens(value);
43561
+ if (tokens === undefined)
43562
+ return value;
43563
+ images += tokens;
43564
+ return null;
43565
+ });
43566
+ return estimateTokens(text) + images;
43567
+ }
43568
+ function httpImageTokens(part) {
43569
+ if (part.type === "image" && isRecord(part.source)) {
43570
+ const source = part.source;
43571
+ if (source.type === "base64" && typeof source.media_type === "string" && typeof source.data === "string")
43572
+ return estimateImageTokensFromBase64(source.media_type, source.data);
43573
+ if (source.type === "url" && typeof source.url === "string")
43574
+ return estimateImageTokensFromDataUrl(source.url);
43575
+ }
43576
+ if (part.type === "image_url" || part.type === "input_image") {
43577
+ const url = isRecord(part.image_url) ? part.image_url.url : part.image_url;
43578
+ if (typeof url === "string")
43579
+ return estimateImageTokensFromDataUrl(url);
43580
+ }
43581
+ const inline = part.inlineData ?? part.inline_data;
43582
+ if (isRecord(inline)) {
43583
+ const mime = inline.mimeType ?? inline.mime_type;
43584
+ if (typeof mime === "string" && mime.startsWith("image/") && typeof inline.data === "string")
43585
+ return estimateImageTokensFromBase64(mime, inline.data);
43586
+ }
43587
+ }
43588
+
42977
43589
  // src/v2/hooks/lkg-system.ts
42978
- import { createHash as createHash19 } from "node:crypto";
43590
+ import { createHash as createHash20 } from "node:crypto";
42979
43591
  function identity2(slot) {
42980
- return createHash19("sha256").update(JSON.stringify({
43592
+ return createHash20("sha256").update(JSON.stringify({
42981
43593
  capturedAt: slot.capturedAt,
42982
43594
  captureSequence: slot.captureSequence,
42983
43595
  rowVersion: slot.rowVersion,
@@ -43106,13 +43718,15 @@ class V2OverflowRecovery {
43106
43718
  if (error === undefined)
43107
43719
  return;
43108
43720
  const prior = this.requests.get(sessionID);
43109
- if (prior?.observed || isProviderRateLimit(error) || !detectOverflow(error).isOverflow)
43721
+ const sizeRefusal = isProviderSizeRefusal(error);
43722
+ if (prior?.observed || isProviderRateLimit(error) || !sizeRefusal && !detectOverflow(error).isOverflow)
43110
43723
  return;
43111
43724
  const messageID = event.data?.assistantMessageID;
43112
43725
  const step = readStep(sessionID, messageID);
43113
43726
  if (!step)
43114
43727
  return;
43115
- if (!messageID && (!step?.error || !detectOverflow(step.error).isOverflow))
43728
+ const durable = !!messageID || !!step.error && detectOverflow(step.error).isOverflow;
43729
+ if (!durable && !isProviderSizeRefusal(step.error))
43116
43730
  return;
43117
43731
  if (!prior && step.model)
43118
43732
  this.begin({
@@ -43128,7 +43742,8 @@ class V2OverflowRecovery {
43128
43742
  sessionID,
43129
43743
  error,
43130
43744
  model: step?.model ?? request.model,
43131
- assistantMessageID: messageID ?? step?.id
43745
+ assistantMessageID: messageID ?? step?.id,
43746
+ durable
43132
43747
  });
43133
43748
  }
43134
43749
  observe(input) {
@@ -43139,13 +43754,22 @@ class V2OverflowRecovery {
43139
43754
  return;
43140
43755
  if (input.status === 429 || isProviderRateLimit(input.error))
43141
43756
  return;
43142
- const detection = detectOverflow(input.error);
43757
+ const reportedError = typeof input.error === "string" && input.status !== undefined ? {
43758
+ status: input.status,
43759
+ responseBody: input.error,
43760
+ data: { responseBody: input.error }
43761
+ } : input.error;
43762
+ const modelKey = `${input.model.providerID}/${input.model.id}`;
43763
+ if (!this.deps.compactionOff && !input.skipMeasured && isProviderSizeRefusal(reportedError))
43764
+ this.deps.onProviderRefused?.(input.sessionID, modelKey, input.assistantMessageID);
43765
+ if (input.durable === false)
43766
+ return;
43767
+ const detection = detectOverflow(reportedError);
43143
43768
  if (!detection.isOverflow)
43144
43769
  return;
43145
43770
  const db = this.deps.database();
43146
43771
  if (!db)
43147
43772
  return;
43148
- const modelKey = `${input.model.providerID}/${input.model.id}`;
43149
43773
  const reportedLimit = resolveOpenCodeOverflowLimit(detection, input.model.providerID, input.model.id, { db, sessionID: input.sessionID });
43150
43774
  if (this.deps.compactionOff) {
43151
43775
  if (reportedLimit)
@@ -43311,8 +43935,10 @@ class V2RevertMessageCleanup {
43311
43935
  const reader = this.openStoreReader();
43312
43936
  try {
43313
43937
  const suffix = reader.revertSuffix(sessionID, cutoff, MAX_STAGED_SUFFIX_ROWS);
43314
- 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 } : {
43315
43940
  cutoff,
43941
+ before,
43316
43942
  unavailable: "stage did not prove a bounded suffix and retained predecessor"
43317
43943
  });
43318
43944
  } finally {
@@ -43322,6 +43948,10 @@ class V2RevertMessageCleanup {
43322
43948
  this.staged.set(sessionID, { cutoff, unavailable: "host store read failed at stage" });
43323
43949
  }
43324
43950
  }
43951
+ stagedPredecessor(sessionID, to) {
43952
+ const staged = this.staged.peek(sessionID);
43953
+ return staged && staged.cutoff === to ? staged.before : undefined;
43954
+ }
43325
43955
  discardStageProof(sessionID) {
43326
43956
  this.staged.delete(sessionID);
43327
43957
  }
@@ -55980,23 +56610,6 @@ function createCtxExpandTools(deps) {
55980
56610
  ctx_expand: createCtxExpandTool(deps)
55981
56611
  };
55982
56612
  }
55983
- // src/tools/ctx-memory/constants.ts
55984
- var CTX_MEMORY_TOOL_NAME = "ctx_memory";
55985
- var CTX_MEMORY_LIST_TOOL_NAME = "ctx_memory_list";
55986
- var CTX_MEMORY_LIST_DESCRIPTION = "Browse active memories, optionally filter by category.";
55987
- var CTX_MEMORY_DESCRIPTION = `Durable facts about this project, shared with every agent working on it and kept for the months this work lasts.
55988
-
55989
- 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.
55990
-
55991
- Actions:
55992
- - write: new memory (content + category).
55993
- - update: rewrite one memory whose fact changed (ids: [one], content; category: the current one to keep, a new one to recategorize).
55994
- - archive: retire wrong or obsolete memories (ids: [one or more], optional reason).
55995
- - merge: collapse duplicates into one (ids: [two or more distinct ids of memories in the same category], content).
55996
- - get: fetch by id (ids: 1–20), readable in every status.
55997
- 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=[].
55998
- Examples: category="CONFIG_VALUES", content="OpenCode source is at ~/Work/OSS/opencode" · category="CONSTRAINTS", content="Dashboard Tauri build needs RGBA PNGs, not grayscale"`;
55999
- var DEFAULT_SEARCH_LIMIT = 10;
56000
56613
  // src/features/magic-context/memory/memory-visibility.ts
56001
56614
  function createMemoryVisibilityPolicy(db, projectIdentity) {
56002
56615
  const identitySet = resolveWorkspaceIdentitySet(db, projectIdentity);
@@ -56210,13 +56823,28 @@ function preflightCurateMutation(args) {
56210
56823
  if (refusals.length === 0)
56211
56824
  return { skip: null, successor };
56212
56825
  let refused = 0;
56826
+ let steer = false;
56827
+ const leaveAlone = [];
56213
56828
  for (const refusal of refusals) {
56214
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
+ }
56215
56835
  }
56216
56836
  const memoryIds = refusals.map((refusal) => refusal.memoryId).join(", ");
56217
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
+ ];
56218
56842
  return {
56219
- 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
+ `),
56220
56848
  successor
56221
56849
  };
56222
56850
  }
@@ -56260,12 +56888,16 @@ var ctxMemoryListArgsShape = {
56260
56888
  category: tool.schema.enum([...V2_MEMORY_CATEGORIES]).optional().describe("Filter listed memories to this category (optional)."),
56261
56889
  limit: tool.schema.number().optional().describe("Max results for list (default 10).")
56262
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
+ };
56263
56895
  var ctxMemoryArgsSchema = tool.schema.object({
56264
56896
  ...ctxMemoryArgsShape,
56265
- superseded_by: tool.schema.number().optional(),
56897
+ superseded_by: ctxMemoryCurateArgsShape.superseded_by,
56266
56898
  limit: tool.schema.number().optional()
56267
56899
  }).passthrough();
56268
- function createCtxMemoryTool(deps) {
56900
+ function createCtxMemoryTool(deps, toolName = CTX_MEMORY_TOOL_NAME) {
56269
56901
  const allowedActions = getAllowedActions(deps);
56270
56902
  return tool({
56271
56903
  description: CTX_MEMORY_DESCRIPTION,
@@ -56314,7 +56946,8 @@ function createCtxMemoryTool(deps) {
56314
56946
  const curatePreflight = toolContext.agent === DREAMER_AGENT ? preflightCurateMutation({
56315
56947
  db: deps.db,
56316
56948
  params: args,
56317
- sessionId: toolContext.sessionID
56949
+ sessionId: toolContext.sessionID,
56950
+ toolName
56318
56951
  }) : { skip: null, successor: null };
56319
56952
  if (curatePreflight.skip)
56320
56953
  return curatePreflight.skip;
@@ -56642,6 +57275,22 @@ function createCtxMemoryListTools(deps) {
56642
57275
  [CTX_MEMORY_LIST_TOOL_NAME]: createCtxMemoryListTool(deps)
56643
57276
  };
56644
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
+ }
56645
57294
  // src/features/magic-context/smart-notes/condition-compiler.ts
56646
57295
  import { existsSync as existsSync9 } from "node:fs";
56647
57296
  import { isAbsolute as isAbsolute2 } from "node:path";
@@ -57422,7 +58071,7 @@ function formatCtxReduceReply(stampedCount, selfStampCount = 0) {
57422
58071
  return parts.join(" ");
57423
58072
  }
57424
58073
  // src/tools/ctx-reduce/tools.ts
57425
- import { createHash as createHash20 } from "node:crypto";
58074
+ import { createHash as createHash21 } from "node:crypto";
57426
58075
 
57427
58076
  // src/features/magic-context/range-parser.ts
57428
58077
  function parseRangeString(input) {
@@ -57485,11 +58134,11 @@ function createCtxReduceTool(deps) {
57485
58134
  const stableId = `oc-${sessionId}-${callId}`;
57486
58135
  if (Buffer.byteLength(stableId) <= 128)
57487
58136
  return stableId;
57488
- return `oc-${createHash20("sha256").update(stableId).digest("hex")}`;
58137
+ return `oc-${createHash21("sha256").update(stableId).digest("hex")}`;
57489
58138
  }
57490
58139
  fallbackCommandSequence += 1;
57491
58140
  const monotonicId = `oc-${sessionId}-${fallbackCommandSequence}`;
57492
- return Buffer.byteLength(monotonicId) <= 128 ? monotonicId : `oc-${createHash20("sha256").update(monotonicId).digest("hex")}`;
58141
+ return Buffer.byteLength(monotonicId) <= 128 ? monotonicId : `oc-${createHash21("sha256").update(monotonicId).digest("hex")}`;
57493
58142
  };
57494
58143
  return tool({
57495
58144
  description: CTX_REDUCE_DESCRIPTION,
@@ -57840,7 +58489,7 @@ async function registerTools(context, db, config, rustToolBackends, isInternalCh
57840
58489
  ...project,
57841
58490
  ...rustToolBackends ? { rustToolBackends } : {}
57842
58491
  }),
57843
- ...createCtxMemoryListTools({
58492
+ ...createDreamerMemoryTools({
57844
58493
  ...project,
57845
58494
  ...rustToolBackends ? { rustToolBackends } : {}
57846
58495
  })
@@ -57858,7 +58507,7 @@ async function registerTools(context, db, config, rustToolBackends, isInternalCh
57858
58507
  const refusal = subagentToolRefusal(db, name, call.sessionID, isInternalChild);
57859
58508
  if (refusal)
57860
58509
  return { content: refusal };
57861
- 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)
57862
58511
  await withAsyncPrivilegedWriter2(db, () => {
57863
58512
  return;
57864
58513
  });
@@ -58327,7 +58976,14 @@ function restoreNativeCheckpointInput(messages, incoming, restored, reader, sess
58327
58976
  const at = messages.indexOf(incoming);
58328
58977
  return [...messages.slice(0, at), ...hidden, ...messages.slice(at + 1)];
58329
58978
  }
58330
- function estimateCheckpointRequest(draft) {
58979
+ function latestDraftAssistantID(messages) {
58980
+ for (let index = messages.length - 1;index >= 0; index--) {
58981
+ const message = messages[index];
58982
+ if (message?.role === "assistant" && message.id)
58983
+ return message.id;
58984
+ }
58985
+ }
58986
+ function checkpointRequestSizingInput(draft) {
58331
58987
  let toolDefinitionTokens = 0;
58332
58988
  for (const tool of Object.values(draft.tools)) {
58333
58989
  const schema = JSON.stringify(tool.input);
@@ -58339,7 +58995,7 @@ function estimateCheckpointRequest(draft) {
58339
58995
  ...draft,
58340
58996
  messages: draft.messages.map((message) => HEAD_IDS.some((id) => message.id === id) ? { ...message, id: undefined } : message)
58341
58997
  };
58342
- return estimateFinalWireInputTokens({
58998
+ return {
58343
58999
  messages: adaptPayload(estimateDraft).messages,
58344
59000
  toolDefinitionTokens,
58345
59001
  systemPromptTokens: estimateTokens(JSON.stringify(draft.system)),
@@ -58347,7 +59003,10 @@ function estimateCheckpointRequest(draft) {
58347
59003
  modelID: draft.model.id,
58348
59004
  agentName: draft.agent,
58349
59005
  sessionId: draft.sessionID
58350
- });
59006
+ };
59007
+ }
59008
+ function estimateCheckpointRequest(draft) {
59009
+ return estimateFinalWireInputTokens(checkpointRequestSizingInput(draft));
58351
59010
  }
58352
59011
  function estimateCheckpointFraming(draft, checkpoint, submitted) {
58353
59012
  const framing = structuredClone(checkpoint);
@@ -58422,7 +59081,7 @@ async function cacheV2SessionDirectory(session, sessionID, directories) {
58422
59081
  sessionLog2(sessionID, "v2 session directory lookup failed; using the launch directory:", error);
58423
59082
  }
58424
59083
  }
58425
- var contextPass = new AsyncLocalStorage2;
59084
+ var contextPass = new AsyncLocalStorage3;
58426
59085
  function noteCheckpointWithoutTail(sessionID, cut, incoming, messageCount) {
58427
59086
  const pass = contextPass.getStore();
58428
59087
  if (pass?.sessionID !== sessionID)
@@ -58536,9 +59195,11 @@ function catalogModels(listed, draftModel) {
58536
59195
  }
58537
59196
  return models;
58538
59197
  }
58539
- function removeDreamerOnlyTools(draft) {
58540
- if (draft.tools)
58541
- 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];
58542
59203
  }
58543
59204
  function applyV2PromptSurfaceTools(draft, runtime, config, smartNotesEnabled = true) {
58544
59205
  if (!draft.tools)
@@ -58807,11 +59468,18 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
58807
59468
  }) : undefined;
58808
59469
  const hiddenChildHook = new HiddenChildHook;
58809
59470
  const usage = new Map;
59471
+ const refusalCounts = new ProviderRefusalCounts;
59472
+ const httpRefusalCounts = new V2HttpRefusalCounts(refusalCounts);
58810
59473
  const overflowRecovery = new V2OverflowRecovery({
58811
59474
  database: () => db ?? null,
58812
59475
  compactionOff,
58813
59476
  isHidden: (sessionID) => hiddenChildHook.owns(sessionID),
58814
59477
  onOverflow: (sessionID) => notifyV2ProviderOverflow(sessionID, openStoreReader),
59478
+ onProviderRefused: (sessionID, modelKey, assistantMessageID) => {
59479
+ const pass = refusalCounts.latestForTerminalFailure(sessionID, assistantMessageID);
59480
+ if (pass)
59481
+ refusalCounts.refusal(sessionID, modelKey, pass);
59482
+ },
58815
59483
  onInputTokens: (sessionID, inputTokens, limit) => usage.set(sessionID, {
58816
59484
  usage: { inputTokens, percentage: limit > 0 ? inputTokens / limit * 100 : 100 },
58817
59485
  hasUsageTokens: true,
@@ -58822,6 +59490,8 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
58822
59490
  await hiddenChildHook.cacheRequest(draft);
58823
59491
  if (draft.kind !== "primary" || hiddenChildHook.owns(draft.sessionID))
58824
59492
  return;
59493
+ if (!compactionOff && draft.model)
59494
+ httpRefusalCounts.capture({ ...draft, model: draft.model });
58825
59495
  const selectedModel = liveModels.get(draft.sessionID);
58826
59496
  if (selectedModel)
58827
59497
  overflowRecovery.begin({
@@ -58834,12 +59504,21 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
58834
59504
  cleanup.tools = () => tools.dispose();
58835
59505
  const generateReplay = new V2GenerateReplay;
58836
59506
  await context.session.hook("http.response", async (draft) => {
58837
- if (!db || draft.kind !== "primary" || draft.response.ok)
59507
+ if (!db || draft.kind !== "primary")
58838
59508
  return;
59509
+ if (draft.response.ok) {
59510
+ httpRefusalCounts.accept(draft.sessionID);
59511
+ return;
59512
+ }
59513
+ if (draft.request && isMeasuredRefusalStatusVeto(draft.response.status))
59514
+ httpRefusalCounts.releaseNonSizeAttempt(draft.request);
59515
+ const error = await draft.response.clone().text();
59516
+ const associated = !compactionOff && draft.request !== undefined && await httpRefusalCounts.observe({ ...draft, request: draft.request }, error);
58839
59517
  overflowRecovery.observe({
58840
59518
  ...draft,
58841
- error: await draft.response.clone().text(),
58842
- status: draft.response.status
59519
+ error,
59520
+ status: draft.response.status,
59521
+ skipMeasured: associated
58843
59522
  });
58844
59523
  });
58845
59524
  await registerHiddenChildAgents(context.agent);
@@ -59364,7 +60043,31 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
59364
60043
  }
59365
60044
  };
59366
60045
  const usageController = new AbortController;
59367
- cleanup.abortUsage = () => usageController.abort();
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
+ };
60067
+ cleanup.abortUsage = () => {
60068
+ usageController.abort();
60069
+ httpRefusalCounts.dispose();
60070
+ };
59368
60071
  const usageDone = (async () => {
59369
60072
  let retry = 0;
59370
60073
  while (!usageController.signal.aborted) {
@@ -59386,6 +60089,10 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
59386
60089
  continue;
59387
60090
  const sessionID = event.data.sessionID;
59388
60091
  observeSyntheticAdmissionEvent(context, event);
60092
+ if (event.type?.startsWith("session.revert.") || event.type === "session.message.removed" || event.type === "session.message.deleted" || event.type === "session.deleted")
60093
+ httpRefusalCounts.accept(sessionID);
60094
+ if ((event.type === "session.step.failed" || event.type === "session.error") && !isProviderSizeRefusal(event.data.error ?? hiddenTerminalError(event)))
60095
+ httpRefusalCounts.release(sessionID, true);
59389
60096
  overflowRecovery.observeTerminal(event, (id, messageID) => {
59390
60097
  const reader = openStoreReader();
59391
60098
  try {
@@ -59398,6 +60105,13 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
59398
60105
  reader.close();
59399
60106
  }
59400
60107
  });
60108
+ if (event.type === "session.step.ended") {
60109
+ const pass = refusalCounts.latestForTerminalFailure(sessionID, event.data.assistantMessageID);
60110
+ if (pass)
60111
+ refusalCounts.discardPreparation(sessionID, pass);
60112
+ }
60113
+ if (event.type === "session.execution.succeeded" || event.type === "session.execution.failed" || event.type === "session.execution.interrupted")
60114
+ httpRefusalCounts.endRun(sessionID);
59401
60115
  if (event.type === "session.revert.staged" && db) {
59402
60116
  revertMessageCleanup.captureStageProof(sessionID, event.data.revert?.messageID);
59403
60117
  }
@@ -59412,6 +60126,7 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
59412
60126
  const indexDb = db;
59413
60127
  withoutSqliteTransformPass2(() => {
59414
60128
  scheduleClearAndReindex(indexDb, sessionID, pagedRead);
60129
+ lowerRetiredInstructionsOnRevert(indexDb, sessionID, event);
59415
60130
  try {
59416
60131
  if (revertMessageCleanup.pruneOnCommit(indexDb, sessionID, event.data?.to, !compactionOff && !rustModeModuleClient)) {
59417
60132
  tagger.cleanup(sessionID);
@@ -59587,8 +60302,10 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
59587
60302
  draft.result = { summary: hiddenSummary, metadata: { keepID: undefined } };
59588
60303
  return;
59589
60304
  }
59590
- if (compactionOff)
60305
+ if (compactionOff) {
60306
+ removeDreamerOnlyTools(draft, [CTX_MEMORY_CURATE_TOOL_NAME]);
59591
60307
  return;
60308
+ }
59592
60309
  if (nativeFoldReplay)
59593
60310
  rememberHostMedia(draft.messages);
59594
60311
  const reader = openStoreReader();
@@ -59598,6 +60315,8 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
59598
60315
  const running = reader.latestRunningCompaction(draft.sessionID);
59599
60316
  const attempt = running && nativeFoldMemory?.admission(draft.sessionID, running.id);
59600
60317
  const manual = running?.data.reason === "manual" && !(attempt?.status === "pending" && attempt.owner_token);
60318
+ if (manual)
60319
+ httpRefusalCounts.accept(draft.sessionID);
59601
60320
  const moduleBaseline = rustModeModuleClient ? servedModuleM0Text(draft.sessionID) : undefined;
59602
60321
  const source = !rustModeModuleClient ? "typescript" : moduleBaseline === null ? "typescript_fallback" : "module";
59603
60322
  if (nativeFoldReplay) {
@@ -59678,11 +60397,13 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
59678
60397
  if (!recorded)
59679
60398
  return messages;
59680
60399
  if (db) {
59681
- foldedInstructionIDs.set(sessionID, new Set([...retiredLiveInstructionIDs(db, sessionID)].filter((id) => recorded({
59682
- type: "system",
59683
- id,
59684
- seq: reader.sequenceForId(sessionID, id) ?? Infinity
59685
- }))));
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);
59686
60407
  }
59687
60408
  const retired = (row) => recorded(row) || isLeftOutInstruction(leftOut, row);
59688
60409
  return messages.filter((message) => {
@@ -59786,7 +60507,7 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
59786
60507
  const pass = contextPass.getStore();
59787
60508
  if (pass)
59788
60509
  pass.legacyCoveredReclaimPermitted = permitted;
59789
- 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);
59790
60511
  },
59791
60512
  compactionOff,
59792
60513
  storeGeneration: "v2",
@@ -59863,7 +60584,7 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
59863
60584
  onRustEngineReconnectRefusal: (refusal) => rustRefusalRecovery?.arm(refusal),
59864
60585
  ...createHostSeams(context, readAllForConversion, pagedRead, liveModels)
59865
60586
  });
59866
- const runManagedContext = async (draft, pass, previousRecovery) => {
60587
+ const runManagedContext = async (draft, pass, previousRecovery, refusalPass) => {
59867
60588
  rememberHostMedia(draft.messages);
59868
60589
  if (hiddenChildHook.apply(draft))
59869
60590
  return "skipped";
@@ -60178,6 +60899,7 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
60178
60899
  let messageTimes;
60179
60900
  let instructionRows = new Map;
60180
60901
  let legacyInstructions;
60902
+ retryRetiredInstructionLowering(db, draft.sessionID);
60181
60903
  const reader = openStoreReader();
60182
60904
  let checkpoint;
60183
60905
  let submitted;
@@ -60188,8 +60910,10 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
60188
60910
  try {
60189
60911
  syntheticIDs = await readSyntheticProvenance(reader, draft.messages);
60190
60912
  const cut = reader.latestCompaction(draft.sessionID);
60191
- if (!rustModeModuleClient)
60913
+ if (!rustModeModuleClient) {
60192
60914
  pass.checkpointSequence = cut?.seq;
60915
+ pass.localCheckpointSequence = cut && isLocalCheckpoint(cut) ? cut.seq : undefined;
60916
+ }
60193
60917
  if (nativeFoldReplay)
60194
60918
  draftSourceIdentity = await nativeFoldReplay.observeSource(draft.sessionID, reader);
60195
60919
  const boundaryRepair = !rustModeModuleClient && db && !compactionOff ? revertMessageCleanup.retireProvenHistory(db, draft.sessionID, reader) ?? checkHistoryBoundary(db, reader, draft.sessionID) : undefined;
@@ -60320,6 +61044,8 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
60320
61044
  nativeFoldReplay.invalidate(draft.sessionID, true);
60321
61045
  }
60322
61046
  }
61047
+ if (refusalPass)
61048
+ refusalPass.observeHistory(snapshotRefusalHistory(draft.messages, readOpenCode2RefusalMessage));
60323
61049
  const mapped = adaptPayload(draft, syntheticIDs, messageTimes, anchorTimesOnly, instructionRows);
60324
61050
  bindSystemDateRequestIdentity(mapped, draft);
60325
61051
  checkpointPassPermissions.delete(draft.sessionID);
@@ -60548,12 +61274,15 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
60548
61274
  const previousRecovery = recoveredInstructions.peek(draft.sessionID);
60549
61275
  recoveredInstructions.delete(draft.sessionID);
60550
61276
  const hiddenChild = hiddenChildHook.owns(draft.sessionID);
61277
+ if (!compactionOff && !hiddenChild && !rustModeModuleClient)
61278
+ httpRefusalCounts.release(draft.sessionID);
61279
+ const refusalPass = compactionOff || hiddenChild || rustModeModuleClient ? undefined : refusalCounts.begin(draft.sessionID, undefined, latestDraftAssistantID(draft.messages));
60551
61280
  const anchor = compactionOff || hiddenChild ? undefined : generateReplayAnchor(draft.messages);
60552
61281
  beginServedRequest(draft.sessionID);
60553
61282
  let returned = false;
60554
61283
  let outcome;
60555
61284
  try {
60556
- outcome = await runManagedContext(draft, pass, previousRecovery);
61285
+ outcome = refusalPass ? await withProviderRefusalPass(draft.sessionID, refusalPass, () => runManagedContext(draft, pass, previousRecovery, refusalPass)) : await runManagedContext(draft, pass, previousRecovery);
60557
61286
  if (!pass.refused && pass.storageNoticeWake && draft.messages.at(-1)?.role === "assistant") {
60558
61287
  await refuseBeforeProvider(context.session, draft.sessionID, "storage-notice-turn", "request ends with the previous reply");
60559
61288
  }
@@ -60614,6 +61343,10 @@ async function setupContext(context, config, nativeRemove, compactionOff, cleanu
60614
61343
  sessionLog2(draft.sessionID, "generate replay capture skipped: compaction-disabled");
60615
61344
  else if (!pass.refused && outcome === "managed" && !hiddenChild && !deletedSessions.has(draft.sessionID))
60616
61345
  generateReplay.capture(draft, anchor);
61346
+ if (refusalPass && !pass.refused && outcome === "managed" && draft.system.some((part) => part.text)) {
61347
+ const saved = { ...draft };
61348
+ refusalPass.freeze(`${saved.model.providerID}/${saved.model.id}`, () => estimateFrozenRequestInputTokens(checkpointRequestSizingInput(saved)));
61349
+ }
60617
61350
  }));
60618
61351
  await context.session.hook("generate", async (draft) => {
60619
61352
  const managed = !compactionOff && !deletedSessions.has(draft.sessionID);