@cortexkit/opencode-magic-context 0.38.0 → 0.38.1

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 (73) hide show
  1. package/dist/{announcement-6c1g4es4.js → announcement-5eg4t64s.js} +6 -6
  2. package/dist/config/schema/magic-context.d.ts +1 -1
  3. package/dist/{conflict-warning-hook-an4fxhwf.js → conflict-warning-hook-f406ggbw.js} +5 -5
  4. package/dist/{derive-budgets-da4yg3tz.js → derive-budgets-xk8cy5e6.js} +5 -5
  5. package/dist/{emscripten-module-ap8t3st0.js → emscripten-module-49k43zfy.js} +1 -1
  6. package/dist/{emscripten-module-682pfzaa.js → emscripten-module-ex4v0x4z.js} +1 -1
  7. package/dist/{emscripten-module-r5h7aghp.js → emscripten-module-jfs3d1dq.js} +1 -1
  8. package/dist/{emscripten-module-bkktz927.js → emscripten-module-ss4g4spn.js} +1 -1
  9. package/dist/features/magic-context/dreamer/retrospective-orphan-sweep.d.ts +17 -6
  10. package/dist/features/magic-context/dreamer/retrospective-orphan-sweep.d.ts.map +1 -1
  11. package/dist/features/magic-context/memory/storage-memory.d.ts.map +1 -1
  12. package/dist/features/magic-context/memory/types.d.ts +16 -0
  13. package/dist/features/magic-context/memory/types.d.ts.map +1 -1
  14. package/dist/features/magic-context/message-index.d.ts +3 -2
  15. package/dist/features/magic-context/message-index.d.ts.map +1 -1
  16. package/dist/features/magic-context/migrations.d.ts.map +1 -1
  17. package/dist/features/magic-context/storage-db.d.ts +1 -1
  18. package/dist/features/magic-context/storage-db.d.ts.map +1 -1
  19. package/dist/features/magic-context/storage-embedding-measurements.d.ts +1 -1
  20. package/dist/features/magic-context/storage-embedding-measurements.d.ts.map +1 -1
  21. package/dist/features/magic-context/storage-meta-session.d.ts.map +1 -1
  22. package/dist/features/magic-context/storage-session-tables.d.ts +18 -0
  23. package/dist/features/magic-context/storage-session-tables.d.ts.map +1 -0
  24. package/dist/features/magic-context/transform-decision-log.d.ts +22 -0
  25. package/dist/features/magic-context/transform-decision-log.d.ts.map +1 -1
  26. package/dist/{ffi-d8pnn3mn.js → ffi-bbm9vkfa.js} +1 -1
  27. package/dist/{ffi-04jzypzk.js → ffi-kb5r0x1j.js} +1 -1
  28. package/dist/{ffi-t8b862vx.js → ffi-qnrt0y78.js} +1 -1
  29. package/dist/{ffi-9wvt2wwz.js → ffi-yx2hpf4p.js} +1 -1
  30. package/dist/hooks/magic-context/empty-task-output.d.ts +16 -0
  31. package/dist/hooks/magic-context/empty-task-output.d.ts.map +1 -0
  32. package/dist/hooks/magic-context/hook-handlers.d.ts.map +1 -1
  33. package/dist/hooks/magic-context/hook.d.ts.map +1 -1
  34. package/dist/hooks/magic-context/inject-compartments.d.ts +6 -0
  35. package/dist/hooks/magic-context/inject-compartments.d.ts.map +1 -1
  36. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts +4 -0
  37. package/dist/hooks/magic-context/transform-postprocess-phase.d.ts.map +1 -1
  38. package/dist/hooks/magic-context/transform.d.ts.map +1 -1
  39. package/dist/{index-cae89eas.js → index-1h9t9xb5.js} +2 -2
  40. package/dist/{index-wckvcay0.js → index-1yh8g550.js} +8 -6
  41. package/dist/index-22mw8km4.js +558 -0
  42. package/dist/{index-cgyfn1s2.js → index-2wchnyk6.js} +4 -2
  43. package/dist/{index-mmvhrqqb.js → index-5znjkjws.js} +6717 -5001
  44. package/dist/{index-4cz5nfxf.js → index-btj2qhmc.js} +5 -5
  45. package/dist/{index-9zhhvr4w.js → index-mg1yx1ph.js} +1 -1
  46. package/dist/{index-ayd60xnw.js → index-rgdqj8nj.js} +3 -3
  47. package/dist/{index-ygcng9t8.js → index-rpgg35ms.js} +50 -50
  48. package/dist/index.d.ts.map +1 -1
  49. package/dist/index.js +177 -88
  50. package/dist/{module-ES6BEMUI-atfbtnbp.js → module-ES6BEMUI-1yjdz59c.js} +4 -4
  51. package/dist/{module-asyncify-2EFITU5U-7xckhw8w.js → module-asyncify-2EFITU5U-fdkx4fhy.js} +1 -1
  52. package/dist/plugin/dream-timer.d.ts +5 -0
  53. package/dist/plugin/dream-timer.d.ts.map +1 -1
  54. package/dist/plugin/hooks/create-session-hooks.d.ts.map +1 -1
  55. package/dist/{prompt-context-jpe2dstn.js → prompt-context-29qkb28f.js} +1 -1
  56. package/dist/{recomp-orchestrator-jsde4ygw.js → recomp-orchestrator-p030kxtc.js} +15 -15
  57. package/dist/{resolve-fallbacks-5n5tvge1.js → resolve-fallbacks-qf0ekmz9.js} +3 -3
  58. package/dist/{rpc-notifications-4d22ybn5.js → rpc-notifications-1ffm755w.js} +6 -6
  59. package/dist/{safe-notification-target-b693f9x3.js → safe-notification-target-tepzc2xa.js} +3 -3
  60. package/dist/{send-session-notification-dxske5zm.js → send-session-notification-6v5b72b4.js} +7 -7
  61. package/dist/shared/harness-provider-map.d.ts +6 -0
  62. package/dist/shared/harness-provider-map.d.ts.map +1 -1
  63. package/dist/{storage-meta-session-mk4gsnke.js → storage-meta-session-2306t3j7.js} +8 -8
  64. package/dist/{task-config-gbp7r23g.js → task-config-at3adc59.js} +6 -6
  65. package/package.json +2 -2
  66. package/src/config/schema/magic-context.test.ts +1 -0
  67. package/src/config/schema/magic-context.ts +3 -3
  68. package/src/shared/harness-provider-map.test.ts +36 -0
  69. package/src/shared/harness-provider-map.ts +8 -0
  70. package/src/tui/index.tsx +1 -1
  71. package/src/tui/tui-compiled-runtime-imports.test.ts +3 -0
  72. package/src/tui-compiled/index.tsx +1 -1
  73. package/dist/index-crke4z5j.js +0 -3022
package/dist/index.js CHANGED
@@ -51,6 +51,7 @@ import {
51
51
  StaleRouteHandleError,
52
52
  SubcClient,
53
53
  SynapseEmbeddingProvider,
54
+ ToolMutationBatch,
54
55
  USER_MEMORY_CANDIDATE_TTL_MS,
55
56
  V2_MEMORY_CATEGORIES,
56
57
  acquireCompartmentLease,
@@ -74,23 +75,28 @@ import {
74
75
  bootQuietRemainingMs,
75
76
  buildChannel1Reminder,
76
77
  buildChannel2Reminder,
78
+ buildFileSourceContent,
79
+ buildInMemoryTailRawMessages,
77
80
  buildPrimaryLanguageDirective,
78
81
  buildSyntheticTodoPart,
79
82
  buildWorkspaceMemorySqlFilter,
80
83
  bumpProjectMemoryEpoch,
81
84
  bumpProjectUserProfileVersion,
85
+ byteSize,
82
86
  captureSlot,
83
87
  casChannel2NudgeClaim,
84
88
  casChannel2NudgeState,
85
89
  checkCompactionMarkerConsistency,
86
90
  checksumAuthoritySeedRows,
87
91
  claimChannel2NudgeState,
92
+ cleanUserText,
88
93
  clearDeferredExecutePendingIfMatches,
89
94
  clearDetectedContextLimit,
90
95
  clearEmergencyDropSample,
91
96
  clearEmergencyRecovery,
92
97
  clearHistorianFailureState,
93
98
  clearHookInitFailure,
99
+ clearIndexedMessages,
94
100
  clearInjectionCache,
95
101
  clearMemoryVerifications,
96
102
  clearNoteNudgeTriggerAndCooldown,
@@ -116,7 +122,9 @@ import {
116
122
  createPrimer,
117
123
  createPromptSurfaceGuidanceEpochCache,
118
124
  createPromptSurfaceRuntime,
125
+ createToolDropTarget,
119
126
  decideChannel1,
127
+ deleteIndexedMessage,
120
128
  deleteTagsByMessageId,
121
129
  deleteUserMemoryCandidates,
122
130
  deriveTagLoadFloor,
@@ -141,11 +149,17 @@ import {
141
149
  escalationBands,
142
150
  estimateEmergencyDropReclaimTokens,
143
151
  estimateImageTokensFromDataUrl,
152
+ estimateTokens,
153
+ estimateTrueRawMessageTokens,
144
154
  evaluateChannel2,
145
155
  expandWorkspaceIdentitySetWithAliases,
146
156
  exports_external,
157
+ extractInMemoryMessageViews,
147
158
  extractLatestAssistantText,
148
159
  extractM0Block,
160
+ extractTexts,
161
+ extractToolCallObservation,
162
+ extractToolCallSummaries,
149
163
  formatDate,
150
164
  getActiveCompartmentRun,
151
165
  getActivePrimers,
@@ -169,9 +183,11 @@ import {
169
183
  getEmergencyInputSample,
170
184
  getEmergencyRecoveryArmedAt,
171
185
  getHistorianFailureState,
186
+ getIndexedMessageCorpusSize,
172
187
  getLastCompartmentEndMessage,
173
188
  getLastCompartmentEndMessageId,
174
189
  getLastHookInitFailure,
190
+ getLastIndexedOrdinal,
175
191
  getLastNudgeLevel,
176
192
  getLastNudgeUndropped,
177
193
  getLatestIndexedCommitTimeMs,
@@ -190,6 +206,8 @@ import {
190
206
  getMemoryMutationsForRenderByProjects,
191
207
  getMemoryVerifications,
192
208
  getMergedReasoningStrippedIds,
209
+ getMessageIndexReconciliationStartOrdinal,
210
+ getMessageIndexSourceIdentity,
193
211
  getMigrationOnOpenRefusal,
194
212
  getMirrorCursor,
195
213
  getModuleNoteEvaluationBridge,
@@ -218,6 +236,7 @@ import {
218
236
  getProjectEmbeddings,
219
237
  getProjectState,
220
238
  getRawHistoryEligibility,
239
+ getRawSessionStoredMessageCount,
221
240
  getReadySmartNotes,
222
241
  getSchemaFenceRejection,
223
242
  getSessionNotes,
@@ -240,11 +259,14 @@ import {
240
259
  getVisibleMemoryIds,
241
260
  getWrapupInProgressState,
242
261
  hasLengthCappedOutput,
262
+ hasMeaningfulUserText,
243
263
  hasMemoryClassifiedAtColumn,
244
264
  hasMemoryShareableColumn,
245
265
  hasMuralCueColumns,
246
266
  hasRunnableCompartmentWindow,
247
267
  incrementalLkgContentDigests,
268
+ indexMessagesAfterOrdinal,
269
+ indexSingleMessage,
248
270
  injectM0M1,
249
271
  injectTemporalMarkers,
250
272
  insertMemory,
@@ -254,15 +276,25 @@ import {
254
276
  insertUserMemoryCandidates,
255
277
  invalidateMemory,
256
278
  invalidateProject,
279
+ invalidateTrueRawTokenCache,
257
280
  isConsumerReconnectTransient,
258
281
  isDatabasePersisted,
282
+ isEditTool,
259
283
  isEmbeddingEnabled,
260
284
  isEmergencyRecoveryArmed,
261
285
  isFailClosedBlockingError,
286
+ isFilePart,
262
287
  isLinkedGitWorktree,
288
+ isMessageIndexReconciledThrough,
289
+ isMessageIndexSourceCurrent,
263
290
  isPidAlive,
264
291
  isProviderOverflowReconfirmed,
292
+ isRawCompactionSummaryInfo,
293
+ isRecord,
265
294
  isSyntheticTodoPart,
295
+ isTextPart,
296
+ isThinkingPart,
297
+ isToolPartWithOutput,
266
298
  lkgContentDigest,
267
299
  loadCompartmentChunkEmbeddingsForSearch,
268
300
  loadPersistedUsage,
@@ -283,6 +315,7 @@ import {
283
315
  nextOccurrence,
284
316
  normalizeSDKResponse,
285
317
  normalizeStoredProjectPath,
318
+ normalizeText,
286
319
  normalizeTodoStateJson,
287
320
  normalizeVerificationFiles,
288
321
  noteEntry,
@@ -292,13 +325,18 @@ import {
292
325
  parkGitSweepNonIndexable,
293
326
  parseCron,
294
327
  parseRpcPortFile,
328
+ partHasCompletedResult,
295
329
  peekDeferredExecutePending,
296
330
  peekNoteNudgeText,
297
331
  peekProjectEmbeddings,
298
332
  pickNearestPriorOwner,
299
333
  planEmergencyDrop,
334
+ preloadTokenizer,
300
335
  prepareAuthority,
301
336
  prepareCompartmentInjection,
337
+ prependTag,
338
+ primeInMemoryTailRawMessageCache,
339
+ primeTailRawMessageCache,
302
340
  primerOccurrenceKey,
303
341
  primerOccurrenceUtcDay,
304
342
  promptSurfaceConfigIdentity,
@@ -314,6 +352,12 @@ import {
314
352
  readGitFileChangeTimesSince,
315
353
  readGitHead,
316
354
  readNewMemoriesForM1Union,
355
+ readRawSessionMessageById,
356
+ readRawSessionMessageOrdinalById,
357
+ readRawSessionMessageOrdinalPage,
358
+ readRawSessionMessagePartsById,
359
+ readRawSessionMessages,
360
+ readSessionChunk,
317
361
  reconcileAuthorityProject,
318
362
  recordChildInvocation,
319
363
  recordDetectedContextLimit,
@@ -394,6 +438,7 @@ import {
394
438
  setPersistedReasoningWatermark,
395
439
  setPersistedTodoPermissionDenied,
396
440
  setPersistedTodoSyntheticAnchor,
441
+ setRawMessageProvider,
397
442
  setRecompStarting,
398
443
  setRecompTerminal,
399
444
  setSessionWorkMetrics,
@@ -405,11 +450,15 @@ import {
405
450
  startCompartmentAgent,
406
451
  storedPathBelongsToIdentity,
407
452
  storedPathBelongsToWorkspace,
453
+ stripPersistedAssistantText,
454
+ stripTagPrefix,
408
455
  supersededMemory,
456
+ sweepOrphanedOpenCodeMessageIndexes,
409
457
  sweepStaleEmbeddingIdentitiesForProject,
410
458
  tagTokenCountIsNull,
411
459
  tailHygieneStructuralSignature,
412
460
  takeDubiousOwnershipProjectIdentityWarning,
461
+ textMentionsRecentCommit,
413
462
  toolOutputTokens,
414
463
  trimMemoriesToBudgetV2,
415
464
  updateCavemanDepth,
@@ -426,8 +475,9 @@ import {
426
475
  updateWrapupInProgress,
427
476
  upsertCommits,
428
477
  verificationFileExists,
429
- withContentLanguageDirective
430
- } from "./index-mmvhrqqb.js";
478
+ withContentLanguageDirective,
479
+ withRawSessionMessageCache
480
+ } from "./index-5znjkjws.js";
431
481
  import {
432
482
  deriveHistorianChunkTokens,
433
483
  deriveTriggerBudget,
@@ -442,7 +492,7 @@ import {
442
492
  setStoragePrivatePermissionEnforcement,
443
493
  setWindowOverlayPath,
444
494
  shouldEnforcePrivateStoragePermissions
445
- } from "./index-9zhhvr4w.js";
495
+ } from "./index-mg1yx1ph.js";
446
496
  import {
447
497
  modelBodyField,
448
498
  resolveFallbackChain
@@ -454,69 +504,19 @@ import {
454
504
  getErrorMessage,
455
505
  sendIgnoredMessage,
456
506
  sendUserPrompt
457
- } from "./index-4cz5nfxf.js";
507
+ } from "./index-btj2qhmc.js";
458
508
  import {
459
- ToolMutationBatch,
460
509
  advanceToolReclaimWatermark,
461
- buildFileSourceContent,
462
- buildInMemoryTailRawMessages,
463
- byteSize,
464
- cleanUserText,
465
- clearIndexedMessages,
466
510
  clearSession,
467
- createToolDropTarget,
468
- deleteIndexedMessage,
469
- estimateTokens,
470
- estimateTrueRawMessageTokens,
471
- extractInMemoryMessageViews,
472
- extractTexts,
473
- extractToolCallObservation,
474
- extractToolCallSummaries,
475
- getIndexedMessageCorpusSize,
476
- getLastIndexedOrdinal,
477
- getMessageIndexReconciliationStartOrdinal,
478
- getMessageIndexSourceIdentity,
479
511
  getOrCreateSessionMeta,
480
- getRawSessionStoredMessageCount,
481
- hasMeaningfulUserText,
482
- indexMessagesAfterOrdinal,
483
- indexSingleMessage,
484
- invalidateTrueRawTokenCache,
485
- isEditTool,
486
- isFilePart,
487
- isMessageIndexReconciledThrough,
488
- isMessageIndexSourceCurrent,
489
- isRawCompactionSummaryInfo,
490
- isRecord,
491
- isTextPart,
492
- isThinkingPart,
493
- isToolPartWithOutput,
494
512
  markSessionCleanupPending,
495
- normalizeText,
496
- partHasCompletedResult,
497
- preloadTokenizer,
498
- prependTag,
499
- primeInMemoryTailRawMessageCache,
500
- primeTailRawMessageCache,
501
- readRawSessionMessageById,
502
- readRawSessionMessageOrdinalById,
503
- readRawSessionMessageOrdinalPage,
504
- readRawSessionMessagePartsById,
505
- readRawSessionMessages,
506
- readSessionChunk,
507
513
  retryPendingSessionCleanups,
508
- setRawMessageProvider,
509
- stripPersistedAssistantText,
510
- stripTagPrefix,
511
- sweepOrphanedOpenCodeMessageIndexes,
512
- textMentionsRecentCommit,
513
- updateSessionMeta,
514
- withRawSessionMessageCache
515
- } from "./index-crke4z5j.js";
514
+ updateSessionMeta
515
+ } from "./index-22mw8km4.js";
516
516
  import {
517
517
  modelRefLookupOrder,
518
518
  piModelRefToCanonical
519
- } from "./index-cgyfn1s2.js";
519
+ } from "./index-2wchnyk6.js";
520
520
  import {
521
521
  Database,
522
522
  closeQuietly,
@@ -531,7 +531,7 @@ import {
531
531
  detectConflicts,
532
532
  resolveCompactionForBoot,
533
533
  sendConflictWarning
534
- } from "./index-cae89eas.js";
534
+ } from "./index-1h9t9xb5.js";
535
535
  import {
536
536
  detectConfigFile,
537
537
  isPrototypePollutionKey,
@@ -573,10 +573,10 @@ import {
573
573
  __commonJS,
574
574
  __require,
575
575
  __toESM
576
- } from "./index-wckvcay0.js";
576
+ } from "./index-1yh8g550.js";
577
577
 
578
578
  // ../../node_modules/.bun/esprima@4.0.1/node_modules/esprima/dist/esprima.js
579
- var require_esprima = __commonJS((exports, module) => {
579
+ var require_esprima = __commonJS(function(exports, module) {
580
580
  (function webpackUniversalModuleDefinition(root, factory) {
581
581
  if (typeof exports === "object" && typeof module === "object")
582
582
  module.exports = factory();
@@ -6716,7 +6716,7 @@ var require_esprima = __commonJS((exports, module) => {
6716
6716
  });
6717
6717
 
6718
6718
  // ../../node_modules/.bun/array-timsort@1.0.3/node_modules/array-timsort/src/index.js
6719
- var require_src = __commonJS((exports, module) => {
6719
+ var require_src = __commonJS(function(exports, module) {
6720
6720
  var DEFAULT_MIN_MERGE = 32;
6721
6721
  var DEFAULT_MIN_GALLOPING = 7;
6722
6722
  var DEFAULT_TMP_STORAGE_LENGTH = 256;
@@ -7359,7 +7359,7 @@ var require_src = __commonJS((exports, module) => {
7359
7359
  });
7360
7360
 
7361
7361
  // ../../node_modules/.bun/comment-json@5.0.0/node_modules/comment-json/src/common.js
7362
- var require_common = __commonJS((exports, module) => {
7362
+ var require_common = __commonJS(function(exports, module) {
7363
7363
  var PREFIX_BEFORE = "before";
7364
7364
  var PREFIX_AFTER_PROP = "after-prop";
7365
7365
  var PREFIX_AFTER_COLON = "after-colon";
@@ -7645,7 +7645,7 @@ var require_common = __commonJS((exports, module) => {
7645
7645
  });
7646
7646
 
7647
7647
  // ../../node_modules/.bun/comment-json@5.0.0/node_modules/comment-json/src/array.js
7648
- var require_array = __commonJS((exports, module) => {
7648
+ var require_array = __commonJS(function(exports, module) {
7649
7649
  var { sort } = require_src();
7650
7650
  var {
7651
7651
  PROP_SYMBOL_PREFIXES,
@@ -7803,7 +7803,7 @@ var require_array = __commonJS((exports, module) => {
7803
7803
  });
7804
7804
 
7805
7805
  // ../../node_modules/.bun/comment-json@5.0.0/node_modules/comment-json/src/parse.js
7806
- var require_parse = __commonJS((exports, module) => {
7806
+ var require_parse = __commonJS(function(exports, module) {
7807
7807
  var esprima = require_esprima();
7808
7808
  var {
7809
7809
  CommentArray
@@ -8169,7 +8169,7 @@ var require_parse = __commonJS((exports, module) => {
8169
8169
  });
8170
8170
 
8171
8171
  // ../../node_modules/.bun/comment-json@5.0.0/node_modules/comment-json/src/stringify.js
8172
- var require_stringify = __commonJS((exports, module) => {
8172
+ var require_stringify = __commonJS(function(exports, module) {
8173
8173
  var {
8174
8174
  PREFIX_BEFORE_ALL,
8175
8175
  PREFIX_BEFORE,
@@ -8377,7 +8377,7 @@ var require_stringify = __commonJS((exports, module) => {
8377
8377
  });
8378
8378
 
8379
8379
  // ../../node_modules/.bun/comment-json@5.0.0/node_modules/comment-json/src/index.js
8380
- var require_src2 = __commonJS((exports, module) => {
8380
+ var require_src2 = __commonJS(function(exports, module) {
8381
8381
  var { parse, tokenize } = require_parse();
8382
8382
  var stringify = require_stringify();
8383
8383
  var { CommentArray } = require_array();
@@ -12253,6 +12253,7 @@ function releaseLease(db, holderId, leaseKey = DREAMING_LEASE_KEY) {
12253
12253
  }
12254
12254
 
12255
12255
  // src/features/magic-context/dreamer/retrospective-orphan-sweep.ts
12256
+ var HISTORIAN_CHILD_TITLE = "magic-context-compartment";
12256
12257
  var RETROSPECTIVE_CHILD_TITLE = "magic-context-dream-retrospective";
12257
12258
  var USER_MEMORIES_CHILD_TITLE = "magic-context-dream-user-memories";
12258
12259
  var CURATE_CHILD_TITLE = "magic-context-dream-curate";
@@ -12278,16 +12279,34 @@ var PRIVACY_SENSITIVE_CHILD_TITLE_MATCHES = {
12278
12279
  ],
12279
12280
  prefixes: [SMART_NOTE_COMPILE_CHILD_TITLE_PREFIX, SMART_NOTE_CONFIRM_CHILD_TITLE_PREFIX]
12280
12281
  };
12282
+ var HISTORIAN_CHILD_TITLE_MATCHES = {
12283
+ exact: [HISTORIAN_CHILD_TITLE],
12284
+ prefixes: []
12285
+ };
12286
+ var INTERNAL_CHILD_TITLE_MATCHES = {
12287
+ exact: [HISTORIAN_CHILD_TITLE, ...PRIVACY_SENSITIVE_CHILD_TITLE_MATCHES.exact],
12288
+ prefixes: PRIVACY_SENSITIVE_CHILD_TITLE_MATCHES.prefixes
12289
+ };
12281
12290
  function retrospectiveOrphanStaleMs(taskTimeoutMinutes) {
12282
12291
  const timeoutCandidates = Array.isArray(taskTimeoutMinutes) ? taskTimeoutMinutes : [taskTimeoutMinutes];
12283
12292
  const maxTimeoutMinutes = Math.max(...timeoutCandidates.map((minutes) => Math.max(1, minutes ?? 20)), 20);
12284
12293
  const timeoutMs = maxTimeoutMinutes * 60000;
12285
12294
  return Math.max(60 * 60000, timeoutMs * 3);
12286
12295
  }
12296
+ var HISTORIAN_OUTER_ATTEMPTS = 3;
12297
+ var HISTORIAN_MODEL_SUGGESTION_ATTEMPTS = 2;
12298
+ var HISTORIAN_MAX_RETRY_BACKOFF_MS = 11000;
12299
+ var HISTORIAN_DETACHED_WRITER_GRACE_MS = 15 * 60000;
12300
+ function historianOrphanStaleMs(timeoutMs, fallbackModelCount) {
12301
+ const timeout = Math.max(60000, timeoutMs);
12302
+ const fallbackCount = Math.max(0, Math.floor(fallbackModelCount));
12303
+ const fullAttemptBudget = timeout * HISTORIAN_OUTER_ATTEMPTS * HISTORIAN_MODEL_SUGGESTION_ATTEMPTS * (fallbackCount + 1);
12304
+ return Math.max(60 * 60000, fullAttemptBudget + HISTORIAN_MAX_RETRY_BACKOFF_MS + HISTORIAN_DETACHED_WRITER_GRACE_MS);
12305
+ }
12287
12306
  async function sweepOrphanedRetrospectiveChildren(args) {
12288
12307
  const { opencodeDb, client, sessionDirectory, staleMs } = args;
12289
- const titleMatches = args.titleMatches ?? PRIVACY_SENSITIVE_CHILD_TITLE_MATCHES;
12290
- if (!opencodeDb)
12308
+ const titleMatches = args.titleMatches ?? INTERNAL_CHILD_TITLE_MATCHES;
12309
+ if (!opencodeDb || args.keepSubagents === true)
12291
12310
  return 0;
12292
12311
  const now = args.now ?? Date.now();
12293
12312
  const cutoff = now - staleMs;
@@ -12310,7 +12329,7 @@ async function sweepOrphanedRetrospectiveChildren(args) {
12310
12329
  ORDER BY time_created ASC
12311
12330
  LIMIT 200`).all(...titleParams, sessionDirectory, cutoff);
12312
12331
  } catch (error) {
12313
- log(`[dreamer] retrospective orphan sweep: read skipped (${String(error)})`);
12332
+ log(`[magic-context] internal child orphan sweep: read skipped (${String(error)})`);
12314
12333
  return 0;
12315
12334
  }
12316
12335
  if (rows.length === 0)
@@ -12325,7 +12344,7 @@ async function sweepOrphanedRetrospectiveChildren(args) {
12325
12344
  }
12326
12345
  }
12327
12346
  if (deleted > 0) {
12328
- log(`[dreamer] swept ${deleted} crash-orphaned privacy-sensitive child session(s)`);
12347
+ log(`[magic-context] swept ${deleted} stale internal child session(s)`);
12329
12348
  }
12330
12349
  return deleted;
12331
12350
  }
@@ -14820,8 +14839,8 @@ var asyncModulePromise = null;
14820
14839
  function getAsyncModule() {
14821
14840
  asyncModulePromise ??= (async () => {
14822
14841
  const [{ default: singlefileAsyncifyVariant }, { newQuickJSAsyncWASMModuleFromVariant }] = await Promise.all([
14823
- import("./index-ayd60xnw.js").then((m)=>__toESM(m.default,1)),
14824
- import("./index-ygcng9t8.js")
14842
+ import("./index-rgdqj8nj.js").then((m)=>__toESM(m.default,1)),
14843
+ import("./index-rpgg35ms.js")
14825
14844
  ]);
14826
14845
  return newQuickJSAsyncWASMModuleFromVariant(singlefileAsyncifyVariant);
14827
14846
  })();
@@ -19447,7 +19466,7 @@ function scheduleInitialProjectRun(reg, db) {
19447
19466
  startupTimers.set(reg.directory, timer);
19448
19467
  }
19449
19468
  async function runProjectMaintenance(reg, origin, db) {
19450
- const projectMaintenanceEnabled = Boolean(reg.dreamerConfig && reg.dreamerConfig.disable !== true) || reg.memoryEnabled === true || reg.gitCommitIndexing?.enabled === true;
19469
+ const projectMaintenanceEnabled = Boolean(reg.dreamerConfig && reg.dreamerConfig.disable !== true) || reg.memoryEnabled === true || reg.gitCommitIndexing?.enabled === true || reg.historianChildSweep !== undefined;
19451
19470
  if (!projectMaintenanceEnabled)
19452
19471
  return;
19453
19472
  await reg.ensureRegistered(reg.directory, db);
@@ -19484,6 +19503,7 @@ async function sweepProject(reg, origin, db, gitCommitEnabled) {
19484
19503
  if (gcDeleted > 0) {
19485
19504
  log(`[magic-context] GC'd ${gcDeleted} stale embedding row(s) for ${reg.projectIdentity} ` + `(memory=${gc.memoryRowsDeleted} commit=${gc.commitRowsDeleted} chunk=${gc.chunkRowsDeleted})`);
19486
19505
  }
19506
+ await sweepOrphanedHistorianChildren(reg);
19487
19507
  const dreamerConfig = reg.dreamerConfig;
19488
19508
  const dreamingEnabled = Boolean(dreamerConfig && dreamerConfig.disable !== true);
19489
19509
  if (commitIndexingEnabled && reg.gitCommitIndexing) {
@@ -19547,6 +19567,27 @@ async function sweepProject(reg, origin, db, gitCommitEnabled) {
19547
19567
  log(`[dreamer] timer-triggered task scheduling failed for ${reg.projectIdentity}:`, error);
19548
19568
  }
19549
19569
  }
19570
+ async function sweepOrphanedHistorianChildren(reg) {
19571
+ const config = reg.historianChildSweep;
19572
+ if (!config || config.keepSubagents)
19573
+ return;
19574
+ const ocDb = openOpenCodeDb();
19575
+ if (!ocDb)
19576
+ return;
19577
+ try {
19578
+ await sweepOrphanedRetrospectiveChildren({
19579
+ opencodeDb: ocDb,
19580
+ client: reg.client,
19581
+ sessionDirectory: reg.directory,
19582
+ staleMs: historianOrphanStaleMs(config.timeoutMs, config.fallbackModelCount),
19583
+ titleMatches: HISTORIAN_CHILD_TITLE_MATCHES
19584
+ });
19585
+ } catch (error) {
19586
+ log(`[magic-context] historian child orphan sweep failed for ${reg.projectIdentity}:`, error);
19587
+ } finally {
19588
+ closeQuietly(ocDb);
19589
+ }
19590
+ }
19550
19591
  async function runCompiledSmartNoteSweep(reg, db) {
19551
19592
  const leaseKey = leaseKeyFor("evaluate-smart-notes", reg.projectIdentity);
19552
19593
  const holderId = crypto.randomUUID();
@@ -21068,7 +21109,7 @@ function executeStatus(db, sessionId, protectedTags, executeThresholdPercentageC
21068
21109
  "### Cache TTL",
21069
21110
  `- Configured: ${meta.cacheTtl}`,
21070
21111
  `- Last response: ${meta.lastResponseTime > 0 ? `${Math.round(elapsed / 1000)}s ago` : "never"}`,
21071
- `- Remaining: ${cacheExpired ? "expired" : ttlMs === Number.POSITIVE_INFINITY ? "never expires (always-warm lane)" : `${Math.round(remainingMs / 1000)}s`}`,
21112
+ `- Remaining: ${cacheExpired ? "expired" : ttlMs === Number.POSITIVE_INFINITY ? "never (MC never assumes expiry — external cache-keep)" : `${Math.round(remainingMs / 1000)}s`}`,
21072
21113
  `- Queue will auto-execute: ${cacheExpired ? "yes (cache expired)" : ttlMs === Number.POSITIVE_INFINITY ? `when context >= ${executeThresholdPercentage}%` : `when TTL expires or context >= ${executeThresholdPercentage}%`}`,
21073
21114
  "",
21074
21115
  "### Execute Threshold",
@@ -22215,6 +22256,10 @@ function writeRustTransformDecision(args) {
22215
22256
  decision: mapped.decision,
22216
22257
  materialized: mapped.materialized,
22217
22258
  materializeReason: args.materializeReason,
22259
+ systemHashPrev: null,
22260
+ systemHashNew: null,
22261
+ m0ModelKeyPrev: null,
22262
+ m0ModelKeyNew: null,
22218
22263
  emergency: false,
22219
22264
  droppedTokens: 0,
22220
22265
  droppedCount: 0,
@@ -22306,10 +22351,16 @@ function writeTransformDecisionRow(dbPath, row) {
22306
22351
  function writeTransformDecisionRowOnDatabase(db, row, configureBusyTimeout) {
22307
22352
  if (configureBusyTimeout)
22308
22353
  db.exec("PRAGMA busy_timeout=0");
22354
+ const systemHashPrev = row.materialized ? row.systemHashPrev : null;
22355
+ const systemHashNew = row.materialized ? row.systemHashNew : null;
22356
+ const m0ModelKeyPrev = row.materialized ? row.m0ModelKeyPrev : null;
22357
+ const m0ModelKeyNew = row.materialized ? row.m0ModelKeyNew : null;
22309
22358
  db.prepare(`INSERT OR REPLACE INTO transform_decisions (
22310
22359
  session_id, harness, message_id, ts_ms, decision, materialized,
22311
- materialize_reason, emergency, dropped_tokens, dropped_count, input_tokens
22312
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(row.sessionId, row.harness, row.messageId, row.tsMs, row.decision, row.materialized ? 1 : 0, row.materializeReason, row.emergency ? 1 : 0, Math.max(0, Math.floor(row.droppedTokens)), Math.max(0, Math.floor(row.droppedCount)), Math.max(0, Math.floor(row.inputTokens)));
22360
+ materialize_reason, system_hash_prev, system_hash_new,
22361
+ m0_model_key_prev, m0_model_key_new, emergency, dropped_tokens,
22362
+ dropped_count, input_tokens
22363
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(row.sessionId, row.harness, row.messageId, row.tsMs, row.decision, row.materialized ? 1 : 0, row.materializeReason, systemHashPrev, systemHashNew, m0ModelKeyPrev, m0ModelKeyNew, row.emergency ? 1 : 0, Math.max(0, Math.floor(row.droppedTokens)), Math.max(0, Math.floor(row.droppedCount)), Math.max(0, Math.floor(row.inputTokens)));
22313
22364
  db.prepare(`DELETE FROM transform_decisions
22314
22365
  WHERE session_id = ? AND harness = ?
22315
22366
  AND rowid NOT IN (
@@ -29229,6 +29280,7 @@ async function runPostTransformPhase(args) {
29229
29280
  let m0RematerializedThisPass = false;
29230
29281
  const m0CoverageBeforeFold = args.sessionMeta.cachedM0Bytes === null ? -1 : args.sessionMeta.cachedM0MaxCompartmentSeq;
29231
29282
  let m0MaterializeReason = null;
29283
+ let m0ComparisonDecision = null;
29232
29284
  if (foldDueDecision.value && args.m0M1) {
29233
29285
  try {
29234
29286
  const foldResult = injectM0M1({
@@ -29249,6 +29301,9 @@ async function runPostTransformPhase(args) {
29249
29301
  foldExecutedThisPass = foldExecutesThisPass(foldDueDecision.value, foldResult.m0RematerializedThisPass);
29250
29302
  m0RematerializedThisPass = foldResult.m0RematerializedThisPass;
29251
29303
  m0MaterializeReason = foldResult.decision.reason;
29304
+ if (foldResult.m0RematerializedThisPass) {
29305
+ m0ComparisonDecision = foldResult.decision;
29306
+ }
29252
29307
  try {
29253
29308
  rearmChannel2AfterCoverageAdvancingHardFold({
29254
29309
  db: args.db,
@@ -29544,6 +29599,9 @@ async function runPostTransformPhase(args) {
29544
29599
  prependedMessageCount += result.prependedMessageCount;
29545
29600
  m0RematerializedThisPass ||= result.m0RematerializedThisPass;
29546
29601
  m0MaterializeReason = result.decision.reason ?? m0MaterializeReason;
29602
+ if (result.m0RematerializedThisPass) {
29603
+ m0ComparisonDecision = result.decision;
29604
+ }
29547
29605
  sessionLog(args.sessionId, `transform: injected m[0]/m[1] (rematerialized=${result.m0RematerializedThisPass}, reason=${result.decision.reason ?? "cache_hit"})`);
29548
29606
  }
29549
29607
  } catch (error) {
@@ -29939,6 +29997,10 @@ async function runPostTransformPhase(args) {
29939
29997
  materialized,
29940
29998
  historianFoldMaterializedThisPass: historyWasConsumedThisPass,
29941
29999
  materializeReason,
30000
+ systemHashPrev: m0RematerializedThisPass ? m0ComparisonDecision?.systemHashPrev ?? null : null,
30001
+ systemHashNew: m0RematerializedThisPass ? m0ComparisonDecision?.systemHashNew ?? null : null,
30002
+ m0ModelKeyPrev: m0RematerializedThisPass ? m0ComparisonDecision?.m0ModelKeyPrev ?? null : null,
30003
+ m0ModelKeyNew: m0RematerializedThisPass ? m0ComparisonDecision?.m0ModelKeyNew ?? null : null,
29942
30004
  droppedTokens,
29943
30005
  emergencyReclaimedTokens,
29944
30006
  droppedCount,
@@ -32877,6 +32939,10 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
32877
32939
  decision: schedulerDecision,
32878
32940
  materialized: postTransformResult.materialized,
32879
32941
  materializeReason: normalizeMaterializeReason("opencode", postTransformResult.materializeReason, postTransformResult.materialized),
32942
+ systemHashPrev: postTransformResult.systemHashPrev,
32943
+ systemHashNew: postTransformResult.systemHashNew,
32944
+ m0ModelKeyPrev: postTransformResult.m0ModelKeyPrev,
32945
+ m0ModelKeyNew: postTransformResult.m0ModelKeyNew,
32880
32946
  emergency: postTransformResult.emergency,
32881
32947
  droppedTokens: postTransformResult.droppedTokens,
32882
32948
  droppedCount: postTransformResult.droppedCount,
@@ -33810,6 +33876,23 @@ function clearSidebarSnapshotCache(sessionId) {
33810
33876
  cache.delete(sessionId);
33811
33877
  }
33812
33878
 
33879
+ // src/hooks/magic-context/empty-task-output.ts
33880
+ var EMPTY_TASK_OUTPUT_SENTINEL = "<magic-context-empty-task-output>";
33881
+ var EMPTY_COMPLETED_TASK_RESULT = /^<task\b[^>]*\bstate="completed"[^>]*>[\s\S]*<task_result>\s*<\/task_result>\s*<\/task>\s*$/;
33882
+ function annotateEmptyTaskOutput(tool, output) {
33883
+ if (tool !== "task" || !isRecord(output))
33884
+ return;
33885
+ if (typeof output.output !== "string")
33886
+ return;
33887
+ if (output.output.includes(EMPTY_TASK_OUTPUT_SENTINEL))
33888
+ return;
33889
+ if (!EMPTY_COMPLETED_TASK_RESULT.test(output.output))
33890
+ return;
33891
+ Reflect.set(output, "output", `${output.output}
33892
+ ${EMPTY_TASK_OUTPUT_SENTINEL}
33893
+ The subagent completed without a final text response. Context-fill truncation may have omitted its final output, or its provider may have emitted reasoning only; inspect the child session and retry with a low-reasoning model or variant.`);
33894
+ }
33895
+
33813
33896
  // src/hooks/magic-context/hook-handlers.ts
33814
33897
  function getLiveNotificationParams(sessionId, liveModelBySession, variantBySession, agentBySession, toastDurationMs) {
33815
33898
  const model = liveModelBySession.get(sessionId);
@@ -33971,6 +34054,7 @@ function createToolExecuteAfterHook(args) {
33971
34054
  return;
33972
34055
  }
33973
34056
  await flushIgnoredMessages(typedInput.sessionID);
34057
+ annotateEmptyTaskOutput(typedInput.tool, output);
33974
34058
  if (typedInput.tool === "ctx_reduce") {
33975
34059
  const state = args.channel1StateBySession.get(typedInput.sessionID);
33976
34060
  if (state) {
@@ -36287,9 +36371,9 @@ function registerRpcHandlers(rpcServer, args) {
36287
36371
  }
36288
36372
  });
36289
36373
  const buildManagedCtx = async (db) => {
36290
- const { deriveHistorianChunkTokens: deriveHistorianChunkTokens2, resolveHistorianContextLimit: resolveHistorianContextLimit2 } = await import("./derive-budgets-da4yg3tz.js");
36291
- const { resolveFallbackChain: resolveFallbackChain2 } = await import("./resolve-fallbacks-5n5tvge1.js");
36292
- const { userMemoryCollectionEnabled: userMemoryCollectionEnabled2 } = await import("./task-config-gbp7r23g.js");
36374
+ const { deriveHistorianChunkTokens: deriveHistorianChunkTokens2, resolveHistorianContextLimit: resolveHistorianContextLimit2 } = await import("./derive-budgets-xk8cy5e6.js");
36375
+ const { resolveFallbackChain: resolveFallbackChain2 } = await import("./resolve-fallbacks-qf0ekmz9.js");
36376
+ const { userMemoryCollectionEnabled: userMemoryCollectionEnabled2 } = await import("./task-config-at3adc59.js");
36293
36377
  const DEFAULT_HISTORIAN_TIMEOUT_MS2 = 600000;
36294
36378
  return {
36295
36379
  client: args.client,
@@ -36314,8 +36398,8 @@ function registerRpcHandlers(rpcServer, args) {
36314
36398
  const db = getDb();
36315
36399
  if (!db)
36316
36400
  return { ok: false, error: "db unavailable" };
36317
- const { runManagedRecomp: runManagedRecomp2 } = await import("./recomp-orchestrator-jsde4ygw.js");
36318
- const { sendIgnoredMessage: sendIgnoredMessage2 } = await import("./send-session-notification-dxske5zm.js");
36401
+ const { runManagedRecomp: runManagedRecomp2 } = await import("./recomp-orchestrator-p030kxtc.js");
36402
+ const { sendIgnoredMessage: sendIgnoredMessage2 } = await import("./send-session-notification-6v5b72b4.js");
36319
36403
  log(`[rpc] recomp requested for session ${sessionId}`);
36320
36404
  const ctx = await buildManagedCtx(db);
36321
36405
  runManagedRecomp2(ctx, sessionId).then((message) => {
@@ -36330,8 +36414,8 @@ function registerRpcHandlers(rpcServer, args) {
36330
36414
  const db = getDb();
36331
36415
  if (!db)
36332
36416
  return { ok: false, error: "db unavailable" };
36333
- const { runManagedUpgrade: runManagedUpgrade2 } = await import("./recomp-orchestrator-jsde4ygw.js");
36334
- const { sendIgnoredMessage: sendIgnoredMessage2 } = await import("./send-session-notification-dxske5zm.js");
36417
+ const { runManagedUpgrade: runManagedUpgrade2 } = await import("./recomp-orchestrator-p030kxtc.js");
36418
+ const { sendIgnoredMessage: sendIgnoredMessage2 } = await import("./send-session-notification-6v5b72b4.js");
36335
36419
  log(`[rpc] session-upgrade requested for session ${sessionId}`);
36336
36420
  const ctx = await buildManagedCtx(db);
36337
36421
  runManagedUpgrade2(ctx, sessionId).then((message) => {
@@ -36347,7 +36431,7 @@ function registerRpcHandlers(rpcServer, args) {
36347
36431
  if (!db)
36348
36432
  return { ok: false, error: "db unavailable" };
36349
36433
  try {
36350
- const { updateSessionMeta: updateSessionMeta2 } = await import("./storage-meta-session-mk4gsnke.js");
36434
+ const { updateSessionMeta: updateSessionMeta2 } = await import("./storage-meta-session-2306t3j7.js");
36351
36435
  updateSessionMeta2(db, sessionId, { upgradeRemindedAt: Date.now() });
36352
36436
  return { ok: true };
36353
36437
  } catch (error) {
@@ -39010,7 +39094,7 @@ var server = async (ctx) => {
39010
39094
  `);
39011
39095
  setTimeout(async () => {
39012
39096
  try {
39013
- const { sendIgnoredMessage: sendIgnoredMessage2 } = await import("./send-session-notification-dxske5zm.js");
39097
+ const { sendIgnoredMessage: sendIgnoredMessage2 } = await import("./send-session-notification-6v5b72b4.js");
39014
39098
  const clientWithSessions = ctx.client;
39015
39099
  const sessions = await Promise.resolve(clientWithSessions.session?.list?.()).catch(() => null);
39016
39100
  const sessionList = Array.isArray(sessions) ? sessions : sessions?.data;
@@ -39158,6 +39242,11 @@ var server = async (ctx) => {
39158
39242
  embeddingConfig: pluginConfig.embedding,
39159
39243
  memoryEnabled: pluginConfig.memory?.enabled === true,
39160
39244
  memoryInjectionBudgetTokens: pluginConfig.memory?.injection_budget_tokens,
39245
+ historianChildSweep: {
39246
+ timeoutMs: pluginConfig.historian_timeout_ms,
39247
+ fallbackModelCount: resolveFallbackChain(pluginConfig.historian?.fallback_models).length,
39248
+ keepSubagents: pluginConfig.keep_subagents === true
39249
+ },
39161
39250
  mural: pluginConfig.mural,
39162
39251
  retinaHandoff: pluginConfig.smart_notes.retina_handoff,
39163
39252
  gitCommitIndexing: pluginConfig.memory.git_commit_indexing?.enabled ? {
@@ -39197,7 +39286,7 @@ var server = async (ctx) => {
39197
39286
  {
39198
39287
  const fence = getSchemaFenceRejection();
39199
39288
  if (fence) {
39200
- import("./conflict-warning-hook-an4fxhwf.js").then(({ sendSchemaFenceWarning }) => sendSchemaFenceWarning(ctx.client, ctx.directory, fence));
39289
+ import("./conflict-warning-hook-f406ggbw.js").then(({ sendSchemaFenceWarning }) => sendSchemaFenceWarning(ctx.client, ctx.directory, fence));
39201
39290
  }
39202
39291
  }
39203
39292
  if (conflictResult?.hasConflict) {
@@ -39215,10 +39304,10 @@ var server = async (ctx) => {
39215
39304
  ANNOUNCEMENT_FEATURES: ANNOUNCEMENT_FEATURES2,
39216
39305
  ANNOUNCEMENT_FOOTER: ANNOUNCEMENT_FOOTER2,
39217
39306
  markAnnouncementSeen: markAnnouncementSeen2
39218
- } = await import("./announcement-6c1g4es4.js");
39307
+ } = await import("./announcement-5eg4t64s.js");
39219
39308
  if (shouldShowAnnouncement2()) {
39220
39309
  setTimeout(() => {
39221
- import("./conflict-warning-hook-an4fxhwf.js").then(({ sendStartupAnnouncement }) => sendStartupAnnouncement(ctx.client, ctx.directory, ANNOUNCEMENT_VERSION2, ANNOUNCEMENT_FEATURES2, ANNOUNCEMENT_FOOTER2, markAnnouncementSeen2)).catch(() => {});
39310
+ import("./conflict-warning-hook-f406ggbw.js").then(({ sendStartupAnnouncement }) => sendStartupAnnouncement(ctx.client, ctx.directory, ANNOUNCEMENT_VERSION2, ANNOUNCEMENT_FEATURES2, ANNOUNCEMENT_FOOTER2, markAnnouncementSeen2)).catch(() => {});
39222
39311
  }, 8000);
39223
39312
  }
39224
39313
  } catch {}