@cortexkit/opencode-magic-context 0.49.9 → 0.49.11

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 (109) hide show
  1. package/dist/auto-search-worker.js +3 -3
  2. package/dist/{conflict-warning-hook-w3crzrar.js → conflict-warning-hook-xwkfncav.js} +3 -3
  3. package/dist/{context-ey3ap3cc.js → context-twz3s0cg.js} +220 -43
  4. package/dist/{embedding-backfill-3h2m5n0q.js → embedding-backfill-fjbfh1dt.js} +3 -3
  5. package/dist/features/magic-context/compartment-chunk-embedding.d.ts +12 -1
  6. package/dist/features/magic-context/compartment-chunk-embedding.d.ts.map +1 -1
  7. package/dist/features/magic-context/dreamer/task-scheduler.d.ts.map +1 -1
  8. package/dist/features/magic-context/memory-enabled.d.ts +5 -0
  9. package/dist/features/magic-context/memory-enabled.d.ts.map +1 -0
  10. package/dist/features/magic-context/search-pool-fixture.d.ts +39 -0
  11. package/dist/features/magic-context/search-pool-fixture.d.ts.map +1 -0
  12. package/dist/features/magic-context/search.d.ts.map +1 -1
  13. package/dist/features/magic-context/transform-decision-log.d.ts +57 -2
  14. package/dist/features/magic-context/transform-decision-log.d.ts.map +1 -1
  15. package/dist/hooks/magic-context/compartment-prompt.d.ts.map +1 -1
  16. package/dist/hooks/magic-context/compartment-runner-incremental.d.ts.map +1 -1
  17. package/dist/hooks/magic-context/historian-prompt-fit.d.ts +12 -2
  18. package/dist/hooks/magic-context/historian-prompt-fit.d.ts.map +1 -1
  19. package/dist/hooks/magic-context/hook.d.ts.map +1 -1
  20. package/dist/hooks/magic-context/producer-window-guard.d.ts.map +1 -1
  21. package/dist/hooks/magic-context/read-session-db.d.ts +5 -0
  22. package/dist/hooks/magic-context/read-session-db.d.ts.map +1 -1
  23. package/dist/hooks/magic-context/render-options.d.ts +21 -0
  24. package/dist/hooks/magic-context/render-options.d.ts.map +1 -0
  25. package/dist/hooks/magic-context/system-prompt-hash.d.ts.map +1 -1
  26. package/dist/hooks/magic-context/tag-messages.d.ts +4 -0
  27. package/dist/hooks/magic-context/tag-messages.d.ts.map +1 -1
  28. package/dist/hooks/magic-context/transform.d.ts +1 -7
  29. package/dist/hooks/magic-context/transform.d.ts.map +1 -1
  30. package/dist/{index-pgy3h49n.js → index-0abg88h2.js} +1 -1
  31. package/dist/{index-0x9cn9w1.js → index-0j6crjgh.js} +2 -2
  32. package/dist/{index-a43xq1pg.js → index-4ccdr7yw.js} +1 -1
  33. package/dist/{index-4hb8nt93.js → index-4jkhhpn1.js} +1 -1
  34. package/dist/{index-ffa8x2as.js → index-84j7jq8a.js} +13 -8
  35. package/dist/{index-7bjgyaj1.js → index-9159kk15.js} +238 -130
  36. package/dist/{index-q76br5zn.js → index-bzp9s8z2.js} +24 -19
  37. package/dist/{index-21919gcq.js → index-g40wgxxt.js} +3 -3
  38. package/dist/{index-x57ep4fp.js → index-hqnggmxn.js} +215 -75
  39. package/dist/{index-6k86es2p.js → index-kkvxnbt8.js} +6 -6
  40. package/dist/{index-nenz4gpb.js → index-q3qck7j2.js} +4 -4
  41. package/dist/{index-wpwpn7nj.js → index-qr1mkc2y.js} +1 -1
  42. package/dist/{index-rg1cezmj.js → index-se1w3v2m.js} +1 -1
  43. package/dist/{index-swgpe402.js → index-xztdf9t7.js} +1 -1
  44. package/dist/{index-16vwdyy5.js → index-yhrrx7qa.js} +1 -1
  45. package/dist/{index-3403gbzj.js → index-z7avx6rw.js} +100 -38
  46. package/dist/index.js +27 -34
  47. package/dist/{message-index-bounded-fskdyc81.js → message-index-bounded-0rbbg9rd.js} +4 -4
  48. package/dist/{message-index-6r1x9cqh.js → message-index-ct5x2kwa.js} +4 -4
  49. package/dist/migration-worker.js +1 -1
  50. package/dist/plugin/dream-timer.d.ts.map +1 -1
  51. package/dist/plugin/hooks/create-session-hooks.d.ts.map +1 -1
  52. package/dist/{project-embedding-registry-vy7sv9jt.js → project-embedding-registry-ft9gh2e2.js} +2 -2
  53. package/dist/raw-ordinal-warmup-worker.js +2 -2
  54. package/dist/{read-session-chunk-zgpvs423.js → read-session-chunk-y3hhsbzw.js} +2 -2
  55. package/dist/{recomp-orchestrator-77xc8wpe.js → recomp-orchestrator-67k45s0b.js} +11 -11
  56. package/dist/{search-72fkjwk2.js → search-jd8xh721.js} +8 -8
  57. package/dist/{send-session-notification-q8ngbap3.js → send-session-notification-vzhj8bsg.js} +2 -2
  58. package/dist/shared/prompt-surface-runtime.d.ts +5 -0
  59. package/dist/shared/prompt-surface-runtime.d.ts.map +1 -1
  60. package/dist/{transform-postprocess-phase-r8d406j0.js → transform-postprocess-phase-pmqxfq4q.js} +11 -11
  61. package/dist/v2/auto-search-worker.js +3 -3
  62. package/dist/v2/{context-z2yagwy4.js → context-p1zfcw41.js} +599 -225
  63. package/dist/v2/{embedding-backfill-vr7wdtrf.js → embedding-backfill-xcw3t6hp.js} +5 -5
  64. package/dist/v2/embedding-worker.js +2 -2
  65. package/dist/v2/hooks/context.d.ts.map +1 -1
  66. package/dist/v2/hooks/dream-manual.d.ts +1 -0
  67. package/dist/v2/hooks/dream-manual.d.ts.map +1 -1
  68. package/dist/v2/hooks/dream-timer.d.ts +3 -1
  69. package/dist/v2/hooks/dream-timer.d.ts.map +1 -1
  70. package/dist/v2/hooks/dream-trigger.d.ts +5 -0
  71. package/dist/v2/hooks/dream-trigger.d.ts.map +1 -1
  72. package/dist/v2/hooks/payload.d.ts +1 -1
  73. package/dist/v2/hooks/payload.d.ts.map +1 -1
  74. package/dist/v2/hooks/transform-decision-binding.d.ts +15 -0
  75. package/dist/v2/hooks/transform-decision-binding.d.ts.map +1 -0
  76. package/dist/v2/hooks/transform-features.d.ts +39 -0
  77. package/dist/v2/hooks/transform-features.d.ts.map +1 -0
  78. package/dist/v2/{message-index-bounded-rqc603f2.js → message-index-bounded-7wcbp975.js} +5 -5
  79. package/dist/v2/{message-index-9ezq6wze.js → message-index-cjhv92m2.js} +5 -5
  80. package/dist/v2/migration-worker.js +1 -1
  81. package/dist/v2/{project-embedding-registry-ja23aygk.js → project-embedding-registry-g34gcf74.js} +6 -4
  82. package/dist/v2/raw-ordinal-warmup-worker.js +2 -2
  83. package/dist/v2/{read-session-chunk-7f87tg2q.js → read-session-chunk-8d3v87vr.js} +3 -3
  84. package/dist/v2/{recomp-orchestrator-s5tdpsbs.js → recomp-orchestrator-n0pq36f0.js} +13 -13
  85. package/dist/v2/{search-2td1b1wy.js → search-a1acjwf8.js} +10 -10
  86. package/dist/v2/{send-session-notification-6n7chhyp.js → send-session-notification-z5mcjdea.js} +2 -2
  87. package/dist/v2/{server-4qr18rfg.js → server-5x7kmyz8.js} +1 -1
  88. package/dist/v2/{server-c9w52qss.js → server-7fvmt15t.js} +109 -38
  89. package/dist/v2/{server-44ryn9rb.js → server-83d71zab.js} +1 -1
  90. package/dist/v2/{server-z0rjemg1.js → server-d3f4g62c.js} +2 -2
  91. package/dist/v2/{server-zrwaj29a.js → server-d6t16r89.js} +24 -19
  92. package/dist/v2/{server-23znwjqk.js → server-erfp0xb6.js} +5 -2
  93. package/dist/v2/{server-9a6bwc12.js → server-ewqshbs8.js} +251 -131
  94. package/dist/v2/{server-ak7w74j9.js → server-h3wc20sv.js} +1 -1
  95. package/dist/v2/{server-7e087rvk.js → server-jc8v585p.js} +1 -1
  96. package/dist/v2/{server-4zwx20yg.js → server-kn7skz9r.js} +1 -1
  97. package/dist/v2/{server-2hxypdx5.js → server-pbpp8r8h.js} +13 -8
  98. package/dist/v2/{server-4rs8sm06.js → server-rxcq4t50.js} +3 -3
  99. package/dist/v2/{server-4easnf78.js → server-sg68np13.js} +13 -4
  100. package/dist/v2/{server-gc8x2xdb.js → server-wkhfyzpg.js} +2 -2
  101. package/dist/v2/server.js +4 -4
  102. package/dist/v2/store-reader.d.ts +4 -0
  103. package/dist/v2/store-reader.d.ts.map +1 -1
  104. package/dist/v2/{wrapup-orchestrator-wg8dmmm9.js → wrapup-orchestrator-87q9d5e2.js} +13 -13
  105. package/dist/{wrapup-orchestrator-b1z99yg5.js → wrapup-orchestrator-jqapepw0.js} +12 -12
  106. package/package.json +1 -1
  107. package/src/shared/chunk-vector-writer-guard.test.ts +72 -0
  108. package/src/shared/prompt-surface-runtime.test.ts +15 -0
  109. package/src/shared/prompt-surface-runtime.ts +12 -0
@@ -9,7 +9,7 @@ import {
9
9
  resolveLegacyConfigSources,
10
10
  getProtectedTokensTierOverrides,
11
11
  loadPluginConfigDetailed
12
- } from "./server-4qr18rfg.js";
12
+ } from "./server-5x7kmyz8.js";
13
13
  import {
14
14
  getHarness2,
15
15
  harnessOwnsOpenCodeStore2
@@ -38,6 +38,7 @@ import {
38
38
  getModelsDevCacheState
39
39
  } from "./server-nveratm5.js";
40
40
  import {
41
+ isValidLanguageCode,
41
42
  withContentLanguageDirective,
42
43
  parseCron,
43
44
  nextOccurrence,
@@ -48,7 +49,7 @@ import {
48
49
  DEFAULT_HISTORIAN_TIMEOUT_MS,
49
50
  DEFAULT_LOCAL_EMBEDDING_MODEL,
50
51
  DREAM_TASK_PROMOTION_DEFAULTS
51
- } from "./server-7e087rvk.js";
52
+ } from "./server-jc8v585p.js";
52
53
  import {
53
54
  historianRunConfig,
54
55
  dreamerRunConfig,
@@ -57,8 +58,11 @@ import {
57
58
  withLiveDreamerOutputCap,
58
59
  embedPauseBySession,
59
60
  embedRunStateBySession,
61
+ autoEmbedAttemptedBySession,
62
+ autoEmbedIdentityBySession,
60
63
  invalidateAutoEmbedSession,
61
64
  getEmbedDrainUiStatus,
65
+ clearEmbedSessionState,
62
66
  acquireCompartmentLease,
63
67
  releaseCompartmentLeaseBestEffort,
64
68
  isCompartmentLeaseHeld,
@@ -201,12 +205,13 @@ import {
201
205
  createPromptAsyncTransport,
202
206
  CTX_NOTE_LIGHT_DESCRIPTION,
203
207
  ACTIVE_TOOL_IDS,
204
- promptSurfaceHashMaterial,
208
+ systemPromptFingerprint,
205
209
  createPromptSurfaceRuntime,
206
210
  createPromptSurfaceGuidanceEpochCache,
207
211
  MARKER_SUMMARY_TEXT,
208
212
  markerUpdateDefinitelyDidNotCut,
209
213
  applyDeferredCompactionMarker,
214
+ isProjectMemoryEnabled,
210
215
  teardownChildSession,
211
216
  runTokenLog,
212
217
  formatRunTokenLog,
@@ -265,7 +270,7 @@ import {
265
270
  startCompartmentAgent,
266
271
  setRecompStarting2,
267
272
  setRecompTerminal2
268
- } from "./server-c9w52qss.js";
273
+ } from "./server-7fvmt15t.js";
269
274
  import {
270
275
  CANONICAL_DREAM_TASKS,
271
276
  DREAM_TASK_CAPABILITIES,
@@ -296,6 +301,7 @@ import {
296
301
  getMigrationOnOpenRefusal,
297
302
  LATEST_SUPPORTED_VERSION,
298
303
  BOOT_SQLITE_BUSY_TIMEOUT_MS,
304
+ getDatabasePath,
299
305
  getPersistedSchemaVersion,
300
306
  runSqliteOptimize,
301
307
  openDatabase,
@@ -303,7 +309,7 @@ import {
303
309
  openDatabaseAsync,
304
310
  isDatabasePersisted,
305
311
  getDatabasePersistenceError
306
- } from "./server-23znwjqk.js";
312
+ } from "./server-erfp0xb6.js";
307
313
  import {
308
314
  setHomeProjectPermission,
309
315
  shouldSkipHomeProjectMemory,
@@ -506,7 +512,7 @@ import {
506
512
  readRawSessionMessageById2,
507
513
  readSessionChunk2,
508
514
  readRawSessionSeedTail2
509
- } from "./server-gc8x2xdb.js";
515
+ } from "./server-wkhfyzpg.js";
510
516
  import {
511
517
  textMentionsRecentCommit,
512
518
  hasMeaningfulUserText2,
@@ -543,7 +549,7 @@ import {
543
549
  import"./server-63ha7f0f.js";
544
550
  import {
545
551
  deleteChunkEmbedBackoffForSession
546
- } from "./server-9a6bwc12.js";
552
+ } from "./server-ewqshbs8.js";
547
553
  import {
548
554
  registerOwnRpcServerInstance,
549
555
  rpcPortDir,
@@ -569,7 +575,7 @@ import {
569
575
  isMessageIndexReconciledThrough2,
570
576
  indexMessagesAfterOrdinal2,
571
577
  sweepOrphanedOpenCodeMessageIndexes2
572
- } from "./server-z0rjemg1.js";
578
+ } from "./server-d3f4g62c.js";
573
579
  import {
574
580
  stableStringify,
575
581
  getTemporalDecisions,
@@ -691,7 +697,7 @@ import {
691
697
  latestRealUserTurnIdFromOpenCodeDb,
692
698
  getMessageTimesFromOpenCodeDb,
693
699
  findLastAssistantModelFromOpenCodeDb
694
- } from "./server-zrwaj29a.js";
700
+ } from "./server-d6t16r89.js";
695
701
  import {
696
702
  getCurrentToolSetHash,
697
703
  recordToolDefinition,
@@ -735,9 +741,12 @@ import {
735
741
  embedUnembeddedMemoriesForProjectOutcome2,
736
742
  drainCommitBacklogForProject2,
737
743
  embedSessionCompartmentChunks2,
738
- getEmbeddingCoverageStatus2
739
- } from "./server-4easnf78.js";
740
- import"./server-fb3zxn06.js";
744
+ getEmbeddingCoverageStatus2,
745
+ getAutoEmbeddingSessionCoverage2
746
+ } from "./server-sg68np13.js";
747
+ import {
748
+ configureContextDatabasePragmas2
749
+ } from "./server-fb3zxn06.js";
741
750
  import {
742
751
  SESSION_NOTE_CONDITION_ERROR,
743
752
  getNoteByIdInScope,
@@ -780,7 +789,7 @@ import {
780
789
  readGitFileChangeTimesSince,
781
790
  verificationFileExists,
782
791
  normalizeVerificationFiles
783
- } from "./server-4zwx20yg.js";
792
+ } from "./server-kn7skz9r.js";
784
793
  import {
785
794
  deriveTriggerBudget2,
786
795
  deriveHistorianChunkTokens2,
@@ -799,10 +808,10 @@ import {
799
808
  } from "./server-4dhv7mqz.js";
800
809
  import {
801
810
  getLocalEmbeddingNativeMemoryStats
802
- } from "./server-44ryn9rb.js";
811
+ } from "./server-83d71zab.js";
803
812
  import {
804
813
  cosineSimilarity
805
- } from "./server-4rs8sm06.js";
814
+ } from "./server-rxcq4t50.js";
806
815
  import {
807
816
  computeCueContentHash,
808
817
  hasMuralCueColumns,
@@ -839,7 +848,7 @@ import"./server-ckrb5rm8.js";
839
848
  import {
840
849
  flushIgnoredMessages2,
841
850
  sendStatusNotification2
842
- } from "./server-ak7w74j9.js";
851
+ } from "./server-h3wc20sv.js";
843
852
  import {
844
853
  renderSingleStoreMigrationRequiredRefusal,
845
854
  SingleStoreMigrationRequiredError,
@@ -860,7 +869,7 @@ import {
860
869
  resolveMemoriesByIdsForSearch2,
861
870
  unifiedSearch2,
862
871
  formatSearchResults2
863
- } from "./server-2hxypdx5.js";
872
+ } from "./server-pbpp8r8h.js";
864
873
  import {
865
874
  resolvePromptContext2
866
875
  } from "./server-fmsr7v69.js";
@@ -2416,6 +2425,275 @@ function createTagger() {
2416
2425
  };
2417
2426
  }
2418
2427
 
2428
+ // src/features/magic-context/transform-decision-log.ts
2429
+ var TRANSFORM_DECISIONS_RETENTION = 2000;
2430
+ var canonicalReasons = new Set([
2431
+ "system_hash",
2432
+ "model_change",
2433
+ "project_memory_epoch",
2434
+ "ttl_idle",
2435
+ "explicit_flush",
2436
+ "user_flush",
2437
+ "fit_retry",
2438
+ "pending_materialization",
2439
+ "variant_change",
2440
+ "recomp",
2441
+ "boundary_repair",
2442
+ "host_history_change",
2443
+ "thinking_hold",
2444
+ "mutation_drift",
2445
+ "max_mutation_id",
2446
+ "first_render",
2447
+ "pressure_refold",
2448
+ "upgrade_state",
2449
+ "cached_m1_missing",
2450
+ "project_change",
2451
+ "compartment_render_epoch",
2452
+ "m1_delta",
2453
+ "ttl_expiry",
2454
+ "epoch_change",
2455
+ "coverage_fold",
2456
+ "profile_transition",
2457
+ "host_compaction",
2458
+ "tag_identity_repair"
2459
+ ]);
2460
+ var piReasonAliases = {
2461
+ project_memory_change: "project_memory_epoch",
2462
+ pending_mutations: "max_mutation_id",
2463
+ renderer_upgrade: "upgrade_state",
2464
+ cache_invalid: "cached_m1_missing",
2465
+ drift: "pressure_refold"
2466
+ };
2467
+ var sharedReasonAliases = {
2468
+ model_key: "model_change",
2469
+ pressure: "pressure_refold"
2470
+ };
2471
+ var pendingDecisionBySession = new Map;
2472
+ var pendingPiDecisionBySession = new Map;
2473
+ var lastBoundMessageIdBySession = new Map;
2474
+ var scheduledWriteTokensBySession = new Map;
2475
+ var systemHashChangedSessions = new Set;
2476
+ var piSystemHashChangedSessions = new Set;
2477
+ var unbustedPassBySession = new Map;
2478
+ var newestInputAssistantBySession = new Map;
2479
+ var stagedV2DecisionBySession = new Map;
2480
+ var writerOverrideForTests = null;
2481
+ var retentionOverrideForTests = null;
2482
+ function normalizeMaterializeReason(harness, reason, rematerialized) {
2483
+ const raw = typeof reason === "string" ? reason.trim() : "";
2484
+ if (raw.length > 0) {
2485
+ const alias = sharedReasonAliases[raw] ?? (harness === "pi" ? piReasonAliases[raw] : undefined) ?? undefined;
2486
+ if (alias)
2487
+ return alias;
2488
+ if (canonicalReasons.has(raw))
2489
+ return raw;
2490
+ return null;
2491
+ }
2492
+ return rematerialized ? "pressure_refold" : null;
2493
+ }
2494
+ function writeRustTransformDecision(args) {
2495
+ const rawDecision = args.decision.trim();
2496
+ const decisionUpper = rawDecision.toUpperCase();
2497
+ const mapped = decisionUpper === "HARD" || decisionUpper === "MIGRATE_HARD" ? { decision: "execute", materialized: true, bustedThisPass: true } : decisionUpper === "SOFT" || decisionUpper === "EXECUTE" || args.materializeReason === "ttl_idle" ? { decision: "execute", materialized: false, bustedThisPass: true } : decisionUpper === "SOFT+" ? { decision: "defer", materialized: false, bustedThisPass: false } : {
2498
+ decision: rawDecision.toLowerCase() || "unknown",
2499
+ materialized: false,
2500
+ bustedThisPass: false
2501
+ };
2502
+ pendingDecisionBySession.set(args.sessionId, {
2503
+ tsMs: args.tsMs ?? Date.now(),
2504
+ decision: mapped.decision,
2505
+ materialized: mapped.materialized,
2506
+ materializeReason: args.materializeReason,
2507
+ systemHashPrev: null,
2508
+ systemHashNew: null,
2509
+ m0ModelKeyPrev: null,
2510
+ m0ModelKeyNew: null,
2511
+ m0ToolSetHashPrev: null,
2512
+ m0ToolSetHashNew: null,
2513
+ emergency: false,
2514
+ droppedTokens: 0,
2515
+ droppedCount: 0,
2516
+ inputTokens: args.inputTokens,
2517
+ bustedThisPass: mapped.bustedThisPass,
2518
+ lkgFrozenReleaseReason: args.lkgFrozenReleaseReason
2519
+ });
2520
+ }
2521
+ function clearOpenCodePendingTransformDecision(sessionId, inputMessages) {
2522
+ pendingDecisionBySession.delete(sessionId);
2523
+ unbustedPassBySession.delete(sessionId);
2524
+ if (!inputMessages)
2525
+ return;
2526
+ let newestAssistant = "";
2527
+ for (const message of inputMessages) {
2528
+ const id = message.info?.id;
2529
+ if (message.info?.role !== "assistant" || typeof id !== "string")
2530
+ continue;
2531
+ if (id > newestAssistant)
2532
+ newestAssistant = id;
2533
+ }
2534
+ newestInputAssistantBySession.set(sessionId, newestAssistant);
2535
+ }
2536
+ function noteSystemPromptHashChange(sessionId) {
2537
+ systemHashChangedSessions.add(sessionId);
2538
+ }
2539
+ function noteOpenCodeUnbustedPass(sessionId, decision) {
2540
+ unbustedPassBySession.set(sessionId, decision);
2541
+ }
2542
+ var IDLE_EXPIRY_REASONS = new Set([
2543
+ "ttl_idle",
2544
+ "ttl_expiry"
2545
+ ]);
2546
+ function withSystemHashReason(decision) {
2547
+ if (IDLE_EXPIRY_REASONS.has(decision.materializeReason))
2548
+ return decision;
2549
+ return { ...decision, materializeReason: "system_hash" };
2550
+ }
2551
+ function unknownPassDecision() {
2552
+ return {
2553
+ tsMs: Date.now(),
2554
+ decision: "unknown",
2555
+ materialized: false,
2556
+ materializeReason: null,
2557
+ systemHashPrev: null,
2558
+ systemHashNew: null,
2559
+ m0ModelKeyPrev: null,
2560
+ m0ModelKeyNew: null,
2561
+ emergency: false,
2562
+ droppedTokens: 0,
2563
+ droppedCount: 0,
2564
+ inputTokens: 0,
2565
+ bustedThisPass: false
2566
+ };
2567
+ }
2568
+ function takeOpenCodeDecisionForBinding(sessionId, applySystemHashChange) {
2569
+ const pending = pendingDecisionBySession.get(sessionId);
2570
+ const unbusted = unbustedPassBySession.get(sessionId);
2571
+ pendingDecisionBySession.delete(sessionId);
2572
+ unbustedPassBySession.delete(sessionId);
2573
+ if (!applySystemHashChange || !systemHashChangedSessions.has(sessionId))
2574
+ return pending;
2575
+ systemHashChangedSessions.delete(sessionId);
2576
+ return withSystemHashReason(pending ?? unbusted ?? unknownPassDecision());
2577
+ }
2578
+ function recordPendingTransformDecision(sessionId, decision) {
2579
+ if (!decision.bustedThisPass) {
2580
+ pendingDecisionBySession.delete(sessionId);
2581
+ return;
2582
+ }
2583
+ pendingDecisionBySession.set(sessionId, decision);
2584
+ }
2585
+ function stageOpenCodeV2TransformDecision(args) {
2586
+ const systemHashChanged = systemHashChangedSessions.has(args.sessionId);
2587
+ const decision = takeOpenCodeDecisionForBinding(args.sessionId, true);
2588
+ stagedV2DecisionBySession.delete(args.sessionId);
2589
+ if (!decision || args.responseAfterSequence === undefined)
2590
+ return false;
2591
+ if (!decision.bustedThisPass && !systemHashChanged)
2592
+ return false;
2593
+ stagedV2DecisionBySession.set(args.sessionId, {
2594
+ decision,
2595
+ responseAfterSequence: args.responseAfterSequence
2596
+ });
2597
+ return true;
2598
+ }
2599
+ function bindOpenCodeV2TransformDecision(args) {
2600
+ const staged = stagedV2DecisionBySession.get(args.sessionId);
2601
+ if (!staged)
2602
+ return false;
2603
+ const reply = args.firstAssistantAfter(staged.responseAfterSequence);
2604
+ if (!reply || reply.state === "running") {
2605
+ if (args.passStarting)
2606
+ stagedV2DecisionBySession.delete(args.sessionId);
2607
+ return false;
2608
+ }
2609
+ stagedV2DecisionBySession.delete(args.sessionId);
2610
+ if (reply.state === "failed")
2611
+ return false;
2612
+ const dbPath = getDatabasePath(args.db);
2613
+ if (!dbPath)
2614
+ return false;
2615
+ const token = addScheduledWriteToken(args.sessionId);
2616
+ inRootAsyncContext2(() => setTimeout(() => {
2617
+ try {
2618
+ if (!hasScheduledWriteToken(args.sessionId, token))
2619
+ return;
2620
+ writeTransformDecisionBestEffort(dbPath, {
2621
+ ...staged.decision,
2622
+ sessionId: args.sessionId,
2623
+ harness: "opencode2",
2624
+ messageId: reply.id,
2625
+ inputTokens: Number.isFinite(reply.inputTokens) ? reply.inputTokens : staged.decision.inputTokens
2626
+ });
2627
+ } finally {
2628
+ deleteScheduledWriteToken(args.sessionId, token);
2629
+ }
2630
+ }, 0));
2631
+ return true;
2632
+ }
2633
+ function addScheduledWriteToken(sessionId) {
2634
+ const token = Symbol(sessionId);
2635
+ let tokens = scheduledWriteTokensBySession.get(sessionId);
2636
+ if (!tokens) {
2637
+ tokens = new Set;
2638
+ scheduledWriteTokensBySession.set(sessionId, tokens);
2639
+ }
2640
+ tokens.add(token);
2641
+ return token;
2642
+ }
2643
+ function hasScheduledWriteToken(sessionId, token) {
2644
+ return scheduledWriteTokensBySession.get(sessionId)?.has(token) === true;
2645
+ }
2646
+ function deleteScheduledWriteToken(sessionId, token) {
2647
+ const tokens = scheduledWriteTokensBySession.get(sessionId);
2648
+ if (!tokens)
2649
+ return;
2650
+ tokens.delete(token);
2651
+ if (tokens.size === 0)
2652
+ scheduledWriteTokensBySession.delete(sessionId);
2653
+ }
2654
+ function writeTransformDecisionBestEffort(dbPath, row) {
2655
+ try {
2656
+ const writer = writerOverrideForTests ?? writeTransformDecisionRow;
2657
+ writer(dbPath, row);
2658
+ } catch {}
2659
+ }
2660
+ function writeTransformDecisionRow(dbPath, row) {
2661
+ const db = new Database2(dbPath);
2662
+ try {
2663
+ db.exec("PRAGMA busy_timeout=0");
2664
+ configureContextDatabasePragmas2(db);
2665
+ writeTransformDecisionRowOnDatabase(db, row, true);
2666
+ } finally {
2667
+ closeQuietly(db);
2668
+ }
2669
+ }
2670
+ function writeTransformDecisionRowOnDatabase(db, row, configureBusyTimeout) {
2671
+ if (configureBusyTimeout)
2672
+ db.exec("PRAGMA busy_timeout=0");
2673
+ const systemHashPrev = row.materialized ? row.systemHashPrev : null;
2674
+ const systemHashNew = row.materialized ? row.systemHashNew : null;
2675
+ const m0ModelKeyPrev = row.materialized ? row.m0ModelKeyPrev : null;
2676
+ const m0ModelKeyNew = row.materialized ? row.m0ModelKeyNew : null;
2677
+ const m0ToolSetHashPrev = row.m0ToolSetHashPrev ?? null;
2678
+ const m0ToolSetHashNew = row.m0ToolSetHashNew ?? null;
2679
+ const persistedMaterializeReason = row.lkgFrozenReleaseReason ? `lkg_frozen_release:${row.lkgFrozenReleaseReason}` + (row.materializeReason ? `;materialize_reason=${row.materializeReason}` : "") : row.materializeReason;
2680
+ db.prepare(`INSERT OR REPLACE INTO transform_decisions (
2681
+ session_id, harness, message_id, ts_ms, decision, materialized,
2682
+ materialize_reason, system_hash_prev, system_hash_new,
2683
+ m0_tool_set_hash_prev, m0_tool_set_hash_new,
2684
+ m0_model_key_prev, m0_model_key_new, emergency, dropped_tokens,
2685
+ dropped_count, input_tokens
2686
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(row.sessionId, row.harness, row.messageId, row.tsMs, row.decision, row.materialized ? 1 : 0, persistedMaterializeReason, systemHashPrev, systemHashNew, m0ToolSetHashPrev, m0ToolSetHashNew, 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)));
2687
+ db.prepare(`DELETE FROM transform_decisions
2688
+ WHERE session_id = ? AND harness = ?
2689
+ AND rowid NOT IN (
2690
+ SELECT rowid FROM transform_decisions
2691
+ WHERE session_id = ? AND harness = ?
2692
+ ORDER BY ts_ms DESC, rowid DESC
2693
+ LIMIT ?
2694
+ )`).run(row.sessionId, row.harness, row.sessionId, row.harness, retentionOverrideForTests ?? TRANSFORM_DECISIONS_RETENTION);
2695
+ }
2696
+
2419
2697
  // src/hooks/magic-context/ctx-reduce-availability.ts
2420
2698
  var ctxReduceRegisteredGlobally = true;
2421
2699
  function setCtxReduceRegisteredGlobally(registered) {
@@ -3628,6 +3906,12 @@ function applyUltraAbbreviationsUnicode(text) {
3628
3906
  return working;
3629
3907
  }
3630
3908
  var CURRENT_CAVEMAN_RULES = "unicode-v2";
3909
+ function cavemanWordRulesForLanguage(language) {
3910
+ const code = typeof language === "string" ? language.trim().toLowerCase() : "";
3911
+ if (code === "en" || code.startsWith("en-"))
3912
+ return "english";
3913
+ return isValidLanguageCode(code) ? "none" : "english";
3914
+ }
3631
3915
  function cavemanCompress(text, level, rules = CURRENT_CAVEMAN_RULES, wordRules = "english") {
3632
3916
  if (text.length === 0)
3633
3917
  return text;
@@ -6494,6 +6778,36 @@ function createModuleToolBackends(options) {
6494
6778
  };
6495
6779
  }
6496
6780
 
6781
+ // src/hooks/magic-context/render-options.ts
6782
+ function createM0RenderOptions(controls, contextUsage, modelKey, resolvedContextLimit, projectPath) {
6783
+ return {
6784
+ projectPath: controls.memoryConfig?.enabled ? projectPath : undefined,
6785
+ memoryEnabled: controls.memoryConfig?.enabled,
6786
+ memoryInjectionBudgetTokens: controls.memoryConfig?.injectionBudgetTokens,
6787
+ injectDocs: controls.injectDocs,
6788
+ muralEnabled: controls.muralEnabled,
6789
+ temporalAwareness: controls.experimentalTemporalAwareness,
6790
+ historyBudgetTokens: resolveHistoryBudgetTokens(controls.historyBudgetPercentage, contextUsage, controls.executeThresholdPercentage, modelKey, controls.executeThresholdTokens, resolvedContextLimit),
6791
+ historyBudgetPolicyIdentity: historyBudgetPolicyIdentity(controls.historyBudgetPercentage, controls.executeThresholdPercentage, modelKey, controls.executeThresholdTokens)
6792
+ };
6793
+ }
6794
+ function resolveHistoryBudgetTokens(historyBudgetPercentage, contextUsage, executeThresholdPercentage, modelKey, executeThresholdTokens, resolvedContextLimit) {
6795
+ if (!historyBudgetPercentage)
6796
+ return;
6797
+ let contextLimit = resolvedContextLimit && resolvedContextLimit > 0 ? resolvedContextLimit : 0;
6798
+ if (contextLimit <= 0) {
6799
+ if (contextUsage.percentage <= 0)
6800
+ return;
6801
+ contextLimit = contextUsage.inputTokens / (contextUsage.percentage / 100);
6802
+ }
6803
+ if (!Number.isFinite(contextLimit) || contextLimit <= 0)
6804
+ return;
6805
+ return Math.floor(contextLimit * (resolveExecuteThreshold(executeThresholdPercentage ?? 65, modelKey, 65, {
6806
+ tokensConfig: executeThresholdTokens,
6807
+ contextLimit
6808
+ }) / 100) * historyBudgetPercentage);
6809
+ }
6810
+
6497
6811
  // src/hooks/magic-context/apply-operations.ts
6498
6812
  var RECENT_TOOL_SKELETON_WINDOW = 20;
6499
6813
  function buildReplacementContent(tagId) {
@@ -10691,9 +11005,6 @@ class StorageBusyRefusalError extends Error {
10691
11005
  }
10692
11006
  }
10693
11007
 
10694
- // src/hooks/magic-context/system-prompt-hash.ts
10695
- import { createHash } from "node:crypto";
10696
-
10697
11008
  // src/hooks/magic-context/system-prompt-dates.ts
10698
11009
  function replaceHostDates(prompt, replace) {
10699
11010
  const fields = /<(plugin-env|environment|env)>[\s\S]*?<\/\1>|Today's date: [^\r\n<]+/g;
@@ -10940,7 +11251,7 @@ function createSystemPromptHashHandler(deps) {
10940
11251
  const dates = systemPromptDates(liveSystemContent, stickyDate);
10941
11252
  const currentDate = dates.live;
10942
11253
  const stableCandidate = dates.stable;
10943
- const stableCandidateHash = createHash("md5").update(promptSurfaceHashMaterial(stableCandidate, promptSurface.preset)).digest("hex");
11254
+ const stableCandidateHash = systemPromptFingerprint(stableCandidate, promptSurface.preset);
10944
11255
  const contentOrPresetChanged = hasPersistedHash && stableCandidateHash !== previousHash;
10945
11256
  const rewritePermission = systemDateRefreshPermission(deps.historyRefreshSessions, dateRequest);
10946
11257
  let deferredDateRefresh = false;
@@ -10954,7 +11265,7 @@ function createSystemPromptHashHandler(deps) {
10954
11265
  try {
10955
11266
  const content = liveElements.join(`
10956
11267
  `);
10957
- const hash = createHash("md5").update(promptSurfaceHashMaterial(content, promptSurface.preset)).digest("hex");
11268
+ const hash = systemPromptFingerprint(content, promptSurface.preset);
10958
11269
  updateSessionMeta(deps.db, sessionId, {
10959
11270
  systemPromptHash: hash,
10960
11271
  cachedM0SystemHash: hash,
@@ -10994,7 +11305,7 @@ function createSystemPromptHashHandler(deps) {
10994
11305
  `);
10995
11306
  if (!availability.frozen || !modelKey)
10996
11307
  return;
10997
- const currentHash = createHash("md5").update(promptSurfaceHashMaterial(systemContent, promptSurface.preset)).digest("hex");
11308
+ const currentHash = systemPromptFingerprint(systemContent, promptSurface.preset);
10998
11309
  recordSystemPromptForRequest(sessionId, currentLkgRequestIdentity(sessionId), currentHash, deps.db, previousHash !== currentHash ? !deps.historyRefreshSessions.has(sessionId) : undefined, deps.historyRefreshSessions, deps.pendingMaterializationSessions);
10999
11310
  if (!sessionMetaEarly) {
11000
11311
  return;
@@ -11002,6 +11313,7 @@ function createSystemPromptHashHandler(deps) {
11002
11313
  const sessionMeta = sessionMetaEarly;
11003
11314
  if (previousHash !== "" && previousHash !== "0" && previousHash !== currentHash) {
11004
11315
  sessionLog2(sessionId, `system prompt hash changed: ${previousHash} → ${currentHash} (len=${systemContent.length}), ${idleCacheExpired ? "adopting on idle-expired request" : requestMessagesFinal ? "adopting on the request whose messages are already final" : "triggering flush"}`);
11316
+ noteSystemPromptHashChange(sessionId);
11005
11317
  if (!adoptSystemChange) {
11006
11318
  deps.historyRefreshSessions.add(sessionId);
11007
11319
  deps.systemPromptRefreshSessions.add(sessionId);
@@ -11054,102 +11366,6 @@ function createSystemPromptHashHandler(deps) {
11054
11366
  };
11055
11367
  }
11056
11368
 
11057
- // src/features/magic-context/transform-decision-log.ts
11058
- var canonicalReasons = new Set([
11059
- "system_hash",
11060
- "model_change",
11061
- "project_memory_epoch",
11062
- "ttl_idle",
11063
- "explicit_flush",
11064
- "user_flush",
11065
- "fit_retry",
11066
- "pending_materialization",
11067
- "variant_change",
11068
- "recomp",
11069
- "boundary_repair",
11070
- "host_history_change",
11071
- "thinking_hold",
11072
- "mutation_drift",
11073
- "max_mutation_id",
11074
- "first_render",
11075
- "pressure_refold",
11076
- "upgrade_state",
11077
- "cached_m1_missing",
11078
- "project_change",
11079
- "compartment_render_epoch",
11080
- "m1_delta",
11081
- "ttl_expiry",
11082
- "epoch_change",
11083
- "coverage_fold",
11084
- "profile_transition",
11085
- "host_compaction",
11086
- "tag_identity_repair"
11087
- ]);
11088
- var piReasonAliases = {
11089
- project_memory_change: "project_memory_epoch",
11090
- pending_mutations: "max_mutation_id",
11091
- renderer_upgrade: "upgrade_state",
11092
- cache_invalid: "cached_m1_missing",
11093
- drift: "pressure_refold"
11094
- };
11095
- var sharedReasonAliases = {
11096
- model_key: "model_change",
11097
- pressure: "pressure_refold"
11098
- };
11099
- var pendingDecisionBySession = new Map;
11100
- var pendingPiDecisionBySession = new Map;
11101
- var lastBoundMessageIdBySession = new Map;
11102
- var scheduledWriteTokensBySession = new Map;
11103
- function normalizeMaterializeReason(harness, reason, rematerialized) {
11104
- const raw = typeof reason === "string" ? reason.trim() : "";
11105
- if (raw.length > 0) {
11106
- const alias = sharedReasonAliases[raw] ?? (harness === "pi" ? piReasonAliases[raw] : undefined) ?? undefined;
11107
- if (alias)
11108
- return alias;
11109
- if (canonicalReasons.has(raw))
11110
- return raw;
11111
- return null;
11112
- }
11113
- return rematerialized ? "pressure_refold" : null;
11114
- }
11115
- function writeRustTransformDecision(args) {
11116
- const rawDecision = args.decision.trim();
11117
- const decisionUpper = rawDecision.toUpperCase();
11118
- const mapped = decisionUpper === "HARD" || decisionUpper === "MIGRATE_HARD" ? { decision: "execute", materialized: true, bustedThisPass: true } : decisionUpper === "SOFT" || decisionUpper === "EXECUTE" || args.materializeReason === "ttl_idle" ? { decision: "execute", materialized: false, bustedThisPass: true } : decisionUpper === "SOFT+" ? { decision: "defer", materialized: false, bustedThisPass: false } : {
11119
- decision: rawDecision.toLowerCase() || "unknown",
11120
- materialized: false,
11121
- bustedThisPass: false
11122
- };
11123
- pendingDecisionBySession.set(args.sessionId, {
11124
- tsMs: args.tsMs ?? Date.now(),
11125
- decision: mapped.decision,
11126
- materialized: mapped.materialized,
11127
- materializeReason: args.materializeReason,
11128
- systemHashPrev: null,
11129
- systemHashNew: null,
11130
- m0ModelKeyPrev: null,
11131
- m0ModelKeyNew: null,
11132
- m0ToolSetHashPrev: null,
11133
- m0ToolSetHashNew: null,
11134
- emergency: false,
11135
- droppedTokens: 0,
11136
- droppedCount: 0,
11137
- inputTokens: args.inputTokens,
11138
- bustedThisPass: mapped.bustedThisPass,
11139
- lkgFrozenReleaseReason: args.lkgFrozenReleaseReason
11140
- });
11141
- }
11142
- function clearOpenCodePendingTransformDecision(sessionId) {
11143
- pendingDecisionBySession.delete(sessionId);
11144
- }
11145
- function recordPendingTransformDecision(sessionId, decision) {
11146
- if (!decision.bustedThisPass) {
11147
- pendingDecisionBySession.delete(sessionId);
11148
- return;
11149
- }
11150
- pendingDecisionBySession.set(sessionId, decision);
11151
- }
11152
-
11153
11369
  // src/hooks/magic-context/compaction-off-transition.ts
11154
11370
  import { existsSync } from "node:fs";
11155
11371
  var loggedUnverifiedMarkerCleanupRetry = false;
@@ -11359,7 +11575,7 @@ function createPassOutcome() {
11359
11575
  }
11360
11576
 
11361
11577
  // src/hooks/magic-context/rust-mode-transform.ts
11362
- import { createHash as createHash5, randomUUID as randomUUID2 } from "node:crypto";
11578
+ import { createHash as createHash4, randomUUID as randomUUID2 } from "node:crypto";
11363
11579
 
11364
11580
  // src/features/magic-context/memory/single-store-embedding-drain.ts
11365
11581
  function isWatermarkRow(row) {
@@ -11423,7 +11639,7 @@ function advanceEmbeddedWatermark(db, projectPath, upTo) {
11423
11639
  }
11424
11640
 
11425
11641
  // src/features/magic-context/mural/source-revision.ts
11426
- import { createHash as createHash2 } from "node:crypto";
11642
+ import { createHash } from "node:crypto";
11427
11643
  var statements = new WeakMap;
11428
11644
  function muralSourceRevision(db, projectPath) {
11429
11645
  let statement = statements.get(db);
@@ -11440,7 +11656,7 @@ function muralSourceRevision(db, projectPath) {
11440
11656
  statements.set(db, statement);
11441
11657
  }
11442
11658
  const row = statement.get(projectPath, Date.now());
11443
- return createHash2("sha256").update(row.revision).digest("hex");
11659
+ return createHash("sha256").update(row.revision).digest("hex");
11444
11660
  }
11445
11661
 
11446
11662
  // src/features/magic-context/install-instance-id.ts
@@ -13814,7 +14030,7 @@ function noteExternalLkgReplay(participant, sessionId, inputMessages, servedMess
13814
14030
  }
13815
14031
 
13816
14032
  // src/hooks/magic-context/rust-served-raw.ts
13817
- import { createHash as createHash4 } from "node:crypto";
14033
+ import { createHash as createHash3 } from "node:crypto";
13818
14034
  class RustServedRawConflict extends EmergencyFailClosedError {
13819
14035
  reason;
13820
14036
  messageIds;
@@ -13828,7 +14044,7 @@ class RustServedRawConflict extends EmergencyFailClosedError {
13828
14044
  }
13829
14045
  function partDigest(part) {
13830
14046
  const serialized = JSON.stringify(part);
13831
- return createHash4("sha256").update(stableStringify(serialized === undefined ? undefined : JSON.parse(serialized))).digest("hex");
14047
+ return createHash3("sha256").update(stableStringify(serialized === undefined ? undefined : JSON.parse(serialized))).digest("hex");
13832
14048
  }
13833
14049
  function records(doc) {
13834
14050
  if (doc.rustServedRaw === undefined)
@@ -14316,10 +14532,10 @@ function messageCacheSignature(message) {
14316
14532
  const parts = Array.isArray(message.parts) ? message.parts : [];
14317
14533
  const serializedParts = JSON.stringify(parts) ?? "null";
14318
14534
  const serializedMessage = JSON.stringify(message) ?? "null";
14319
- return `${messageIdOf(message) ?? ""}:${parts.length}:${Buffer.byteLength(serializedParts)}:${createHash5("sha256").update(serializedMessage).digest("hex")}`;
14535
+ return `${messageIdOf(message) ?? ""}:${parts.length}:${Buffer.byteLength(serializedParts)}:${createHash4("sha256").update(serializedMessage).digest("hex")}`;
14320
14536
  }
14321
14537
  function advanceWireFingerprint(previous, encoded) {
14322
- return createHash5("sha256").update(previous).update("\\0").update(JSON.stringify(encoded) ?? "null").digest("hex");
14538
+ return createHash4("sha256").update(previous).update("\\0").update(JSON.stringify(encoded) ?? "null").digest("hex");
14323
14539
  }
14324
14540
  function buildWireFingerprint(encoded) {
14325
14541
  let fingerprint = "rust-wire-v1";
@@ -16100,7 +16316,7 @@ function createRustModeTransform(deps, options) {
16100
16316
  const id = messageIdOf(message) ?? `index:${todoStart + offset}`;
16101
16317
  const parts = message.parts?.filter((part) => isRecord4(part) && part.type === "tool" && part.tool === "todowrite");
16102
16318
  if (parts?.length) {
16103
- todoCalls.set(id, createHash5("sha256").update(JSON.stringify(parts)).digest("hex"));
16319
+ todoCalls.set(id, createHash4("sha256").update(JSON.stringify(parts)).digest("hex"));
16104
16320
  } else {
16105
16321
  todoCalls.delete(id);
16106
16322
  }
@@ -17790,7 +18006,7 @@ function createTransform(deps) {
17790
18006
  return historianRun?.toastDurationMs === undefined ? params : { ...params, toastDurationMs: historianRun.toastDurationMs };
17791
18007
  };
17792
18008
  beginLkgPass(sessionId);
17793
- clearOpenCodePendingTransformDecision(sessionId);
18009
+ clearOpenCodePendingTransformDecision(sessionId, messages);
17794
18010
  const db = deps.db;
17795
18011
  try {
17796
18012
  const tPrepare = performance.now();
@@ -18157,9 +18373,10 @@ function createTransform(deps) {
18157
18373
  const persistedUsageFreshForBoundary = persistedUsageBeforeResets && Date.now() - persistedUsageBeforeResets.updatedAt <= 10 * 60 * 1000 && (persistedUsageBeforeResets.lastObservedModelKey === null || currentModelKeyForBoundary === undefined || piModelRefToCanonical(persistedUsageBeforeResets.lastObservedModelKey) === piModelRefToCanonical(currentModelKeyForBoundary)) && (resolvedContextLimit === undefined || persistedUsageBeforeResets.lastUsageContextLimit === 0 || persistedUsageBeforeResets.lastUsageContextLimit === resolvedContextLimit) ? persistedUsageBeforeResets.usage : null;
18158
18374
  const boundaryUsageForProtectedTail = persistedUsageFreshForBoundary ?? contextUsageEarly;
18159
18375
  const boundaryUsageSource = persistedUsageFreshForBoundary ? "persisted" : "live";
18160
- const historyPolicyIdentity = historyBudgetPolicyIdentity(deps.historyBudgetPercentage, deps.executeThresholdPercentage, currentModelKeyForBoundary, deps.executeThresholdTokens);
18161
18376
  const historyContextLimit = resolvedContextLimit ?? (currentModelKeyForBoundary && persistedUsageBeforeResets?.lastObservedModelKey && piModelRefToCanonical(currentModelKeyForBoundary) === piModelRefToCanonical(persistedUsageBeforeResets.lastObservedModelKey) && persistedUsageBeforeResets.lastUsageContextLimit > 0 ? persistedUsageBeforeResets.lastUsageContextLimit : undefined);
18162
- const historyBudgetTokens = resolveHistoryBudgetTokens(deps.historyBudgetPercentage, contextUsageEarly, deps.executeThresholdPercentage, deps.getModelKey?.(sessionId), deps.executeThresholdTokens, historyContextLimit);
18377
+ const memoryProjectDirectory = compartmentDirectory || process.cwd();
18378
+ const renderOptions = createM0RenderOptions(deps, contextUsageEarly, currentModelKeyForBoundary, historyContextLimit, deps.memoryConfig?.enabled ? resolveProjectIdentityForSession(memoryProjectDirectory, deps.allowHomeProject) : undefined);
18379
+ const { historyBudgetTokens, projectPath: projectIdentity } = renderOptions;
18163
18380
  const emergencyCeilingLimit = thresholdContextLimit ?? 0;
18164
18381
  const emergencyCeilingTokens = Number.isFinite(emergencyCeilingLimit) && emergencyCeilingLimit > 0 ? Math.floor(emergencyCeilingLimit * (effectiveExecuteThresholdPercentage / 100)) : undefined;
18165
18382
  const schedulerDecision = compactionOff ? "defer" : resolveSchedulerDecision(deps.scheduler, sessionMeta, contextUsageEarly, sessionId, deps.getModelKey?.(sessionId), resolvedContextLimit);
@@ -18293,8 +18510,6 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
18293
18510
  });
18294
18511
  }
18295
18512
  logTransformTiming(sessionId, "emergencyRecoveryBlock", tFirstPass);
18296
- const memoryProjectDirectory = compartmentDirectory || process.cwd();
18297
- const projectIdentity = deps.memoryConfig?.enabled ? resolveProjectIdentityForSession(memoryProjectDirectory, deps.allowHomeProject) : undefined;
18298
18513
  if (deps.memoryConfig?.enabled) {
18299
18514
  maybeSendProjectIdentityWarning(deps, sessionId, memoryProjectDirectory, notificationParams);
18300
18515
  }
@@ -18579,14 +18794,8 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
18579
18794
  db,
18580
18795
  sessionId,
18581
18796
  state: sessionMeta,
18582
- projectPath: projectIdentity,
18583
18797
  projectDirectory: sessionDirectory,
18584
- injectDocs: deps.injectDocs,
18585
- memoryEnabled: deps.memoryConfig?.enabled,
18586
- muralEnabled: deps.muralEnabled,
18587
- memoryInjectionBudgetTokens: deps.memoryConfig?.injectionBudgetTokens,
18588
- historyBudgetTokens,
18589
- historyBudgetPolicyIdentity: historyPolicyIdentity,
18798
+ ...renderOptions,
18590
18799
  hardSignals: m0HardSignals
18591
18800
  }).value;
18592
18801
  const protectionCacheBustingPass = !compactionOff && (schedulerDecision === "execute" || isCacheBusting || contextUsage.percentage >= forceMaterializationPercentage || deps.pendingMaterializationSessions.has(sessionId) || canConsumeDeferredLate && deferredMaterializationSessions.has(sessionId) || protectionFoldWillBust);
@@ -18727,16 +18936,9 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
18727
18936
  passOutcome,
18728
18937
  historyRefreshSessions: deps.historyRefreshSessions,
18729
18938
  m0M1: {
18730
- projectPath: projectIdentity,
18731
18939
  projectDirectory: sessionDirectory,
18732
- injectDocs: deps.injectDocs,
18733
- memoryEnabled: deps.memoryConfig?.enabled,
18734
- memoryInjectionBudgetTokens: deps.memoryConfig?.injectionBudgetTokens,
18735
- historyBudgetTokens,
18736
- historyBudgetPolicyIdentity: historyPolicyIdentity,
18737
- temporalAwareness: deps.experimentalTemporalAwareness,
18738
- hardSignals: m0HardSignals,
18739
- muralEnabled: deps.muralEnabled
18940
+ ...renderOptions,
18941
+ hardSignals: m0HardSignals
18740
18942
  }
18741
18943
  });
18742
18944
  if (recovery.prefix && !recoveryNormalized) {
@@ -18980,6 +19182,24 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
18980
19182
  bustedThisPass: true,
18981
19183
  lkgFrozenReleaseReason: recoveryReleaseReason
18982
19184
  });
19185
+ } else {
19186
+ noteOpenCodeUnbustedPass(sessionId, {
19187
+ tsMs: Date.now(),
19188
+ decision: schedulerDecision,
19189
+ materialized: postTransformResult.materialized,
19190
+ materializeReason: normalizeMaterializeReason("opencode", postTransformResult.materializeReason, postTransformResult.materialized),
19191
+ systemHashPrev: postTransformResult.systemHashPrev,
19192
+ systemHashNew: postTransformResult.systemHashNew,
19193
+ m0ToolSetHashPrev: postTransformResult.m0ToolSetHashPrev,
19194
+ m0ToolSetHashNew: postTransformResult.m0ToolSetHashNew,
19195
+ m0ModelKeyPrev: postTransformResult.m0ModelKeyPrev,
19196
+ m0ModelKeyNew: postTransformResult.m0ModelKeyNew,
19197
+ emergency: postTransformResult.emergency,
19198
+ droppedTokens: postTransformResult.droppedTokens,
19199
+ droppedCount: postTransformResult.droppedCount,
19200
+ inputTokens: contextUsage.inputTokens,
19201
+ bustedThisPass: false
19202
+ });
18983
19203
  }
18984
19204
  logTransformTiming(sessionId, "postTransformPhase", tPostProcess);
18985
19205
  const msgTokens = getMessageTokensCache(sessionId);
@@ -19110,24 +19330,14 @@ Historian previously failed ${historianFailureState.failureCount} time(s), so Ma
19110
19330
  }
19111
19331
  });
19112
19332
  }
19113
- function resolveHistoryBudgetTokens(historyBudgetPercentage, contextUsage, executeThresholdPercentage, modelKey, executeThresholdTokens, resolvedContextLimit) {
19114
- if (!historyBudgetPercentage) {
19115
- return;
19116
- }
19117
- let contextLimit = resolvedContextLimit && resolvedContextLimit > 0 ? resolvedContextLimit : 0;
19118
- if (contextLimit <= 0) {
19119
- if (contextUsage.percentage <= 0) {
19120
- return;
19121
- }
19122
- contextLimit = contextUsage.inputTokens / (contextUsage.percentage / 100);
19123
- }
19124
- if (!Number.isFinite(contextLimit) || contextLimit <= 0) {
19333
+
19334
+ // src/plugin/dream-timer-module-client.ts
19335
+ function createDreamTimerModuleClient(moduleClient) {
19336
+ if (!moduleClient)
19125
19337
  return;
19126
- }
19127
- return Math.floor(contextLimit * (resolveExecuteThreshold(executeThresholdPercentage ?? 65, modelKey, 65, {
19128
- tokensConfig: executeThresholdTokens,
19129
- contextLimit
19130
- }) / 100) * historyBudgetPercentage);
19338
+ return {
19339
+ call: (args) => moduleClient.call(args)
19340
+ };
19131
19341
  }
19132
19342
 
19133
19343
  // src/shared/recovery-reasoning-prefix.ts
@@ -20762,7 +20972,7 @@ function computeOpenCodeWorkMetricsIncremental(openCodeDb, sessionId, carry) {
20762
20972
  import { readFileSync, statSync } from "node:fs";
20763
20973
 
20764
20974
  // src/plugin/embedding-bootstrap-helpers.ts
20765
- import { createHash as createHash6 } from "node:crypto";
20975
+ import { createHash as createHash5 } from "node:crypto";
20766
20976
  var EMBEDDING_AFFECTING_KEYS = new Set([
20767
20977
  "embedding.api_key",
20768
20978
  "embedding.endpoint",
@@ -20810,7 +21020,7 @@ var EMBEDDING_WARNING_TERMS = [
20810
21020
  ];
20811
21021
  var loggedFailureSignatures = new Map;
20812
21022
  function sha256Prefix(value, length = 16) {
20813
- return createHash6("sha256").update(value).digest("hex").slice(0, length);
21023
+ return createHash5("sha256").update(value).digest("hex").slice(0, length);
20814
21024
  }
20815
21025
  function warningLooksEmbeddingRelated(message) {
20816
21026
  const lower = message.toLowerCase();
@@ -22316,8 +22526,8 @@ function registerRpcHandlers(rpcServer, args) {
22316
22526
  const db = readDatabase();
22317
22527
  if (!db)
22318
22528
  return { ok: false, error: "db unavailable" };
22319
- const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-s5tdpsbs.js"));
22320
- const { sendIgnoredMessage } = await importPluginModule(() => import("./send-session-notification-6n7chhyp.js"));
22529
+ const { runManagedRecomp } = await importPluginModule(() => import("./recomp-orchestrator-n0pq36f0.js"));
22530
+ const { sendIgnoredMessage } = await importPluginModule(() => import("./send-session-notification-z5mcjdea.js"));
22321
22531
  log2(`[rpc] recomp requested for session ${sessionId}`);
22322
22532
  if (!args.client && !args.hiddenCompletionExecutor) {
22323
22533
  return {
@@ -22401,7 +22611,7 @@ function registerRpcHandlers(rpcServer, args) {
22401
22611
  const db = readDatabase();
22402
22612
  if (!db)
22403
22613
  return { ok: false, error: "db unavailable" };
22404
- const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-wg8dmmm9.js"));
22614
+ const { runManagedWrapup } = await importPluginModule(() => import("./wrapup-orchestrator-87q9d5e2.js"));
22405
22615
  const model = liveSessionState.liveModelBySession.get(sessionId);
22406
22616
  const contextLimit = model ? resolveContextLimit(model.providerID, model.modelID, { db, sessionID: sessionId }) : 128000;
22407
22617
  const ctx = {
@@ -23390,8 +23600,8 @@ function hostMediaFromEncoded(value) {
23390
23600
  import { randomUUID as randomUUID4 } from "node:crypto";
23391
23601
 
23392
23602
  // src/v2/fold/owner.ts
23393
- import { createHash as createHash7 } from "node:crypto";
23394
- var foldDigest = (value) => createHash7("sha256").update(value).digest("hex");
23603
+ import { createHash as createHash6 } from "node:crypto";
23604
+ var foldDigest = (value) => createHash6("sha256").update(value).digest("hex");
23395
23605
 
23396
23606
  class FoldOwner {
23397
23607
  storage;
@@ -23834,7 +24044,7 @@ function rebuildFileContent(value, output, attachments) {
23834
24044
  rebuilt.unshift({ type: "text", text: output });
23835
24045
  return { type: "content", value: rebuilt };
23836
24046
  }
23837
- function adaptPayload(draft, admittedIDs = new Set) {
24047
+ function adaptPayload(draft, admittedIDs = new Set, messageTimes = new Map) {
23838
24048
  const existingHeads = new Map(draft.messages.filter((m) => HEAD_IDS.some((id) => m.id === id)).map((m) => [m.id, m]));
23839
24049
  const source = draft.messages.filter((m) => !existingHeads.has(m.id));
23840
24050
  const results = new Map;
@@ -23944,6 +24154,7 @@ function adaptPayload(draft, admittedIDs = new Set) {
23944
24154
  id: message.id,
23945
24155
  sessionID: draft.sessionID,
23946
24156
  role: message.role,
24157
+ time: message.id ? messageTimes.get(message.id) : undefined,
23947
24158
  ...{
23948
24159
  providerID: draft.model.providerID,
23949
24160
  modelID: draft.model.id,
@@ -25999,11 +26210,11 @@ class DeletedSessionTombstones {
25999
26210
  }
26000
26211
 
26001
26212
  // src/features/magic-context/dreamer/task-executor.ts
26002
- import { createHash as createHash14 } from "node:crypto";
26213
+ import { createHash as createHash13 } from "node:crypto";
26003
26214
  import { existsSync as existsSync7, readFileSync as readFileSync8 } from "node:fs";
26004
26215
 
26005
26216
  // src/features/magic-context/mural/compress-cues.ts
26006
- import { createHash as createHash8 } from "node:crypto";
26217
+ import { createHash as createHash7 } from "node:crypto";
26007
26218
 
26008
26219
  // src/features/magic-context/dreamer/storage-dream-state.ts
26009
26220
  var getDreamStateStatements = new WeakMap;
@@ -26733,7 +26944,7 @@ async function applyCuesThroughModule(args, chunk, manifestText, signal) {
26733
26944
  log2(`[dreamer] compress-cues: skipped cue for memory ${entry.id} (${failure.reason}; rejection ${rejectionCount}/${CUE_REJECTION_LATCH_THRESHOLD})`);
26734
26945
  }
26735
26946
  }
26736
- const commandId = `mural-cues:${route.moduleCommandId}:${createHash8("sha256").update(chunk.map((candidate) => candidate.memory.id).join(",")).digest("hex").slice(0, 24)}`;
26947
+ const commandId = `mural-cues:${route.moduleCommandId}:${createHash7("sha256").update(chunk.map((candidate) => candidate.memory.id).join(",")).digest("hex").slice(0, 24)}`;
26737
26948
  let response;
26738
26949
  try {
26739
26950
  response = await route.moduleClient.call({
@@ -27321,7 +27532,7 @@ function applyReviewVerdict(args, leaseKey, parsed, result) {
27321
27532
  }
27322
27533
 
27323
27534
  // src/features/magic-context/dreamer/classify.ts
27324
- import { createHash as createHash9 } from "node:crypto";
27535
+ import { createHash as createHash8 } from "node:crypto";
27325
27536
 
27326
27537
  // src/plugin/rust-tool-backends.ts
27327
27538
  function isRustAuthorityDrainingError(error) {
@@ -27758,7 +27969,7 @@ async function runClassifyThroughModule(args, chunk, anchors, signal, runOnHost)
27758
27969
  if (entry.qualifier)
27759
27970
  modelVariants[entry.model] = entry.qualifier;
27760
27971
  }
27761
- const commandId = `classify:${args.moduleCommandId ?? Date.now()}:${createHash9("sha256").update(chunk.map((candidate) => candidate.id).join(",")).digest("hex").slice(0, 24)}`;
27972
+ const commandId = `classify:${args.moduleCommandId ?? Date.now()}:${createHash8("sha256").update(chunk.map((candidate) => candidate.id).join(",")).digest("hex").slice(0, 24)}`;
27762
27973
  const runTask = (hostCompletion) => args.moduleClient?.call({
27763
27974
  sessionId: args.moduleSessionId,
27764
27975
  projectRoot: args.moduleProjectRoot,
@@ -28033,7 +28244,7 @@ function takeCurateSafetyRefusalCount(sessionId) {
28033
28244
 
28034
28245
  // src/features/magic-context/dreamer/docs-proposals.ts
28035
28246
  import { execFileSync } from "node:child_process";
28036
- import { createHash as createHash10 } from "node:crypto";
28247
+ import { createHash as createHash9 } from "node:crypto";
28037
28248
  import {
28038
28249
  existsSync as existsSync4,
28039
28250
  mkdirSync,
@@ -28048,7 +28259,7 @@ import {
28048
28259
  import { tmpdir } from "node:os";
28049
28260
  import { join as join7 } from "node:path";
28050
28261
  var FILES = ["ARCHITECTURE.md", "STRUCTURE.md"];
28051
- var hash = (text) => createHash10("sha256").update(text).digest("hex");
28262
+ var hash = (text) => createHash9("sha256").update(text).digest("hex");
28052
28263
  var proposalDir = (projectDir) => join7(projectDir, ".cortexkit/magic-context/docs-update-proposals");
28053
28264
  function docsBaseHashes(projectDir) {
28054
28265
  return Object.fromEntries(FILES.map((name) => [
@@ -28584,7 +28795,7 @@ function throwIfAborted2(signal) {
28584
28795
  }
28585
28796
 
28586
28797
  // src/features/magic-context/smart-notes/compiler.ts
28587
- import { createHash as createHash11 } from "node:crypto";
28798
+ import { createHash as createHash10 } from "node:crypto";
28588
28799
 
28589
28800
  // src/features/magic-context/smart-notes/compiler-prompt.ts
28590
28801
  var SMART_NOTE_COMPILER_SYSTEM_PROMPT = `You are the Magic Context smart-note compiler for the magic-context system.
@@ -28923,7 +29134,7 @@ function manifestAdvisoryWarnings(code, manifest) {
28923
29134
  return warnings;
28924
29135
  }
28925
29136
  function hashCheck(surfaceCondition, compiledCheck, manifest, checkCron) {
28926
- return createHash11("sha256").update(surfaceCondition ?? "").update("\x00").update(compiledCheck).update("\x00").update(JSON.stringify(manifest)).update("\x00").update(checkCron).digest("hex");
29137
+ return createHash10("sha256").update(surfaceCondition ?? "").update("\x00").update(compiledCheck).update("\x00").update(JSON.stringify(manifest)).update("\x00").update(checkCron).digest("hex");
28927
29138
  }
28928
29139
  function extractJsonObject(output) {
28929
29140
  const fenced = output.match(/```(?:json)?\s*([\s\S]*?)```/i);
@@ -29689,7 +29900,7 @@ function snapshotMaintainDocsFiles(docsDir) {
29689
29900
  }
29690
29901
 
29691
29902
  // src/features/magic-context/dreamer/map-memories.ts
29692
- import { createHash as createHash12 } from "node:crypto";
29903
+ import { createHash as createHash11 } from "node:crypto";
29693
29904
 
29694
29905
  // src/features/magic-context/dreamer/map-memories-prompt.ts
29695
29906
  import { execFile as execFile2 } from "node:child_process";
@@ -29924,7 +30135,7 @@ function readRetries(db, project) {
29924
30135
  }
29925
30136
  }
29926
30137
  function contentKey2(memory) {
29927
- return createHash12("sha256").update(`${memory.category}
30138
+ return createHash11("sha256").update(`${memory.category}
29928
30139
  ${memory.content}`).digest("hex");
29929
30140
  }
29930
30141
  function isDeferred(memory, retries) {
@@ -30323,7 +30534,7 @@ async function applyParsedBatchMappings(args, batch, parsed, budgetFinalized = f
30323
30534
  name: "memory.set_mapping",
30324
30535
  arguments: {
30325
30536
  memory_project: args.projectIdentity,
30326
- command_id: `${args.moduleRoute.moduleCommandId}:${createHash12("sha256").update(rows.map((row) => row.memory_id).join(",")).digest("hex").slice(0, 16)}`,
30537
+ command_id: `${args.moduleRoute.moduleCommandId}:${createHash11("sha256").update(rows.map((row) => row.memory_id).join(",")).digest("hex").slice(0, 16)}`,
30327
30538
  rows
30328
30539
  }
30329
30540
  }
@@ -31604,7 +31815,7 @@ function insertDreamRun(db, run) {
31604
31815
  }
31605
31816
 
31606
31817
  // src/features/magic-context/dreamer/verify.ts
31607
- import { createHash as createHash13 } from "node:crypto";
31818
+ import { createHash as createHash12 } from "node:crypto";
31608
31819
 
31609
31820
  // src/features/magic-context/dreamer/verify-diff.ts
31610
31821
  import { execFile as execFile3 } from "node:child_process";
@@ -32348,7 +32559,7 @@ async function applyParsedVerifyManifest(args, batch, parsed, headAtPrompt, budg
32348
32559
  name: "memory.set_verification",
32349
32560
  arguments: {
32350
32561
  memory_project: args.projectIdentity,
32351
- command_id: `${args.moduleRoute.moduleCommandId}:${createHash13("sha256").update(rows.map((row) => row.memory_id).join(",")).digest("hex").slice(0, 16)}`,
32562
+ command_id: `${args.moduleRoute.moduleCommandId}:${createHash12("sha256").update(rows.map((row) => row.memory_id).join(",")).digest("hex").slice(0, 16)}`,
32352
32563
  rows
32353
32564
  }
32354
32565
  }
@@ -33154,7 +33365,7 @@ function parseFrictionGateVerdict(verdict) {
33154
33365
  }
33155
33366
  function computeRetrospectiveWindowKey(flagged) {
33156
33367
  const anchors = flagged.map((message) => `${message.sessionId}:${message.ts}`).sort().join("|");
33157
- return createHash14("sha256").update(anchors).digest("hex").slice(0, 32);
33368
+ return createHash13("sha256").update(anchors).digest("hex").slice(0, 32);
33158
33369
  }
33159
33370
  function renderFrictionWindow(messages, flaggedOrdinals, radius = 2) {
33160
33371
  const flagged = new Set(flaggedOrdinals);
@@ -34097,6 +34308,8 @@ async function runManualDream(deps) {
34097
34308
  } else {
34098
34309
  selected = deps.tasks.filter((t) => t.schedule.trim() !== "");
34099
34310
  }
34311
+ if (!isProjectMemoryEnabled(deps.projectMemoryEnabled))
34312
+ selected = selected.filter((config) => config.task === "evaluate-smart-notes");
34100
34313
  if (selected.length === 0)
34101
34314
  return result;
34102
34315
  const selectedTaskNames = selected.map((config) => config.task);
@@ -34162,7 +34375,7 @@ async function runManualDream(deps) {
34162
34375
  async function runDueTasksForProject(deps) {
34163
34376
  if (!isUsableProjectIdentity(deps.projectIdentity))
34164
34377
  return 0;
34165
- if (deps.projectMemoryEnabled === false)
34378
+ if (!isProjectMemoryEnabled(deps.projectMemoryEnabled))
34166
34379
  return 0;
34167
34380
  const now = deps.now ?? Date.now();
34168
34381
  const due = planDueTasks(deps.db, deps.projectIdentity, deps.tasks, now);
@@ -34301,6 +34514,7 @@ async function runManualDreamNow(args) {
34301
34514
  const summary = await runManualDream({
34302
34515
  db: args.db,
34303
34516
  projectIdentity: args.projectIdentity,
34517
+ projectMemoryEnabled: args.memoryEnabled,
34304
34518
  tasks: selection.runnable,
34305
34519
  executor,
34306
34520
  ...args.task !== undefined ? { task: args.task } : {}
@@ -34686,7 +34900,7 @@ function scheduleInitialProjectRun(reg, db) {
34686
34900
  async function runProjectMaintenance(reg, origin, db) {
34687
34901
  const sampled = reg.sampleDreamRun?.();
34688
34902
  const current = sampled ? { ...reg, ...sampled } : reg;
34689
- const projectMaintenanceEnabled = Boolean(current.dreamerConfig && current.dreamerConfig.disable !== true) || reg.memoryEnabled === true || reg.gitCommitIndexing?.enabled === true || reg.historianChildSweep !== undefined;
34903
+ const projectMaintenanceEnabled = Boolean(current.dreamerConfig && current.dreamerConfig.disable !== true) || reg.memoryEnabled === true || current.gitCommitIndexing?.enabled === true || reg.historianChildSweep !== undefined;
34690
34904
  if (!projectMaintenanceEnabled)
34691
34905
  return;
34692
34906
  await reg.ensureRegistered(reg.directory, db);
@@ -34697,7 +34911,7 @@ async function runProjectMaintenance(reg, origin, db) {
34697
34911
  log2(`[magic-context] proactively embedded ${embeddedCount} ${embeddedCount === 1 ? "memory" : "memories"} for project ${reg.projectIdentity}`);
34698
34912
  }
34699
34913
  }
34700
- await sweepProject(current, origin, db);
34914
+ await sweepProject(current, origin, db, current.gitCommitIndexing?.enabled === true);
34701
34915
  }
34702
34916
  async function sweepProject(reg, origin, db, gitCommitEnabled) {
34703
34917
  if (!directoryStillExists(reg.directory)) {
@@ -34934,7 +35148,11 @@ function registerV2DreamScheduleTimer(args) {
34934
35148
  dreamerConfig: dreamer,
34935
35149
  sampleDreamRun: () => {
34936
35150
  const current = dreamerRunConfig(config, args.liveConfig());
34937
- return { dreamerConfig: current.dreamer ?? dreamer, mural: current.mural };
35151
+ return {
35152
+ dreamerConfig: current.dreamer ?? dreamer,
35153
+ mural: current.mural,
35154
+ gitCommitIndexing: current.memory.git_commit_indexing
35155
+ };
34938
35156
  },
34939
35157
  validateTaskModels: (tasks) => selectRunnableDreamTasks({ tasks, toolsSupported: executor.capabilities.tools }).runnable,
34940
35158
  language: config.language,
@@ -34944,6 +35162,8 @@ function registerV2DreamScheduleTimer(args) {
34944
35162
  retinaHandoff: config.smart_notes.retina_handoff,
34945
35163
  smartNotesEnabled: config.smart_notes.enabled,
34946
35164
  embeddingConfig: config.embedding,
35165
+ transformMode: config.transform_mode,
35166
+ moduleClient: createDreamTimerModuleClient(args.rustModeModuleClient),
34947
35167
  gitCommitIndexing: gitCommitIndexing?.enabled ? {
34948
35168
  enabled: true,
34949
35169
  since_days: gitCommitIndexing.since_days,
@@ -35019,6 +35239,10 @@ function startDreamTrigger(context, args) {
35019
35239
  retrospectiveRawProvider: (db) => new V2RetrospectiveRawProvider(db),
35020
35240
  language: args.language,
35021
35241
  mural: sampled?.mural ?? args.mural,
35242
+ memoryInjectionBudgetTokens: args.memoryInjectionBudgetTokens,
35243
+ retinaHandoff: args.retinaHandoff,
35244
+ transformMode: args.transformMode,
35245
+ moduleClient: args.moduleClient,
35022
35246
  smartNotesEnabled: args.smartNotesEnabled
35023
35247
  })
35024
35248
  });
@@ -35108,9 +35332,9 @@ function hiddenTerminalError(event) {
35108
35332
  }
35109
35333
 
35110
35334
  // src/v2/hooks/lkg-system.ts
35111
- import { createHash as createHash15 } from "node:crypto";
35335
+ import { createHash as createHash14 } from "node:crypto";
35112
35336
  function identity(slot) {
35113
- return createHash15("sha256").update(JSON.stringify({
35337
+ return createHash14("sha256").update(JSON.stringify({
35114
35338
  capturedAt: slot.capturedAt,
35115
35339
  captureSequence: slot.captureSequence,
35116
35340
  rowVersion: slot.rowVersion,
@@ -47938,7 +48162,7 @@ function resolveCtxExpandMode(args, domain) {
47938
48162
  }
47939
48163
 
47940
48164
  // src/tools/ctx-expand/render.ts
47941
- import { createHash as createHash16 } from "node:crypto";
48165
+ import { createHash as createHash15 } from "node:crypto";
47942
48166
  function isRecord6(value) {
47943
48167
  return value !== null && typeof value === "object" && !Array.isArray(value);
47944
48168
  }
@@ -48162,7 +48386,7 @@ function renderItemByTag(db, sessionId, number, textIndexDomain = "part") {
48162
48386
  const index = scoped ? Number(scoped[2]) : 0;
48163
48387
  const piText = message.parts.filter((part) => isRecord6(part) && part.type === "text");
48164
48388
  const part = message.parts[index];
48165
- const matching = derived ? piText.filter((part) => isRecord6(part) && typeof part.text === "string" && createHash16("sha256").update(part.text).digest("hex") === derived[3]) : [];
48389
+ const matching = derived ? piText.filter((part) => isRecord6(part) && typeof part.text === "string" && createHash15("sha256").update(part.text).digest("hex") === derived[3]) : [];
48166
48390
  const selected = derived ? matching[Number(derived[4])] : textIndexDomain === "text" ? piText[index] : part;
48167
48391
  return selected ? renderPartFull(selected) ?? "" : `Tag ${number}'s original text part is no longer in stored history.`;
48168
48392
  }
@@ -49738,7 +49962,7 @@ function formatCtxReduceReply(stampedCount, selfStampCount = 0) {
49738
49962
  return parts.join(" ");
49739
49963
  }
49740
49964
  // src/tools/ctx-reduce/tools.ts
49741
- import { createHash as createHash17 } from "node:crypto";
49965
+ import { createHash as createHash16 } from "node:crypto";
49742
49966
 
49743
49967
  // src/features/magic-context/range-parser.ts
49744
49968
  function parseRangeString(input) {
@@ -49801,11 +50025,11 @@ function createCtxReduceTool(deps) {
49801
50025
  const stableId = `oc-${sessionId}-${callId}`;
49802
50026
  if (Buffer.byteLength(stableId) <= 128)
49803
50027
  return stableId;
49804
- return `oc-${createHash17("sha256").update(stableId).digest("hex")}`;
50028
+ return `oc-${createHash16("sha256").update(stableId).digest("hex")}`;
49805
50029
  }
49806
50030
  fallbackCommandSequence += 1;
49807
50031
  const monotonicId = `oc-${sessionId}-${fallbackCommandSequence}`;
49808
- return Buffer.byteLength(monotonicId) <= 128 ? monotonicId : `oc-${createHash17("sha256").update(monotonicId).digest("hex")}`;
50032
+ return Buffer.byteLength(monotonicId) <= 128 ? monotonicId : `oc-${createHash16("sha256").update(monotonicId).digest("hex")}`;
49809
50033
  };
49810
50034
  return tool({
49811
50035
  description: CTX_REDUCE_DESCRIPTION,
@@ -50186,6 +50410,112 @@ async function registerTools(context, db, config, rustToolBackends, isInternalCh
50186
50410
  return { dispose: () => controller.abort() };
50187
50411
  }
50188
50412
 
50413
+ // src/v2/hooks/transform-decision-binding.ts
50414
+ function bindV2TransformDecision(args) {
50415
+ try {
50416
+ return bindOpenCodeV2TransformDecision({
50417
+ db: args.db,
50418
+ sessionId: args.sessionId,
50419
+ passStarting: args.passStarting,
50420
+ firstAssistantAfter: (sequence) => {
50421
+ const first = args.reader.assistantSince(args.sessionId, sequence)[0];
50422
+ if (!first)
50423
+ return;
50424
+ const completion = {
50425
+ completedAt: first.data.time?.completed,
50426
+ finish: first.data.finish,
50427
+ error: first.data.error
50428
+ };
50429
+ return {
50430
+ id: first.id,
50431
+ state: providerResponseFailed(completion) ? "failed" : isSuccessfulProviderCompletion(completion) ? "succeeded" : "running",
50432
+ inputTokens: lkgProviderInputTotal(first.data.tokens)
50433
+ };
50434
+ }
50435
+ });
50436
+ } catch {
50437
+ return false;
50438
+ }
50439
+ }
50440
+
50441
+ // src/v2/hooks/transform-features.ts
50442
+ function createV2TransformFeatureDeps(config, compactionOff, directory) {
50443
+ return {
50444
+ protectedTools: config.protected_tools,
50445
+ commitClusterTrigger: config.commit_cluster_trigger,
50446
+ allowHomeProject: config.allow_home_project,
50447
+ injectDocs: config.dreamer?.inject_docs !== false,
50448
+ memoryConfig: {
50449
+ enabled: config.memory.enabled,
50450
+ injectionBudgetTokens: config.memory.injection_budget_tokens,
50451
+ autoPromote: config.memory.auto_promote
50452
+ },
50453
+ ensureProjectRegistered: ensureProjectRegisteredFromOpenCodeDirectory,
50454
+ historyBudgetPercentage: config.history_budget_percentage,
50455
+ experimentalUserMemories: userMemoryCollectionEnabled2(config.dreamer),
50456
+ experimentalTemporalAwareness: config.temporal_awareness === true,
50457
+ muralEnabled: config.mural?.enabled === true,
50458
+ autoSearch: {
50459
+ enabled: config.memory.auto_search?.enabled ?? true,
50460
+ scoreThreshold: config.memory.auto_search?.score_threshold ?? 0.6,
50461
+ minPromptChars: config.memory.auto_search?.min_prompt_chars ?? 20,
50462
+ directory,
50463
+ ensureProjectRegistered: ensureProjectRegisteredFromOpenCodeDirectory,
50464
+ wordRules: cavemanWordRulesForLanguage(config.language)
50465
+ },
50466
+ cavemanTextCompression: compactionOff ? undefined : config.caveman_text_compression?.enabled === true ? {
50467
+ enabled: true,
50468
+ minChars: config.caveman_text_compression.min_chars ?? 500,
50469
+ wordRules: cavemanWordRulesForLanguage(config.language)
50470
+ } : undefined
50471
+ };
50472
+ }
50473
+ function createV2AutoEmbedSession(deps) {
50474
+ return (sessionId) => {
50475
+ if (isEmbeddingHostBusy2())
50476
+ return;
50477
+ const directory = deps.resolveDirectory(sessionId);
50478
+ const identity = resolveProjectIdentityForSession(directory, deps.allowHomeProject);
50479
+ const snapshot = identity ? getProjectEmbeddingSnapshot2(identity) : undefined;
50480
+ const embedIdentity = snapshot ? JSON.stringify([
50481
+ snapshot.providerIdentity,
50482
+ snapshot.chunkModelId,
50483
+ snapshot.runtimeFingerprint
50484
+ ]) : "off";
50485
+ if (autoEmbedIdentityBySession.get(sessionId) !== embedIdentity)
50486
+ invalidateAutoEmbedSession(sessionId);
50487
+ if (autoEmbedAttemptedBySession.has(sessionId) || embedPauseBySession.has(sessionId))
50488
+ return;
50489
+ autoEmbedAttemptedBySession.add(sessionId);
50490
+ autoEmbedIdentityBySession.set(sessionId, embedIdentity);
50491
+ (async () => {
50492
+ try {
50493
+ await new Promise((resolve) => setTimeout(resolve, 0));
50494
+ if (isEmbeddingHostBusy2()) {
50495
+ invalidateAutoEmbedSession(sessionId);
50496
+ return;
50497
+ }
50498
+ await ensureProjectRegisteredFromOpenCodeDirectory(directory, deps.db);
50499
+ const project = resolveProjectIdentityForSession(directory, deps.allowHomeProject);
50500
+ if (!project) {
50501
+ invalidateAutoEmbedSession(sessionId);
50502
+ return;
50503
+ }
50504
+ const coverage = await getAutoEmbeddingSessionCoverage2(deps.db, project, sessionId);
50505
+ if (!coverage.enabled) {
50506
+ invalidateAutoEmbedSession(sessionId);
50507
+ return;
50508
+ }
50509
+ if (coverage.total <= coverage.embedded)
50510
+ return;
50511
+ await runEmbedHistoryDrain(deps, sessionId, { silent: true });
50512
+ } catch (error) {
50513
+ log2("[magic-context] auto-embed drain failed:", error);
50514
+ }
50515
+ })();
50516
+ };
50517
+ }
50518
+
50189
50519
  // src/v2/hooks/usage-reading.ts
50190
50520
  function usageReadingMatchesDraft(reading, draftModel) {
50191
50521
  return reading.modelKey === undefined || reading.modelKey === `${draftModel.providerID}/${draftModel.id}`;
@@ -50636,29 +50966,39 @@ async function registerContext(context) {
50636
50966
  projectIdentity: () => resolveProjectIdentityForSession(directory, config.allow_home_project) ?? "",
50637
50967
  projectMemoryEnabled: config.memory.enabled,
50638
50968
  language: config.language,
50639
- mural: config.mural
50969
+ mural: config.mural,
50970
+ memoryInjectionBudgetTokens: config.memory.injection_budget_tokens,
50971
+ retinaHandoff: config.smart_notes.retina_handoff,
50972
+ transformMode: config.transform_mode,
50973
+ moduleClient: createDreamTimerModuleClient(rustModeModuleClient)
50640
50974
  });
50641
- const timer = registerV2DreamScheduleTimer({
50975
+ return trigger;
50976
+ };
50977
+ let hiddenCompletionExecutor = db && isDatabasePersisted(db) && resolveProjectIdentityForSession(directory, config.allow_home_project) ? await createHiddenExecutor(db) : undefined;
50978
+ let dreamTrigger = hiddenCompletionExecutor ? startDreamer(hiddenCompletionExecutor) : undefined;
50979
+ const lateHiddenExecutor = createLateHiddenExecutor(() => hiddenCompletionExecutor);
50980
+ let maintenanceTimer;
50981
+ const startMaintenance = () => {
50982
+ const timerProjectIdentity = resolveProjectIdentityForSession(directory, config.allow_home_project);
50983
+ if (!timerProjectIdentity || maintenanceTimer)
50984
+ return;
50985
+ maintenanceTimer = registerV2DreamScheduleTimer({
50642
50986
  directory,
50643
- projectIdentity,
50987
+ projectIdentity: timerProjectIdentity,
50644
50988
  config,
50645
50989
  dreamer: dreamerAtBoot,
50646
50990
  liveConfig: () => liveConfigReader.poll().effective,
50647
- executor: cappedExecutor,
50648
- openReader: openStoreReader
50991
+ executor: withLiveDreamerOutputCap(lateHiddenExecutor, config, () => liveConfigReader.poll().effective),
50992
+ openReader: openStoreReader,
50993
+ rustModeModuleClient
50649
50994
  });
50650
- return {
50651
- async dispose() {
50652
- await Promise.all([trigger.dispose(), timer.dispose()]);
50653
- }
50654
- };
50655
50995
  };
50656
- let hiddenCompletionExecutor = db && isDatabasePersisted(db) && resolveProjectIdentityForSession(directory, config.allow_home_project) ? await createHiddenExecutor(db) : undefined;
50657
- let dreamTrigger = hiddenCompletionExecutor ? startDreamer(hiddenCompletionExecutor) : undefined;
50658
- const lateHiddenExecutor = createLateHiddenExecutor(() => hiddenCompletionExecutor);
50996
+ if (db && isDatabasePersisted(db))
50997
+ startMaintenance();
50659
50998
  let hiddenWorkRecovery;
50660
50999
  const recoverHiddenWork = (database) => !resolveProjectIdentityForSession(directory, config.allow_home_project) ? Promise.resolve(false) : hiddenWorkRecovery ??= (async () => {
50661
51000
  try {
51001
+ startMaintenance();
50662
51002
  hiddenCompletionExecutor ??= await createHiddenExecutor(database);
50663
51003
  dreamTrigger ??= startDreamer(hiddenCompletionExecutor);
50664
51004
  return true;
@@ -50693,6 +51033,7 @@ async function registerContext(context) {
50693
51033
  registerSystemDateRefresh(historyRefreshSessions);
50694
51034
  const pendingMaterializationSessions = new Set;
50695
51035
  const lastHeuristicsTurnId = new Map;
51036
+ const commitSeenLastPass = new Map;
50696
51037
  const restoredRows = new RestoredRowCache;
50697
51038
  const rawProviders = new Map;
50698
51039
  let passDuties;
@@ -50802,7 +51143,7 @@ async function registerContext(context) {
50802
51143
  }
50803
51144
  };
50804
51145
  const latestLkgResponseIds = new BoundedSessionMap(1000);
50805
- const recordUsage = async (draft) => {
51146
+ const recordUsage = async (draft, passStarting = false) => {
50806
51147
  let unsafe = false;
50807
51148
  try {
50808
51149
  await storage.probe();
@@ -50817,6 +51158,12 @@ async function registerContext(context) {
50817
51158
  } catch (error) {
50818
51159
  sessionLog2(draft.sessionID, "v2 response ownership unavailable; keeping system identity pending", error);
50819
51160
  }
51161
+ bindV2TransformDecision({
51162
+ db,
51163
+ sessionId: draft.sessionID,
51164
+ reader,
51165
+ passStarting
51166
+ });
50820
51167
  if (latest)
50821
51168
  noteLkgProviderResponse({
50822
51169
  sessionId: draft.sessionID,
@@ -50946,6 +51293,8 @@ async function registerContext(context) {
50946
51293
  variants.delete(sessionID);
50947
51294
  agents.delete(sessionID);
50948
51295
  channel1.delete(sessionID);
51296
+ commitSeenLastPass.delete(sessionID);
51297
+ clearEmbedSessionState(sessionID);
50949
51298
  historyRefreshSessions.delete(sessionID);
50950
51299
  clearPendingMaterialization(pendingMaterializationSessions, sessionID);
50951
51300
  lastHeuristicsTurnId.delete(sessionID);
@@ -50977,16 +51326,22 @@ async function registerContext(context) {
50977
51326
  const materialize = (draft) => {
50978
51327
  db = storage.require();
50979
51328
  const state = getOrCreateSessionMeta(db, draft.sessionID);
51329
+ const modelKey = `${draft.model.providerID}/${draft.model.id}`;
51330
+ const contextLimit = resolveContextLimit(draft.model.providerID, draft.model.id, {
51331
+ db,
51332
+ sessionID: draft.sessionID
51333
+ }) || draft.model.limit?.context || (state.lastObservedModelKey === modelKey ? state.lastUsageContextLimit : undefined);
50980
51334
  return materializeM0({
51335
+ ...createM0RenderOptions({
51336
+ ...createV2TransformFeatureDeps(config, compactionOff, directory),
51337
+ ...createV2ThresholdDeps(config)
51338
+ }, usage.get(draft.sessionID)?.usage ?? { percentage: 0, inputTokens: 0 }, modelKey, contextLimit, resolveProjectIdentityForSession(directory, config.allow_home_project)),
50981
51339
  db,
50982
51340
  sessionId: draft.sessionID,
50983
51341
  state,
50984
- projectPath: resolveProjectIdentityForSession(directory, config.allow_home_project) ?? "",
50985
51342
  projectDirectory: directory,
50986
- memoryEnabled: config.memory.enabled && !!resolveProjectIdentityForSession(directory, config.allow_home_project),
50987
- memoryInjectionBudgetTokens: config.memory.injection_budget_tokens,
50988
51343
  hardSignals: {
50989
- systemHash: foldDigest(JSON.stringify(draft.system)),
51344
+ systemHash: state.systemPromptHash ?? "",
50990
51345
  toolSetHash: getCurrentToolSetHash(draft.model.providerID, draft.model.id, draft.agent),
50991
51346
  modelKey: `${draft.model.providerID}/${draft.model.id}`,
50992
51347
  cacheExpired: false,
@@ -51006,6 +51361,7 @@ async function registerContext(context) {
51006
51361
  rememberHostMedia(draft.messages);
51007
51362
  const reader = openStoreReader();
51008
51363
  try {
51364
+ await storage.probe();
51009
51365
  const watermark = reader.latestSequenceForIds(draft.sessionID, draft.messages.flatMap((message) => message.id ? [message.id] : []));
51010
51366
  const running = reader.latestRunningCompaction(draft.sessionID);
51011
51367
  const moduleBaseline = rustModeModuleClient ? servedModuleM0Text(draft.sessionID) : undefined;
@@ -51144,7 +51500,7 @@ async function registerContext(context) {
51144
51500
  if (admissionDb)
51145
51501
  hideSubagentTools(draft, admissionDb);
51146
51502
  recordV2ToolDefinitions(draft);
51147
- if (await recordUsage(draft) && !compactionOff) {
51503
+ if (await recordUsage(draft, true) && !compactionOff) {
51148
51504
  const storageReason = storage.current() ? null : storage.reason();
51149
51505
  if (storageReason) {
51150
51506
  noticeStorageRefusal(draft.sessionID, storageReason);
@@ -51226,6 +51582,7 @@ async function registerContext(context) {
51226
51582
  await cacheV2SessionDirectory(context.session, draft.sessionID, sessionDirectories);
51227
51583
  prepareHistorySession(draft.sessionID);
51228
51584
  transform ??= createTransform({
51585
+ ...createV2TransformFeatureDeps(config, compactionOff, directory),
51229
51586
  cacheTtlConfig: config.cache_ttl,
51230
51587
  cacheTtlConfigured: config.cacheTtlConfigured,
51231
51588
  sampleCacheTtlConfig: () => liveConfigReader.poll().effective,
@@ -51255,14 +51612,27 @@ async function registerContext(context) {
51255
51612
  historyRefreshSessions,
51256
51613
  pendingMaterializationSessions,
51257
51614
  lastHeuristicsTurnId,
51615
+ commitSeenLastPass,
51258
51616
  variantBySession: variants,
51259
51617
  keepReasoningTokens: config.keep_reasoning_tokens,
51260
51618
  directory,
51261
51619
  sessionDirectoryBySession: sessionDirectories,
51262
- projectPath: directory,
51620
+ projectPath: resolveProjectIdentityForSession(directory, config.allow_home_project),
51621
+ getHistorianChunkTokens: () => sampleHistorian().chunkTokens,
51622
+ getFallbackModelId: (sessionID) => {
51623
+ const model = liveModels.get(sessionID);
51624
+ return model ? `${model.providerID}/${model.modelID}` : undefined;
51625
+ },
51626
+ maybeAutoEmbedSession: createV2AutoEmbedSession({
51627
+ db,
51628
+ resolveDirectory: (sessionID) => sessionDirectories.get(sessionID) ?? directory,
51629
+ allowHomeProject: config.allow_home_project,
51630
+ recompProgressBySession: new Map
51631
+ }),
51263
51632
  hiddenCompletionExecutor,
51264
51633
  historianRunnable: !compactionOff && hiddenCompletionExecutor !== undefined && config.historian?.disable !== true,
51265
51634
  historianModel: historianModels.primary,
51635
+ historianContextLimit: sampleHistorian().contextLimit,
51266
51636
  fallbackModels: historianModels.fallbacks,
51267
51637
  resolveHistorianRun: sampleHistorian,
51268
51638
  historianTimeoutMs: config.historian_timeout_ms,
@@ -51290,14 +51660,10 @@ async function registerContext(context) {
51290
51660
  promptSurface: config.prompt_surface,
51291
51661
  promptSurfaceRuntime,
51292
51662
  onRustEngineReconnectRefusal: (refusal) => rustRefusalRecovery?.arm(refusal),
51293
- memoryConfig: {
51294
- enabled: config.memory.enabled,
51295
- injectionBudgetTokens: config.memory.injection_budget_tokens,
51296
- autoPromote: config.memory.auto_promote
51297
- },
51298
51663
  ...createHostSeams(context, readAllForConversion, pagedRead, liveModels)
51299
51664
  });
51300
51665
  const admitted = new Set;
51666
+ let messageTimes;
51301
51667
  const reader = openStoreReader();
51302
51668
  let checkpoint;
51303
51669
  let submitted;
@@ -51368,6 +51734,8 @@ async function registerContext(context) {
51368
51734
  } : undefined));
51369
51735
  draft.messages.splice(0, draft.messages.length, ...restored, ...draft.messages.filter((message) => message !== incoming));
51370
51736
  }
51737
+ if (config.temporal_awareness === true)
51738
+ messageTimes = reader.messageTimes(draft.sessionID, draft.messages.flatMap((message) => message.id ? [message.id] : []));
51371
51739
  } finally {
51372
51740
  reader.close();
51373
51741
  }
@@ -51384,7 +51752,7 @@ async function registerContext(context) {
51384
51752
  nativeFoldReplay.invalidate(draft.sessionID, true);
51385
51753
  }
51386
51754
  }
51387
- const mapped = adaptPayload(draft, admitted);
51755
+ const mapped = adaptPayload(draft, admitted, messageTimes);
51388
51756
  bindSystemDateRequestIdentity(mapped, draft);
51389
51757
  await createMessagesTransformHandler({
51390
51758
  magicContext: { "experimental.chat.messages.transform": transform },
@@ -51394,6 +51762,10 @@ async function registerContext(context) {
51394
51762
  rustReplayParticipant: () => transform?.getRustReplayParticipant() ?? null
51395
51763
  })({}, mapped);
51396
51764
  mapped.commit();
51765
+ stageOpenCodeV2TransformDecision({
51766
+ sessionId: draft.sessionID,
51767
+ responseAfterSequence
51768
+ });
51397
51769
  if (db) {
51398
51770
  await deliverPendingChannel2(context, db, draft.sessionID, channel1.get(draft.sessionID));
51399
51771
  }
@@ -51560,6 +51932,7 @@ ${baseline}
51560
51932
  db: runDb,
51561
51933
  dreamer: manualDreamer,
51562
51934
  smartNotesEnabled: config.smart_notes.enabled,
51935
+ memoryEnabled: config.memory.enabled,
51563
51936
  projectIdentity: resolveProjectIdentityForSession(directory, config.allow_home_project) ?? "",
51564
51937
  directory,
51565
51938
  language: config.language,
@@ -51610,6 +51983,7 @@ ${baseline}
51610
51983
  await usageDone;
51611
51984
  deletedSessions.clear();
51612
51985
  await dreamTrigger?.dispose();
51986
+ await maintenanceTimer?.dispose();
51613
51987
  for (const release of rawProviders.values())
51614
51988
  release();
51615
51989
  rawProviders.clear();