@cortexkit/pi-magic-context 0.49.34 → 0.49.35

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 (68) hide show
  1. package/dist/auto-search-worker.js +11 -6
  2. package/dist/chunk-embedding-write-worker.js +16 -13
  3. package/dist/{compaction-marker-candidates-p1kqkqhq.js → compaction-marker-candidates-hk2frhac.js} +3 -2
  4. package/dist/compaction-marker-candidates-worker.js +1 -1
  5. package/dist/{compartment-chunk-embedding-8c85ebce.js → compartment-chunk-embedding-5j1d1e3v.js} +8 -7
  6. package/dist/embedding-backfill-jt459ady.js +26 -0
  7. package/dist/embedding-worker-process.js +2 -1
  8. package/dist/embedding-worker.js +5 -4
  9. package/dist/expand-attachments-8sxeyj26.js +21 -0
  10. package/dist/historian-calibration-extension.js +2 -1
  11. package/dist/{index-0mc0vv97.js → index-0rvn6vhq.js} +3 -3
  12. package/dist/{index-hqw0rt9k.js → index-0wtm7g7f.js} +1 -1
  13. package/dist/{index-np9ryr8y.js → index-11knwv2h.js} +20 -240
  14. package/dist/{index-0gymvr5j.js → index-2p691ayw.js} +19 -8
  15. package/dist/{index-wqpjhx1p.js → index-2qqsnh1b.js} +2 -2
  16. package/dist/index-3bb24eb6.js +229 -0
  17. package/dist/{index-48twbev2.js → index-6pk49fc3.js} +37 -51
  18. package/dist/index-6y6v2wvn.js +194 -0
  19. package/dist/{index-e61zxfts.js → index-8m82cez2.js} +4 -4
  20. package/dist/{index-xn5yh0pn.js → index-a11nmw5t.js} +29 -128
  21. package/dist/index-by1bzjcd.js +24 -0
  22. package/dist/index-c6wbq66z.js +168 -0
  23. package/dist/{index-jn44h81p.js → index-cq71g4dk.js} +1 -1
  24. package/dist/{index-6wdwv3a6.js → index-d0w84hy5.js} +1 -1
  25. package/dist/{index-pb3ea2tq.js → index-d107f484.js} +5 -5
  26. package/dist/index-d21rhpbd.js +4171 -0
  27. package/dist/index-dnp1jjar.js +222 -0
  28. package/dist/index-ea37qn4x.js +777 -0
  29. package/dist/{index-f4fz95fy.js → index-fzm8fm4z.js} +303 -4980
  30. package/dist/{index-fgs78jyd.js → index-gymgz20n.js} +5 -222
  31. package/dist/index-hgd00nas.js +113 -0
  32. package/dist/{index-cj3bkd16.js → index-m68qfjte.js} +2 -2
  33. package/dist/{index-6981g1xv.js → index-mkh1cm5k.js} +1 -1
  34. package/dist/{index-4zemngt7.js → index-mp0gh04g.js} +2 -2
  35. package/dist/{index-23t8ryqw.js → index-n0zjvs3h.js} +1 -168
  36. package/dist/{index-bvpar0bg.js → index-rgvqh5x7.js} +2 -2
  37. package/dist/{index-gwxaz0z5.js → index-rzfr7wdv.js} +2 -2
  38. package/dist/{index-eenxm3t3.js → index-svqk0701.js} +40 -29
  39. package/dist/{index-9xd7qveg.js → index-vgfk2xa5.js} +4 -4
  40. package/dist/index-w26zvs1q.js +528 -0
  41. package/dist/index-wrr9rp9a.js +16 -0
  42. package/dist/{index-my0dn413.js → index-wt7vmyj4.js} +1 -1
  43. package/dist/{index-c474g0gj.js → index-yacs388s.js} +1 -1
  44. package/dist/{index-g2tfayfc.js → index-yg42q9bc.js} +95 -550
  45. package/dist/{index-eqw9t2ty.js → index-yhsmjvqa.js} +3 -3
  46. package/dist/index.js +523 -236
  47. package/dist/{logger-shetp43v.js → logger-2j70hhz4.js} +2 -1
  48. package/dist/{message-fts-rowid-map-3mbvdgn9.js → message-fts-rowid-map-aw4xa05a.js} +5 -4
  49. package/dist/{message-index-bounded-a6na71rg.js → message-index-bounded-da34vhs4.js} +12 -10
  50. package/dist/{message-time-backfill-e3r8ddh1.js → message-time-backfill-x45573rs.js} +3 -2
  51. package/dist/migration-worker.js +13 -10
  52. package/dist/{project-embedding-registry-acqb6be4.js → project-embedding-registry-davzvsz9.js} +13 -11
  53. package/dist/raw-ordinal-warmup-worker.js +12 -7
  54. package/dist/{read-session-chunk-2xcp6f40.js → read-session-chunk-nbcznexm.js} +14 -8
  55. package/dist/{read-session-raw-g9b1zdn5.js → read-session-raw-zb8kpa2y.js} +3 -2
  56. package/dist/render-d931g2vv.js +41 -0
  57. package/dist/{safe-notification-target-zcpchea6.js → safe-notification-target-jk69jxwp.js} +3 -2
  58. package/dist/search-archive-a76pp30g.js +24 -0
  59. package/dist/{search-b6hp64hc.js → search-atp7g95j.js} +24 -20
  60. package/dist/{storage-tags-6409qq18.js → storage-tags-jy8b0xsy.js} +5 -4
  61. package/dist/store-kabezr25.js +453 -0
  62. package/dist/store-reader-2m80zs5z.js +14 -0
  63. package/dist/subagent-entry.js +31 -23
  64. package/dist/tag-snapshot-worker-pi.js +15 -12
  65. package/dist/v2-archive-reader-wcjcfdzq.js +11 -0
  66. package/package.json +1 -1
  67. package/dist/embedding-backfill-rwfmyvze.js +0 -24
  68. package/dist/search-archive-jate39w5.js +0 -21
package/dist/index.js CHANGED
@@ -9,15 +9,17 @@ import {
9
9
  getMagicContextStorageDir,
10
10
  isMagicContextStorageOutsideEngram,
11
11
  claimStorageBackupWarningCheck,
12
- sanitizeDiagnosticText,
13
- hasShareabilitySensitiveText,
14
12
  registerStalePluginBuildHost,
15
13
  classifyStalePluginBuild,
16
14
  importPluginModule,
17
15
  log2,
18
16
  sessionLog2,
19
17
  flushLogger2
20
- } from "./index-fgs78jyd.js";
18
+ } from "./index-gymgz20n.js";
19
+ import {
20
+ sanitizeDiagnosticText,
21
+ hasShareabilitySensitiveText
22
+ } from "./index-dnp1jjar.js";
21
23
  import {
22
24
  COMPACTION_ENABLED_PATH,
23
25
  isDreamerRunnable,
@@ -47,121 +49,6 @@ import {
47
49
  cortexKitProjectConfigBasePath,
48
50
  migrateMagicContextConfigLocations,
49
51
  getProtectedTokensTierOverrides,
50
- LkgRecoveryFenceError,
51
- clearLkgFenceProcessState,
52
- lkgFenceRequiresRebuild,
53
- lkgRecoveryFenceUnclean,
54
- ownsLkgDirtyFence,
55
- invalidateCleanLkgRecoveryFence,
56
- markLkgRecoveryDirty,
57
- rememberUnpublishedAutoSearchNoHint,
58
- getUnpublishedAutoSearchNoHint,
59
- forgetUnpublishedAutoSearchNoHint,
60
- registerAutoSearchWork,
61
- cancelAutoSearchWork,
62
- readSessionActivity,
63
- observeSessionActivity,
64
- backfillSessionActivity,
65
- readSessionMeta,
66
- getOrCreateSessionMeta,
67
- updateSessionMeta,
68
- advanceToolReclaimWatermark,
69
- retryPendingSessionCleanups,
70
- retryPendingRustSessionCleanupsForProject,
71
- COMPARTMENT_LEASE_RENEWAL_MS,
72
- acquireCompartmentLease,
73
- renewCompartmentLease,
74
- releaseCompartmentLease,
75
- releaseCompartmentLeaseBestEffort,
76
- isCompartmentLeaseHeld,
77
- isNoContentCompartment,
78
- HAS_COMPARTMENT_CONTENT_SQL,
79
- queueM0Mutation,
80
- getMaxM0MutationId,
81
- getCompartments,
82
- getLastCompartmentEndMessage,
83
- getLastCompartmentEndMessageId,
84
- getCompartmentsByEndMessageId,
85
- appendCompartments,
86
- saveRecompStagingPass,
87
- getRecompStaging,
88
- clearRecompStaging,
89
- getRecompPartialRange,
90
- setRecompPartialRange,
91
- escapeXmlAttr,
92
- escapeXmlContent,
93
- getUncoveredCompartmentEndThrough,
94
- isPartialCompartmentEnd,
95
- readProjectDocsCanonical,
96
- providerResponseFailed,
97
- isSuccessfulProviderCompletion,
98
- requestPendingMaterialization,
99
- pendingMaterializationOrigin,
100
- hasPendingMaterializationOrigin,
101
- clearPendingMaterialization,
102
- recordSystemRefreshOwnership,
103
- recordSystemPromptForRequest,
104
- recordHeldHeadForRequest,
105
- bindSystemPromptResponse,
106
- acknowledgeSystemPromptDelivery,
107
- deferDeliveredSystemRefresh,
108
- clearSystemPromptDelivery,
109
- saveLkgSlotToDb,
110
- loadPersistedLkgSlot,
111
- drainStaleLkgSlots,
112
- createDbLkgPersistence,
113
- replayLkg,
114
- registerLkgPersistence,
115
- LKG_SNAPSHOT_ARRAY,
116
- LKG_SNAPSHOT_OBJECT,
117
- LKG_SNAPSHOT_KEY,
118
- LKG_SNAPSHOT_STRING,
119
- LKG_SNAPSHOT_NUMBER,
120
- LKG_SNAPSHOT_BOOLEAN,
121
- LKG_SNAPSHOT_NULL,
122
- LKG_SNAPSHOT_UNDEFINED,
123
- contentSnapshotValue,
124
- signatureForFields,
125
- lkgContentFields,
126
- lkgContentDigestFromFields,
127
- isLegacyLkgDigest,
128
- legacyLkgDigestFromFields,
129
- lkgFieldsMatchDigest,
130
- exactReusablePrefix,
131
- incrementalLkgContentDigests,
132
- lkgSlotRejection,
133
- captureSlot,
134
- getInMemorySlot,
135
- getSlot,
136
- dropSlot,
137
- TOOL_SWEEP_SCOPED_MARKER,
138
- encodePiContentDecision,
139
- decodePiContentDecision,
140
- getPiContentDecisions,
141
- freezePiContentDecision,
142
- withNativeReplayWriteBarrier,
143
- getNativeReplayState,
144
- saveNativeToolInputs,
145
- addNativeReasoningIds,
146
- copySessionStateForClone,
147
- externalHistorianFailureReason,
148
- subprocessExitHistorianFailureReason,
149
- countHistorianRuns,
150
- recordHistorianRun,
151
- summarizeImportance,
152
- tallyFactsByCategory,
153
- queueMemoryMutation,
154
- getMemoryMutationsForRender,
155
- getMemoryMutationsForRenderByProjects,
156
- getMaxMemoryMutationId,
157
- getMaxMemoryMutationIdForProjects,
158
- GLOBAL_USER_PROFILE_PROJECT_PATH,
159
- getProjectState,
160
- bumpProjectUserProfileVersion,
161
- saveSourceContent,
162
- getSourceContents,
163
- recordSubagentInvocation,
164
- getLatestHistorianInvocationId,
165
52
  noteTouchedAt,
166
53
  noteNudgePickIndex,
167
54
  formatNoteNudge,
@@ -263,7 +150,7 @@ import {
263
150
  registerTodoStateLifecycle,
264
151
  syncCtxMemoryToolEnabled,
265
152
  registerMagicContextTools
266
- } from "./index-f4fz95fy.js";
153
+ } from "./index-fzm8fm4z.js";
267
154
  import"./index-4knyh1kt.js";
268
155
  import {
269
156
  canonicalModelIdentity,
@@ -288,26 +175,9 @@ import {
288
175
  createFailClosedBlockingError,
289
176
  isFailClosedBlockingError,
290
177
  shouldBypassFailClosedBlock,
291
- createFailClosedController,
292
- piHarnessKindFromExecutable,
293
- getErrorMessage,
294
- describeError,
295
- startBootDeadline,
296
- getSchemaFenceRejection,
297
- getMigrationOnOpenRefusal,
298
- LATEST_SUPPORTED_VERSION,
299
- getDatabasePath,
300
- getPersistedSchemaVersion,
301
- setSqlitePragmaConfig,
302
- applySqliteTuningPragmas,
303
- runSqliteOptimize,
304
- openDatabase,
305
- openCurrentDatabase,
306
- openDatabaseAsync,
307
- closeDatabase
308
- } from "./index-np9ryr8y.js";
178
+ createFailClosedController
179
+ } from "./index-3bb24eb6.js";
309
180
  import {
310
- sameProjectDirectory,
311
181
  pruneMissingProjectIdentities,
312
182
  setHomeProjectPermission,
313
183
  ProjectIdentityError,
@@ -318,7 +188,7 @@ import {
318
188
  resolveProjectIdentityForSession,
319
189
  beginBootQuietPeriod,
320
190
  scheduleAfterBootQuiet
321
- } from "./index-48twbev2.js";
191
+ } from "./index-6pk49fc3.js";
322
192
  import {
323
193
  detectThinkingBindingMismatch,
324
194
  detectLatestTurnThinkingMismatch,
@@ -424,7 +294,7 @@ import {
424
294
  getSessionWorkMetrics,
425
295
  resolveEpochFloorForPass,
426
296
  askAnswerLines,
427
- retreatPastHostUnservedRows,
297
+ removeUnsupportedCommitHashes,
428
298
  completedToolArcCrossesBoundary,
429
299
  estimateTrueRawMessageTokens,
430
300
  buildToolArcs,
@@ -483,7 +353,7 @@ import {
483
353
  getRawSessionTagKeysThrough2,
484
354
  getLegacyProtectedTailStartOrdinal2,
485
355
  readSessionChunk2
486
- } from "./index-eenxm3t3.js";
356
+ } from "./index-svqk0701.js";
487
357
  import {
488
358
  UNKNOWN_FIT_RATIO,
489
359
  hasMeasuredDecisionCalibration,
@@ -570,7 +440,7 @@ import {
570
440
  getToolTagNumberByOwner2,
571
441
  getNullOwnerToolTag2,
572
442
  adoptNullOwnerToolTag2
573
- } from "./index-eqw9t2ty.js";
443
+ } from "./index-yhsmjvqa.js";
574
444
  import {
575
445
  textMentionsRecentCommit,
576
446
  hasMeaningfulUserText2,
@@ -582,7 +452,7 @@ import {
582
452
  estimateTokens,
583
453
  estimateFixedPromptTokens,
584
454
  normalizeText
585
- } from "./index-my0dn413.js";
455
+ } from "./index-wt7vmyj4.js";
586
456
  import {
587
457
  inRootAsyncContext2,
588
458
  Database2,
@@ -602,27 +472,162 @@ import {
602
472
  observeTemporalDecisions,
603
473
  freezeTemporalDecisions,
604
474
  tagIdentityRevisionKey
605
- } from "./index-c474g0gj.js";
475
+ } from "./index-yacs388s.js";
476
+ import {
477
+ piHarnessKindFromExecutable,
478
+ getErrorMessage,
479
+ describeError,
480
+ startBootDeadline,
481
+ getSchemaFenceRejection,
482
+ getMigrationOnOpenRefusal,
483
+ LATEST_SUPPORTED_VERSION,
484
+ getDatabasePath,
485
+ getPersistedSchemaVersion,
486
+ setSqlitePragmaConfig,
487
+ applySqliteTuningPragmas,
488
+ runSqliteOptimize,
489
+ openDatabase,
490
+ openCurrentDatabase,
491
+ openDatabaseAsync,
492
+ closeDatabase
493
+ } from "./index-11knwv2h.js";
494
+ import {
495
+ LkgRecoveryFenceError,
496
+ clearLkgFenceProcessState,
497
+ lkgFenceRequiresRebuild,
498
+ lkgRecoveryFenceUnclean,
499
+ ownsLkgDirtyFence,
500
+ invalidateCleanLkgRecoveryFence,
501
+ markLkgRecoveryDirty,
502
+ rememberUnpublishedAutoSearchNoHint,
503
+ getUnpublishedAutoSearchNoHint,
504
+ forgetUnpublishedAutoSearchNoHint,
505
+ registerAutoSearchWork,
506
+ cancelAutoSearchWork,
507
+ readSessionActivity,
508
+ observeSessionActivity,
509
+ backfillSessionActivity,
510
+ readSessionMeta,
511
+ getOrCreateSessionMeta,
512
+ updateSessionMeta,
513
+ advanceToolReclaimWatermark,
514
+ retryPendingSessionCleanups,
515
+ retryPendingRustSessionCleanupsForProject,
516
+ COMPARTMENT_LEASE_RENEWAL_MS,
517
+ acquireCompartmentLease,
518
+ renewCompartmentLease,
519
+ releaseCompartmentLease,
520
+ releaseCompartmentLeaseBestEffort,
521
+ isCompartmentLeaseHeld,
522
+ isNoContentCompartment,
523
+ HAS_COMPARTMENT_CONTENT_SQL,
524
+ queueM0Mutation,
525
+ getMaxM0MutationId,
526
+ getCompartments,
527
+ getLastCompartmentEndMessage,
528
+ getLastCompartmentEndMessageId,
529
+ getCompartmentsByEndMessageId,
530
+ appendCompartments,
531
+ saveRecompStagingPass,
532
+ getRecompStaging,
533
+ clearRecompStaging,
534
+ getRecompPartialRange,
535
+ setRecompPartialRange,
536
+ escapeXmlAttr,
537
+ escapeXmlContent,
538
+ getUncoveredCompartmentEndThrough,
539
+ isPartialCompartmentEnd,
540
+ readProjectDocsCanonical,
541
+ providerResponseFailed,
542
+ isSuccessfulProviderCompletion,
543
+ requestPendingMaterialization,
544
+ pendingMaterializationOrigin,
545
+ hasPendingMaterializationOrigin,
546
+ clearPendingMaterialization,
547
+ recordSystemRefreshOwnership,
548
+ recordSystemPromptForRequest,
549
+ recordHeldHeadForRequest,
550
+ bindSystemPromptResponse,
551
+ acknowledgeSystemPromptDelivery,
552
+ deferDeliveredSystemRefresh,
553
+ clearSystemPromptDelivery,
554
+ saveLkgSlotToDb,
555
+ loadPersistedLkgSlot,
556
+ drainStaleLkgSlots,
557
+ createDbLkgPersistence,
558
+ replayLkg,
559
+ registerLkgPersistence,
560
+ LKG_SNAPSHOT_ARRAY,
561
+ LKG_SNAPSHOT_OBJECT,
562
+ LKG_SNAPSHOT_KEY,
563
+ LKG_SNAPSHOT_STRING,
564
+ LKG_SNAPSHOT_NUMBER,
565
+ LKG_SNAPSHOT_BOOLEAN,
566
+ LKG_SNAPSHOT_NULL,
567
+ LKG_SNAPSHOT_UNDEFINED,
568
+ contentSnapshotValue,
569
+ signatureForFields,
570
+ lkgContentFields,
571
+ lkgContentDigestFromFields,
572
+ isLegacyLkgDigest,
573
+ legacyLkgDigestFromFields,
574
+ lkgFieldsMatchDigest,
575
+ exactReusablePrefix,
576
+ incrementalLkgContentDigests,
577
+ lkgSlotRejection,
578
+ captureSlot,
579
+ getInMemorySlot,
580
+ getSlot,
581
+ dropSlot,
582
+ TOOL_SWEEP_SCOPED_MARKER,
583
+ encodePiContentDecision,
584
+ decodePiContentDecision,
585
+ getPiContentDecisions,
586
+ freezePiContentDecision,
587
+ withNativeReplayWriteBarrier,
588
+ getNativeReplayState,
589
+ saveNativeToolInputs,
590
+ addNativeReasoningIds,
591
+ copySessionStateForClone,
592
+ externalHistorianFailureReason,
593
+ subprocessExitHistorianFailureReason,
594
+ countHistorianRuns,
595
+ recordHistorianRun,
596
+ summarizeImportance,
597
+ tallyFactsByCategory,
598
+ queueMemoryMutation,
599
+ getMemoryMutationsForRender,
600
+ getMemoryMutationsForRenderByProjects,
601
+ getMaxMemoryMutationId,
602
+ getMaxMemoryMutationIdForProjects,
603
+ GLOBAL_USER_PROFILE_PROJECT_PATH,
604
+ getProjectState,
605
+ bumpProjectUserProfileVersion,
606
+ saveSourceContent,
607
+ getSourceContents,
608
+ recordSubagentInvocation,
609
+ getLatestHistorianInvocationId
610
+ } from "./index-d21rhpbd.js";
606
611
  import {
607
- BoundedSessionMap,
608
612
  resolveOpenCodeDbPath,
609
613
  assertOpenCodeStoreGeneration,
610
614
  openCodeDbPathExists,
611
615
  recordOpenCodeDbReadFailure,
612
616
  clearOpenCodeDbReadFailure,
613
617
  claimOpenCodeDbDiagnosticOnce
614
- } from "./index-23t8ryqw.js";
618
+ } from "./index-n0zjvs3h.js";
615
619
  import"./index-399p688g.js";
616
620
  import {
617
621
  createWorkerShutdown
618
622
  } from "./index-54wmg4rj.js";
619
623
  import {
620
624
  RAW_SUMMARY_TEXT_MAX_CHARS2
621
- } from "./index-6981g1xv.js";
625
+ } from "./index-mkh1cm5k.js";
626
+ import"./index-ea37qn4x.js";
622
627
  import {
623
628
  formatSynapseLaneDescriptor
624
- } from "./index-gwxaz0z5.js";
625
- import"./index-bvpar0bg.js";
629
+ } from "./index-rzfr7wdv.js";
630
+ import"./index-rgvqh5x7.js";
626
631
  import {
627
632
  buildCanonicalChunkTextFromFts2,
628
633
  buildCompartmentSummaryFallbackText2,
@@ -632,7 +637,7 @@ import {
632
637
  replaceCompartmentChunkEmbeddings2,
633
638
  deleteChunkEmbedBackoffForSession2,
634
639
  chunkWindowSourceKey2
635
- } from "./index-0gymvr5j.js";
640
+ } from "./index-2p691ayw.js";
636
641
  import {
637
642
  recordSessionProjectIdentity,
638
643
  GIT_SWEEP_LEASE_RENEWAL_MS,
@@ -641,7 +646,7 @@ import {
641
646
  markGitSweepSuccessAndRelease,
642
647
  parkGitSweepNonIndexable,
643
648
  releaseGitSweepLease
644
- } from "./index-4zemngt7.js";
649
+ } from "./index-mp0gh04g.js";
645
650
  import {
646
651
  embedPauseBySession,
647
652
  embedRunStateBySession,
@@ -650,33 +655,20 @@ import {
650
655
  autoEmbedIdentityBySession,
651
656
  autoEmbedRetryAfterBySession,
652
657
  invalidateAutoEmbedSession,
653
- getEmbedDrainUiStatus,
654
- describeShadowBackfillWriteRefusal2,
655
- contentSha2562,
656
- drainProjectEmbeddingIdentityMaintenance2,
657
- drainStaleEmbeddingIdentitiesForProject2,
658
- enqueueShadowEmbeddingItems2,
659
- getProjectEmbeddingSnapshot2,
660
- getProjectChunkEmbeddingModelId2,
661
- getProjectEmbeddingMaxInputTokens2,
662
- embedTextForProject2,
663
- embedBatchForProject2,
664
- embedItemsForProject2,
665
- embedUnembeddedMemoriesForProject2,
666
- drainCommitBacklogForProject2,
667
- embedSessionCompartmentChunks2,
668
- getEmbeddingCoverageStatus2,
669
- getAutoEmbeddingSessionCoverage2
670
- } from "./index-xn5yh0pn.js";
658
+ getEmbedDrainUiStatus
659
+ } from "./index-hgd00nas.js";
671
660
  import {
672
661
  clearCompressionDepth,
673
662
  clearCompressionDepthRange,
674
663
  cleanSearchText,
675
664
  matchedSearchSnippet
676
- } from "./index-e61zxfts.js";
665
+ } from "./index-8m82cez2.js";
677
666
  import {
678
667
  rememberV1HiddenRun
679
668
  } from "./index-6x556c2q.js";
669
+ import {
670
+ BoundedSessionMap
671
+ } from "./index-c6wbq66z.js";
680
672
  import {
681
673
  V2_MEMORY_CATEGORIES
682
674
  } from "./index-135e8hvg.js";
@@ -688,7 +680,7 @@ import {
688
680
  expandWorkspaceIdentitySetWithAliases,
689
681
  sourceNameForMemory,
690
682
  computeWorkspaceEpochFingerprint
691
- } from "./index-pb3ea2tq.js";
683
+ } from "./index-d107f484.js";
692
684
  import {
693
685
  configureContextDatabasePragmas2
694
686
  } from "./index-fapenpch.js";
@@ -712,39 +704,8 @@ import {
712
704
  getActivePrimers,
713
705
  createPrimer,
714
706
  updatePrimerSupport,
715
- updatePrimerAnswer,
716
- USER_FACING_FAILURES,
717
- renderUserFacingFailure,
718
- userFacingFailureCode,
719
- renderCapabilityRefusal,
720
- renderDreamFailure,
721
- dreamFailureCode,
722
- renderEmbeddingFailure,
723
- renderSingleStoreMigrationRequiredRefusal,
724
- SingleStoreMigrationRequiredError,
725
- projectNeedsSingleStoreMigration,
726
- promoteSessionFactsDurable,
727
- embedPromotedFacts,
728
- recordMemoryMapping,
729
- recordMemoryVerifications,
730
- getUnmappedMemoryIds,
731
- clearMemoryVerifications,
732
- getMemoryVerifications,
733
- resolveGitTopLevel,
734
- readGitHead,
735
- readGitChangedFilesSince,
736
- readGitFileChangeTimesSince,
737
- verificationFileExists,
738
- normalizeVerificationFiles,
739
- indexCommitsForProject,
740
- embedUnembeddedCommits,
741
- getMessageIndexEpoch,
742
- isMessageIndexSearchable,
743
- scheduleReconciliation,
744
- scheduleIncrementalIndex,
745
- scheduleClearAndReindex,
746
- clearSessionTracking
747
- } from "./index-g2tfayfc.js";
707
+ updatePrimerAnswer
708
+ } from "./index-w26zvs1q.js";
748
709
  import {
749
710
  setEmbeddingSessionBusy2,
750
711
  isEmbeddingHostBusy2
@@ -777,11 +738,63 @@ import {
777
738
  } from "./index-q1yc6bs0.js";
778
739
  import {
779
740
  getCachedLocalEmbeddingPooling
780
- } from "./index-wqpjhx1p.js";
741
+ } from "./index-2qqsnh1b.js";
742
+ import {
743
+ describeShadowBackfillWriteRefusal2,
744
+ contentSha2562,
745
+ drainProjectEmbeddingIdentityMaintenance2,
746
+ drainStaleEmbeddingIdentitiesForProject2,
747
+ enqueueShadowEmbeddingItems2,
748
+ getProjectEmbeddingSnapshot2,
749
+ getProjectChunkEmbeddingModelId2,
750
+ getProjectEmbeddingMaxInputTokens2,
751
+ embedTextForProject2,
752
+ embedBatchForProject2,
753
+ embedItemsForProject2,
754
+ embedUnembeddedMemoriesForProject2,
755
+ drainCommitBacklogForProject2,
756
+ embedSessionCompartmentChunks2,
757
+ getEmbeddingCoverageStatus2,
758
+ getAutoEmbeddingSessionCoverage2
759
+ } from "./index-a11nmw5t.js";
781
760
  import {
782
761
  cosineSimilarity
783
- } from "./index-9xd7qveg.js";
784
- import"./index-6wdwv3a6.js";
762
+ } from "./index-vgfk2xa5.js";
763
+ import {
764
+ USER_FACING_FAILURES,
765
+ renderUserFacingFailure,
766
+ userFacingFailureCode,
767
+ renderCapabilityRefusal,
768
+ renderDreamFailure,
769
+ dreamFailureCode,
770
+ renderEmbeddingFailure,
771
+ renderSingleStoreMigrationRequiredRefusal,
772
+ SingleStoreMigrationRequiredError,
773
+ projectNeedsSingleStoreMigration,
774
+ promoteSessionFactsDurable,
775
+ embedPromotedFacts,
776
+ recordMemoryMapping,
777
+ recordMemoryVerifications,
778
+ getUnmappedMemoryIds,
779
+ clearMemoryVerifications,
780
+ getMemoryVerifications,
781
+ resolveGitTopLevel,
782
+ readGitHead,
783
+ readGitChangedFilesSince,
784
+ readGitFileChangeTimesSince,
785
+ verificationFileExists,
786
+ normalizeVerificationFiles,
787
+ indexCommitsForProject,
788
+ embedUnembeddedCommits,
789
+ getMessageIndexEpoch,
790
+ isMessageIndexSearchable,
791
+ scheduleReconciliation,
792
+ scheduleIncrementalIndex,
793
+ scheduleClearAndReindex,
794
+ clearSessionTracking,
795
+ createAutoSearchDiagnostics
796
+ } from "./index-yg42q9bc.js";
797
+ import"./index-d0w84hy5.js";
785
798
  import {
786
799
  DREAMER_PRIMER_INVESTIGATOR_ALLOWED_TOOLS,
787
800
  buildHiddenAgentRegistrations,
@@ -808,19 +821,26 @@ import {
808
821
  drainPiTagSnapshotSession,
809
822
  assertPiTagSnapshotReady,
810
823
  ensurePiTagSnapshotReady
811
- } from "./index-0mc0vv97.js";
812
- import"./index-jn44h81p.js";
824
+ } from "./index-0rvn6vhq.js";
825
+ import"./index-cq71g4dk.js";
813
826
  import"./index-1cvyaw9a.js";
814
- import"./index-cj3bkd16.js";
827
+ import"./index-6y6v2wvn.js";
828
+ import"./index-m68qfjte.js";
815
829
  import {
816
830
  __toESM
817
831
  } from "./index-22jkk6wg.js";
832
+ import {
833
+ retreatPastHostUnservedRows
834
+ } from "./index-by1bzjcd.js";
818
835
  import {
819
836
  computeNormalizedHash
820
837
  } from "./index-9x1f96r8.js";
821
838
  import {
822
839
  normalizeProtectedToolName
823
840
  } from "./index-674f6qs2.js";
841
+ import {
842
+ sameProjectDirectory
843
+ } from "./index-wrr9rp9a.js";
824
844
  import {
825
845
  closeQuietly,
826
846
  isKnownAutocommit
@@ -828,7 +848,7 @@ import {
828
848
  import {
829
849
  logSlowWriteTransaction,
830
850
  WriteTransactionSteps
831
- } from "./index-hqw0rt9k.js";
851
+ } from "./index-0wtm7g7f.js";
832
852
  import {
833
853
  setStoragePrivatePermissionEnforcement,
834
854
  ensureStorageDirectorySync,
@@ -3560,7 +3580,7 @@ function startHostStallProfilerSwitch() {
3560
3580
  // package.json
3561
3581
  var package_default = {
3562
3582
  name: "@cortexkit/pi-magic-context",
3563
- version: "0.49.34",
3583
+ version: "0.49.35",
3564
3584
  type: "module",
3565
3585
  description: "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
3566
3586
  main: "dist/index.js",
@@ -7235,6 +7255,15 @@ function validateHistorianOutput(text, sessionId, chunk, _priorCompartments, seq
7235
7255
  error: "Historian terminal boundary splits a completed tool invocation/result arc"
7236
7256
  });
7237
7257
  }
7258
+ for (const compartment of mapped.compartments) {
7259
+ const supported = new Set(chunk.lines.filter((line) => line.ordinal >= compartment.startMessage && line.ordinal <= compartment.endMessage).flatMap((line) => line.commitHashes ?? []));
7260
+ for (const field of ["title", "content", "p1", "p2", "p3", "p4"]) {
7261
+ const value = compartment[field];
7262
+ if (typeof value === "string") {
7263
+ compartment[field] = removeUnsupportedCommitHashes(value, supported);
7264
+ }
7265
+ }
7266
+ }
7238
7267
  return finish({
7239
7268
  ok: true,
7240
7269
  compartments: mapped.compartments,
@@ -24734,6 +24763,50 @@ function prepareLegacyToolSkeletonConversions(db, sessionId, targets, options =
24734
24763
  }
24735
24764
  };
24736
24765
  }
24766
+ function prepareAgedToolSkeletonConversions(db, sessionId, targets, options = {}) {
24767
+ const candidates = [...targets.keys()].sort((a, b) => a - b);
24768
+ const readRows = (connection) => {
24769
+ const window = getNewestToolTagNumbers2(connection, sessionId, RECENT_TOOL_SKELETON_WINDOW);
24770
+ const recent = new Set(window);
24771
+ const statement = connection.prepare(`SELECT tag_number AS tagNumber, drop_mode AS dropMode, message_id AS callId
24772
+ FROM tags WHERE session_id = ? AND tag_number = ?
24773
+ AND type = 'tool' AND status = 'dropped'
24774
+ AND drop_mode IN ('truncated', 'skeleton_real', 'skeleton_stripped')`);
24775
+ const rows = candidates.filter((id) => !recent.has(id)).flatMap((id) => {
24776
+ const row = statement.get(sessionId, id);
24777
+ return row ? [row] : [];
24778
+ });
24779
+ return { window, rows };
24780
+ };
24781
+ const snapshot = readRows(db);
24782
+ options.prepareRemovals?.(snapshot.rows);
24783
+ const converted = new Map;
24784
+ const plannedRemovals = new Set;
24785
+ for (const row of snapshot.rows) {
24786
+ const target = targets.get(row.tagNumber);
24787
+ if (target?.thinkingDropProtected || target?.thinkingRewriteProtected || target?.identityRepairProtected)
24788
+ continue;
24789
+ if (target?.canDrop?.() !== true || target.prepareDrop?.() === false)
24790
+ continue;
24791
+ if (target.requiresToolArcSkeleton) {
24792
+ const owners = target.mutationParts ? target.mutationParts.map(({ message }) => message).filter((message) => message.info.role === "assistant") : target.message ? [target.message] : [];
24793
+ if (owners.length === 0 || owners.some((message) => !options.thinkingStrippedIds?.has(message.info.id ?? "")))
24794
+ continue;
24795
+ }
24796
+ if (target.cannotRemove?.() === true || target.wouldStrandConversationEnd?.(plannedRemovals) === true)
24797
+ continue;
24798
+ converted.set(row.tagNumber, "full");
24799
+ target.notePlannedRemoval?.(plannedRemovals);
24800
+ }
24801
+ return {
24802
+ converted,
24803
+ isCurrent: (connection) => JSON.stringify(readRows(connection)) === JSON.stringify(snapshot),
24804
+ persist: (connection) => {
24805
+ for (const tagNumber of converted.keys())
24806
+ updateTagDropMode2(connection, sessionId, tagNumber, "full");
24807
+ }
24808
+ };
24809
+ }
24737
24810
  var PENDING_OPERATION_CHUNK_SIZE = 64;
24738
24811
  function applyPendingOperations(sessionId, db, targets, protectedTagIds, preloadedTags, preloadedPendingOps, syntheticPendingOps = [], editMarkerTagIds = new Set, onTagReduced, onBatchComplete, onEligibilitySnapshot) {
24739
24812
  let didMutateMessage = false;
@@ -28536,6 +28609,32 @@ function selectAutoSearchResults(results, threshold) {
28536
28609
  return results.filter((result) => relevance(result) >= threshold).sort((left, right) => relevance(right) - relevance(left));
28537
28610
  }
28538
28611
 
28612
+ // ../plugin/src/hooks/magic-context/auto-search-observation.ts
28613
+ var disabledTurns = new WeakMap;
28614
+ function logDisabledAutoSearch(db, sessionId, messageId, threshold, startedAt) {
28615
+ const sessions = disabledTurns.get(db) ?? new Map;
28616
+ disabledTurns.set(db, sessions);
28617
+ if (sessions.get(sessionId) === messageId)
28618
+ return;
28619
+ sessions.set(sessionId, messageId);
28620
+ observeAutoSearch(sessionId, threshold, startedAt).finish("disabled");
28621
+ }
28622
+ function observeAutoSearch(sessionId, threshold, startedAt) {
28623
+ const diagnostics = createAutoSearchDiagnostics(threshold);
28624
+ let logged = false;
28625
+ return {
28626
+ diagnostics,
28627
+ finish(outcome, reason) {
28628
+ if (logged)
28629
+ return;
28630
+ logged = true;
28631
+ const lanes = Object.entries(diagnostics.lanes).map(([lane, value]) => `${lane}:${value.top?.toFixed(3) ?? "none"}`).join(",");
28632
+ const nearMisses = Object.values(diagnostics.lanes).reduce((sum, lane) => sum + lane.nearMisses, 0);
28633
+ sessionLog2(sessionId, `auto-search: decision outcome=${outcome}${reason ? ` reason=${reason}` : ""} lanes=${lanes || "none"} nearMisses=${nearMisses} threshold=${threshold} pool=${diagnostics.pool} rows=${diagnostics.poolRows ?? "unknown"} workerStarted=${diagnostics.workerStarted ?? "unknown"} peek=${diagnostics.peek} elapsedMs=${Math.round(performance.now() - startedAt)}`);
28634
+ }
28635
+ };
28636
+ }
28637
+
28539
28638
  // ../plugin/src/hooks/magic-context/auto-search-worker-client.ts
28540
28639
  import { Worker } from "node:worker_threads";
28541
28640
  var pendingRegistrations = new WeakMap;
@@ -28773,6 +28872,7 @@ async function executeAutoSearchWorker(db, sessionId, projectPath, query, option
28773
28872
  readMessages: _readMessages,
28774
28873
  searchMessageHistory: _searchMessageHistory,
28775
28874
  stepTimings: _stepTimings,
28875
+ onAutoSearchDiagnostics: _onAutoSearchDiagnostics,
28776
28876
  ...serializable
28777
28877
  } = options;
28778
28878
  const lifecycle = registerAutoSearchWork(sessionId);
@@ -28814,6 +28914,11 @@ async function executeAutoSearchWorker(db, sessionId, projectPath, query, option
28814
28914
  throw new AutoSearchBusyError;
28815
28915
  }
28816
28916
  const { slot, fresh } = lease;
28917
+ if (options.autoSearchDiagnostics) {
28918
+ options.autoSearchDiagnostics.workerStarted = fresh;
28919
+ if (fresh)
28920
+ options.autoSearchDiagnostics.pool = "cold";
28921
+ }
28817
28922
  const worker = slot.worker;
28818
28923
  const detachable = job === "search" && entry.href === defaultAutoSearchWorkerEntry().href;
28819
28924
  const startedAt = performance.now();
@@ -28893,6 +28998,15 @@ async function executeAutoSearchWorker(db, sessionId, projectPath, query, option
28893
28998
  const onMessage = async (reply) => {
28894
28999
  if (released)
28895
29000
  return;
29001
+ if (reply.kind === "diagnostics") {
29002
+ if (!settled && options.autoSearchDiagnostics) {
29003
+ const workerStarted = options.autoSearchDiagnostics.workerStarted;
29004
+ Object.assign(options.autoSearchDiagnostics, reply.diagnostics, {
29005
+ workerStarted
29006
+ });
29007
+ }
29008
+ return;
29009
+ }
28896
29010
  if (reply.kind === "result" || reply.kind === "error") {
28897
29011
  if (detachedAt !== undefined) {
28898
29012
  logLateSearch(sessionId, performance.now() - detachedAt, detachedAt - startedAt, ownerVectorMs, reply.kind === "result" ? reply.timings : undefined, reply.kind === "error");
@@ -29096,8 +29210,6 @@ async function runAutoSearchHintForPi(args) {
29096
29210
  const timestamp = message.timestamp;
29097
29211
  return `test-entry-${index}:${typeof timestamp === "number" ? timestamp : "no-ts"}`;
29098
29212
  }) : args.entryIds;
29099
- if (!options.enabled)
29100
- return messages;
29101
29213
  const strictResolutionFailed = entryIds === null;
29102
29214
  const effectiveEntryIds = strictResolutionFailed ? messages.map((message) => {
29103
29215
  const id = message.id;
@@ -29107,6 +29219,11 @@ async function runAutoSearchHintForPi(args) {
29107
29219
  if (found === null)
29108
29220
  return messages;
29109
29221
  const { message: userMsg, messageId: userMsgId } = found;
29222
+ if (!options.enabled) {
29223
+ if (found.index === messages.length - 1)
29224
+ logDisabledAutoSearch(db, sessionId, userMsgId, options.scoreThreshold ?? DEFAULT_SCORE_THRESHOLD, startedAt);
29225
+ return messages;
29226
+ }
29110
29227
  await wait(coalesceAutoSearchTurn(db, sessionId, userMsgId, async (lifecycleSignal) => {
29111
29228
  args.passGuard?.assert();
29112
29229
  if (lifecycleSignal.aborted)
@@ -29133,10 +29250,12 @@ async function runAutoSearchHintForPi(args) {
29133
29250
  return messages;
29134
29251
  if (!isUsableProjectIdentity(options.projectPath))
29135
29252
  return messages;
29253
+ const observation = observeAutoSearch(sessionId, options.scoreThreshold ?? DEFAULT_SCORE_THRESHOLD, startedAt);
29136
29254
  const snapshot = getProjectEmbeddingSnapshot2(options.projectPath);
29137
29255
  if (!snapshot) {
29138
29256
  queueAutoSearchRegistration(db, options.projectPath, args.ensureProjectRegistered);
29139
29257
  persistAutoSearchSkip(db, sessionId, userMsgId, "empty");
29258
+ observation.finish("no-candidates", "unregistered");
29140
29259
  return messages;
29141
29260
  }
29142
29261
  const writeNoHintAndReconcile = async (reason) => {
@@ -29149,17 +29268,20 @@ async function runAutoSearchHintForPi(args) {
29149
29268
  args.passGuard?.assert();
29150
29269
  if (outcome === null) {
29151
29270
  persistAutoSearchSkip(db, sessionId, userMsgId);
29271
+ observation.finish("timeout");
29152
29272
  return;
29153
29273
  }
29154
- if (!outcome.ok)
29274
+ if (!outcome.ok) {
29275
+ observation.finish("error", outcome.kind);
29155
29276
  return;
29277
+ }
29156
29278
  if (outcome.kind === "already-present" && outcome.decision.decision === "hint") {
29157
29279
  appendHintToUserMessage(userMsg, outcome.decision.text);
29158
29280
  }
29281
+ observation.finish(outcome.decision.decision === "hint" ? "attached" : reason === "below-threshold" ? "below-threshold" : reason === "error" ? "error" : "no-candidates", reason);
29159
29282
  };
29160
29283
  const rawPartsText = collectUserPromptParts(userMsg);
29161
29284
  if (hasStackedAugmentation(rawPartsText)) {
29162
- sessionLog2(sessionId, "auto-search: skipping — user message already carries augmentation/hint");
29163
29285
  await writeNoHintAndReconcile("stacked");
29164
29286
  return messages;
29165
29287
  }
@@ -29179,6 +29301,7 @@ async function runAutoSearchHintForPi(args) {
29179
29301
  const embeddingEnabled = snapshot ? snapshot.historyEnabled : true;
29180
29302
  const gitCommitsEnabled = snapshot?.gitCommitEnabled ?? false;
29181
29303
  const searchOptions = {
29304
+ autoSearchDiagnostics: observation.diagnostics,
29182
29305
  limit: 10,
29183
29306
  maxMessageOrdinal: Math.max(0, getLastCompartmentEndMessage(db, sessionId)),
29184
29307
  excludeMessageId: userMsgId,
@@ -29207,11 +29330,10 @@ async function runAutoSearchHintForPi(args) {
29207
29330
  if (lifecycleSignal.aborted)
29208
29331
  return messages;
29209
29332
  if (error instanceof AutoSearchBusyError) {
29210
- sessionLog2(sessionId, "auto-search: an earlier search of this session is still running, skipping hint for this turn");
29333
+ observation.finish("timeout", "worker-busy");
29211
29334
  persistAutoSearchSkip(db, sessionId, userMsgId);
29212
29335
  return messages;
29213
29336
  }
29214
- log2(`[auto-search] unified search failed for session ${sessionId} (no-hint frozen for this turn): ${error instanceof Error ? error.message : String(error)}`);
29215
29337
  await writeNoHintAndReconcile("error");
29216
29338
  return messages;
29217
29339
  }
@@ -29220,7 +29342,7 @@ async function runAutoSearchHintForPi(args) {
29220
29342
  return messages;
29221
29343
  try {
29222
29344
  if (results === null) {
29223
- sessionLog2(sessionId, `auto-search: timed out after ${AUTO_SEARCH_TIMEOUT_MS}ms, skipping hint for this turn`);
29345
+ observation.finish("timeout");
29224
29346
  persistAutoSearchSkip(db, sessionId, userMsgId);
29225
29347
  return messages;
29226
29348
  }
@@ -29231,7 +29353,6 @@ async function runAutoSearchHintForPi(args) {
29231
29353
  const scoreThreshold = options.scoreThreshold ?? DEFAULT_SCORE_THRESHOLD;
29232
29354
  results = selectAutoSearchResults(results, scoreThreshold);
29233
29355
  if (results.length === 0) {
29234
- sessionLog2(sessionId, `auto-search: no fragment meets relevance threshold ${scoreThreshold}`);
29235
29356
  await writeNoHintAndReconcile("below-threshold");
29236
29357
  return messages;
29237
29358
  }
@@ -29255,14 +29376,17 @@ ${hintText}`;
29255
29376
  args.passGuard?.assert();
29256
29377
  if (outcome === null) {
29257
29378
  persistAutoSearchSkip(db, sessionId, userMsgId);
29379
+ observation.finish("timeout");
29258
29380
  return messages;
29259
29381
  }
29260
- if (!outcome.ok)
29382
+ if (!outcome.ok) {
29383
+ observation.finish("error", outcome.kind);
29261
29384
  return messages;
29385
+ }
29262
29386
  if (outcome.decision.decision === "hint") {
29263
29387
  appendHintToUserMessage(userMsg, outcome.decision.text);
29264
29388
  }
29265
- sessionLog2(sessionId, `auto-search: attached hint to ${userMsgId} (${results.length} fragments, top relevance ${(results[0].relevanceScore ?? results[0].score).toFixed(3)})`);
29389
+ observation.finish(outcome.decision.decision === "hint" ? "attached" : "no-candidates");
29266
29390
  return messages;
29267
29391
  } finally {
29268
29392
  if (!lifecycleSignal.aborted && results !== null) {
@@ -35316,6 +35440,118 @@ function authorizePiToolRemoval(args) {
35316
35440
  }
35317
35441
  }
35318
35442
 
35443
+ // src/native-replay-tag-provenance-pi.ts
35444
+ import { createHash as createHash12 } from "node:crypto";
35445
+ var PI_NATIVE_TAG_STRIP_PROVENANCE = "magicContextNativeTagStrips";
35446
+ function nativeResponseTagStripKey(id, phase, text) {
35447
+ return createHash12("sha256").update(JSON.stringify([id, phase, text])).digest("hex");
35448
+ }
35449
+ function ownsNativeResponseTagStrip(decisions, id, phase, text) {
35450
+ if (!isRecord(decisions) || phase !== undefined && phase !== "commentary" && phase !== "final_answer")
35451
+ return false;
35452
+ return Object.entries(decisions).some(([key, original]) => typeof original === "string" && /^§\d+§ /u.test(original) && original.replace(/^§\d+§ /u, "") === text && nativeResponseTagStripKey(id, phase, original) === key);
35453
+ }
35454
+
35455
+ // src/native-replay-tags-pi.ts
35456
+ var FIELD = "piResponsesTagStrips";
35457
+ var TAG = /^§\d+§ /u;
35458
+ function readDecisions(value) {
35459
+ if (value === undefined)
35460
+ return new Set;
35461
+ if (!Array.isArray(value) || !value.every((key) => typeof key === "string" && /^[a-f0-9]{64}$/u.test(key)))
35462
+ throw new Error("Invalid persisted Responses tag strips");
35463
+ return new Set(value);
35464
+ }
35465
+ function signature(part) {
35466
+ if (!isRecord(part) || typeof part.textSignature !== "string")
35467
+ return;
35468
+ try {
35469
+ const value = JSON.parse(part.textSignature);
35470
+ if (isRecord(value) && value.v === 1 && typeof value.id === "string" && value.id.length > 0 && (value.phase === undefined || value.phase === "commentary" || value.phase === "final_answer"))
35471
+ return { id: value.id, phase: value.phase };
35472
+ } catch {}
35473
+ }
35474
+ function applyNativeResponseTagReplayPi(args) {
35475
+ let saved;
35476
+ const added = new Set;
35477
+ const pending = new Map;
35478
+ for (const [index, message] of args.messages.entries()) {
35479
+ if (!isRecord(message) || message.role !== "assistant" || !Array.isArray(message.content) || ![
35480
+ "openai-responses",
35481
+ "azure-openai-responses",
35482
+ "openai-codex-responses"
35483
+ ].includes(String(message.api)))
35484
+ continue;
35485
+ const payload = message.providerPayload;
35486
+ if (!isRecord(payload) || payload.type !== "openaiResponsesHistory" || payload.dt !== true || !Array.isArray(payload.items))
35487
+ continue;
35488
+ if (saved === undefined) {
35489
+ try {
35490
+ saved = readDecisions(readReplayEnvelope(args.db, args.sessionId)[FIELD]);
35491
+ } catch (error) {
35492
+ sessionLog2(args.sessionId, `native tag replay unavailable; retaining native history: ${String(error)}`);
35493
+ return 0;
35494
+ }
35495
+ }
35496
+ if (!args.canApply && saved.size === 0)
35497
+ return 0;
35498
+ const frozen = saved;
35499
+ const content = message.content;
35500
+ const nativeItems = payload.items;
35501
+ const decisions = {};
35502
+ let changed = false;
35503
+ const items = nativeItems.map((item) => {
35504
+ if (!isRecord(item) || item.type !== "message" || item.role !== "assistant" || item.phase !== undefined && item.phase !== "commentary" && item.phase !== "final_answer" || !Array.isArray(item.content) || item.content.length !== 1)
35505
+ return item;
35506
+ const output = item.content[0];
35507
+ if (!isRecord(output) || output.type !== "output_text" || typeof output.text !== "string" || !TAG.test(output.text))
35508
+ return item;
35509
+ if (nativeItems.filter((other) => isRecord(other) && other.id === item.id && other.phase === item.phase).length !== 1)
35510
+ return item;
35511
+ const key = nativeResponseTagStripKey(item.id, item.phase, output.text);
35512
+ if (!frozen.has(key)) {
35513
+ if (!args.canApply)
35514
+ return item;
35515
+ const blocks = content.filter((block) => {
35516
+ const identity = signature(block);
35517
+ return identity && identity.id === item.id && identity.phase === item.phase;
35518
+ });
35519
+ const block = blocks[0];
35520
+ if (blocks.length !== 1 || !isRecord(block) || block.type !== "text" || typeof block.text !== "string" || block.text.replace(TAG, "") !== output.text.replace(TAG, ""))
35521
+ return item;
35522
+ added.add(key);
35523
+ }
35524
+ decisions[key] = output.text;
35525
+ changed = true;
35526
+ return {
35527
+ ...item,
35528
+ content: [{ ...output, text: output.text.replace(TAG, "") }]
35529
+ };
35530
+ });
35531
+ if (changed)
35532
+ pending.set(index, {
35533
+ ...message,
35534
+ [PI_NATIVE_TAG_STRIP_PROVENANCE]: decisions,
35535
+ providerPayload: { ...payload, items }
35536
+ });
35537
+ }
35538
+ if (added.size > 0) {
35539
+ const persisted = updateReplayDocument(args.db, args.sessionId, (doc) => {
35540
+ const decisions = readDecisions(doc[FIELD]);
35541
+ for (const key of added)
35542
+ decisions.add(key);
35543
+ doc.version = 2;
35544
+ doc[FIELD] = [...decisions];
35545
+ return true;
35546
+ });
35547
+ if (!persisted)
35548
+ throw new Error("Could not persist Responses tag strips");
35549
+ }
35550
+ for (const [index, message] of pending)
35551
+ args.messages[index] = message;
35552
+ return added.size;
35553
+ }
35554
+
35319
35555
  // src/note-visibility-pi.ts
35320
35556
  var NOTE_TOOL_NAME = "ctx_note";
35321
35557
  var READ_ACTION = "read";
@@ -36846,7 +37082,7 @@ function coldReplayable(items) {
36846
37082
  }
36847
37083
  return reasoning;
36848
37084
  }
36849
- function piResponsesAssistantTexts(value, model, host, alternatives) {
37085
+ function piResponsesAssistantTexts(value, model, host, alternatives, frozenTagStrips) {
36850
37086
  const message = object10(value);
36851
37087
  if (!message || !Array.isArray(message.content))
36852
37088
  return;
@@ -36900,6 +37136,7 @@ function piResponsesAssistantTexts(value, model, host, alternatives) {
36900
37136
  ].includes(model?.api ?? "");
36901
37137
  let unsigned = false;
36902
37138
  let rewrittenText = false;
37139
+ let allUnsignedFrozen = true;
36903
37140
  for (const value of payload.items) {
36904
37141
  const item = object10(value);
36905
37142
  if (item?.type === "reasoning")
@@ -36929,6 +37166,7 @@ function piResponsesAssistantTexts(value, model, host, alternatives) {
36929
37166
  if (!allowUnsigned || "textSignature" in block || stripped !== block.text.replace(/^§\d+§ /u, ""))
36930
37167
  return texts;
36931
37168
  unsigned = true;
37169
+ allUnsignedFrozen &&= part.text === block.text && ownsNativeResponseTagStrip(frozenTagStrips, item.id, item.phase, part.text);
36932
37170
  rewrittenText ||= part.text !== stripped;
36933
37171
  }
36934
37172
  bound++;
@@ -36940,7 +37178,7 @@ function piResponsesAssistantTexts(value, model, host, alternatives) {
36940
37178
  for (const text of itemTexts)
36941
37179
  replay.push(textIdentity2(wellFormed2(text), item.phase));
36942
37180
  }
36943
- if (!output || bound !== blocks.length || unsigned && !rewrittenText)
37181
+ if (!output || bound !== blocks.length || unsigned && !rewrittenText && !allUnsignedFrozen)
36944
37182
  return texts;
36945
37183
  if (unsigned && alternatives) {
36946
37184
  alternatives.fallback = texts;
@@ -37555,7 +37793,7 @@ function buildPiPreparedStructure(messages, model, prepareUser, host = "omp") {
37555
37793
  continue;
37556
37794
  }
37557
37795
  const alternatives = {};
37558
- const texts = piResponsesAssistantTexts(projectedMessages[index], model, host, alternatives);
37796
+ const texts = piResponsesAssistantTexts(projectedMessages[index], model, host, alternatives, object11(projectedMessages[index])?.[PI_NATIVE_TAG_STRIP_PROVENANCE]);
37559
37797
  if (!texts) {
37560
37798
  responsesMessages = undefined;
37561
37799
  break;
@@ -40059,7 +40297,7 @@ function createPiFallbackIndex() {
40059
40297
  }
40060
40298
 
40061
40299
  // src/pi-fit-reclaim.ts
40062
- import { createHash as createHash12, randomUUID as randomUUID4 } from "node:crypto";
40300
+ import { createHash as createHash13, randomUUID as randomUUID4 } from "node:crypto";
40063
40301
  var pendingInput = new Set;
40064
40302
  var KEY2 = "piUpperEstimateReclaim";
40065
40303
  function piFitOverflowPossible(args) {
@@ -40095,7 +40333,7 @@ function piUpperReclaimCursor(args) {
40095
40333
  sessionId: args.sessionId,
40096
40334
  modelKey: args.modelKey,
40097
40335
  contextWindow: args.contextWindow ?? null,
40098
- head: head ? createHash12("sha256").update(JSON.stringify([
40336
+ head: head ? createHash13("sha256").update(JSON.stringify([
40099
40337
  Buffer.from(head.cachedM0Bytes ?? []).toString("base64"),
40100
40338
  Buffer.from(head.cachedM1Bytes ?? []).toString("base64"),
40101
40339
  head.cachedM0MuralDataUrl ?? null
@@ -40182,7 +40420,7 @@ async function waitForPiHistorianInTurn(sessionId, remainingMs, wait) {
40182
40420
  }
40183
40421
 
40184
40422
  // src/pi-lkg-fit-envelope.ts
40185
- import { createHash as createHash13 } from "node:crypto";
40423
+ import { createHash as createHash14 } from "node:crypto";
40186
40424
  function readPiLkgFitEnvelope(ctx, pi, modelKey, frozen, wireSchema) {
40187
40425
  try {
40188
40426
  if (!modelKey || typeof pi.getAllTools !== "function")
@@ -40244,7 +40482,7 @@ function readPiLkgFitEnvelope(ctx, pi, modelKey, frozen, wireSchema) {
40244
40482
  refusalToolDefinitionTokens,
40245
40483
  toolDefinitionsMeasured: refusalToolDefinitionTokens !== undefined,
40246
40484
  envelopeBytes: Buffer.byteLength(envelopeJson),
40247
- envelopeSignature: activeNames ? createHash13("sha256").update(envelopeJson).update(JSON.stringify(activeNames)).digest("hex") : undefined,
40485
+ envelopeSignature: activeNames ? createHash14("sha256").update(envelopeJson).update(JSON.stringify(activeNames)).digest("hex") : undefined,
40248
40486
  calibration
40249
40487
  };
40250
40488
  } catch {
@@ -40253,13 +40491,13 @@ function readPiLkgFitEnvelope(ctx, pi, modelKey, frozen, wireSchema) {
40253
40491
  }
40254
40492
 
40255
40493
  // src/pi-message-identity.ts
40256
- import { createHash as createHash16 } from "node:crypto";
40494
+ import { createHash as createHash17 } from "node:crypto";
40257
40495
 
40258
40496
  // src/pi-tool-identity.ts
40259
- import { createHash as createHash15 } from "node:crypto";
40497
+ import { createHash as createHash16 } from "node:crypto";
40260
40498
 
40261
40499
  // src/served-array-ledger.ts
40262
- import { createHash as createHash14 } from "node:crypto";
40500
+ import { createHash as createHash15 } from "node:crypto";
40263
40501
  import {
40264
40502
  closeSync as closeSync2,
40265
40503
  fstatSync,
@@ -40537,7 +40775,7 @@ function getPiLastServedArray(sessionId) {
40537
40775
  return previous ? `[${previous.serializedMessages.join(",")}]` : undefined;
40538
40776
  }
40539
40777
  function sha256(value) {
40540
- return createHash14("sha256").update(value).digest("hex");
40778
+ return createHash15("sha256").update(value).digest("hex");
40541
40779
  }
40542
40780
  function safeSessionFileStem(sessionId) {
40543
40781
  const readable = sessionId.replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 96);
@@ -40822,7 +41060,7 @@ function readPiServedCachedArray(sessionId) {
40822
41060
  const memory = getPiLastServedArray(sessionId);
40823
41061
  const slot = memory === undefined ? getSlot(sessionId) : undefined;
40824
41062
  const jsonPrefix = memory ?? slot?.jsonPrefix;
40825
- if (jsonPrefix === undefined || createHash15("sha256").update(jsonPrefix).digest("hex") !== getPiLastServedDigest(sessionId))
41063
+ if (jsonPrefix === undefined || createHash16("sha256").update(jsonPrefix).digest("hex") !== getPiLastServedDigest(sessionId))
40826
41064
  return;
40827
41065
  let parsed;
40828
41066
  try {
@@ -40846,7 +41084,7 @@ function piMessageEntryFingerprint(message) {
40846
41084
  const m = message;
40847
41085
  if (typeof m.role !== "string")
40848
41086
  return null;
40849
- const contentHash = createHash16("sha256").update(stableStringify(m.content)).digest("hex");
41087
+ const contentHash = createHash17("sha256").update(stableStringify(m.content)).digest("hex");
40850
41088
  return JSON.stringify([
40851
41089
  typeof m.responseId === "string" ? m.responseId : null,
40852
41090
  typeof m.timestamp === "number" || typeof m.timestamp === "string" ? m.timestamp : null,
@@ -45803,6 +46041,21 @@ function registerPiContextHandler(pi, baseOptions) {
45803
46041
  });
45804
46042
  }
45805
46043
  }
46044
+ if (options.autoSearch && !options.autoSearch.enabled && !options.compactionOff && result.prefixMutationAllowed) {
46045
+ await runAutoSearchHintForPi({
46046
+ sessionId,
46047
+ db: options.db,
46048
+ messages: outputMessages,
46049
+ entryIds: strictEntryIds,
46050
+ entryIdByRef: result.postCommitEntryIdByRef,
46051
+ options: {
46052
+ enabled: false,
46053
+ scoreThreshold: options.autoSearch.scoreThreshold,
46054
+ minPromptChars: options.autoSearch.minPromptChars,
46055
+ projectPath: projectIdentity
46056
+ }
46057
+ });
46058
+ }
45806
46059
  logTransformTiming(sessionId, "autoSearch", tAutoSearch);
45807
46060
  const tTodoCapture = performance.now();
45808
46061
  const injectTodo = () => {
@@ -47521,9 +47774,11 @@ async function runPipeline(args) {
47521
47774
  afterFallbackAdoptionForTests?.(args.stableIdSchemeCutover === true);
47522
47775
  const textIdentityPlan = buildPiTextIdentityPlan(args.db, args.sessionId, args.tagger, transcript, args.reusableMessageIds);
47523
47776
  const tTag = performance.now();
47777
+ const strippedSubagentThinking = args.sessionMeta.isSubagent && (!thinkingRecovery.restore || rewritingSignedPrefix) ? frozenBindingEntryIds(args.db, args.sessionId) : new Set;
47524
47778
  const mutationView = transcript.messages.map((message) => ({
47525
47779
  ...message,
47526
- parts: message.parts
47780
+ parts: message.parts,
47781
+ requiresToolArcSkeleton: strippedSubagentThinking.has(message.info.id ?? "") ? false : message.requiresToolArcSkeleton
47527
47782
  }));
47528
47783
  const recoveryNormalized = !!args.recoveryPrefix && (isCacheBustingPass || identityRebuild);
47529
47784
  const taggingView = args.recoveryPrefix && !recoveryNormalized ? mutationView.filter((message) => !args.recoveryPrefix?.untaggedInputIds.has(message.info.id ?? "")) : mutationView;
@@ -47659,6 +47914,31 @@ async function runPipeline(args) {
47659
47914
  }
47660
47915
  }
47661
47916
  logTransformTiming(args.sessionId, "convertLegacyToolSkeletons", tLegacyToolConversion);
47917
+ if (args.sessionMeta.isSubagent && isCacheBustingPass && !protectedSignedPrefix && !args.compactionOff) {
47918
+ const savedRemovalInputs = nativeRemovalInputs;
47919
+ try {
47920
+ nativeRemovalInputs = savedRemovalInputs && new Map(savedRemovalInputs);
47921
+ const converted = args.db.transaction(() => removalBatch((flush) => {
47922
+ const conversions = prepareAgedToolSkeletonConversions(args.db, args.sessionId, newTargets, {
47923
+ prepareRemovals: (rows) => preparePiToolRemovalChecks({
47924
+ db: args.db,
47925
+ rows,
47926
+ targets: newTargets,
47927
+ messages: args.messages,
47928
+ prepare: transcript.prepareToolRemovalMeasurements
47929
+ })
47930
+ });
47931
+ conversions.persist(args.db);
47932
+ flush();
47933
+ return conversions.converted.size;
47934
+ })).immediate();
47935
+ if (converted > 0)
47936
+ recordFirstApplicationWireEdit(true);
47937
+ } catch (error) {
47938
+ nativeRemovalInputs = savedRemovalInputs;
47939
+ throw error;
47940
+ }
47941
+ }
47662
47942
  try {
47663
47943
  if (!args.sessionMeta.isSubagent) {
47664
47944
  const hasRecentCommit = detectRecentCommit(args.messages);
@@ -48175,6 +48455,13 @@ async function runPipeline(args) {
48175
48455
  const tTranscriptCommit = performance.now();
48176
48456
  transcript.commit();
48177
48457
  logTransformTiming(args.sessionId, "transcriptCommit", tTranscriptCommit);
48458
+ if (applyNativeResponseTagReplayPi({
48459
+ db: args.db,
48460
+ sessionId: args.sessionId,
48461
+ messages: args.messages,
48462
+ canApply: isCacheBustingPass
48463
+ }) > 0)
48464
+ recordFirstApplicationWireEdit(true);
48178
48465
  let nativeInputs;
48179
48466
  let nativeReasoningIds;
48180
48467
  try {