@cortexkit/pi-magic-context 0.49.28 → 0.49.30

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.
@@ -24,11 +24,11 @@ var [
24
24
  { Database, registerSqliteDiagnosticSink },
25
25
  { log }
26
26
  ] = await Promise.all([
27
- import("./embedding-backfill-25fp3b8w.js"),
27
+ import("./embedding-backfill-v83xh6e8.js"),
28
28
  import("./embedding-cache-7rp4gqzr.js"),
29
29
  import("./storage-memory-0ndn65fm.js"),
30
- import("./project-embedding-registry-hc4ahjdt.js"),
31
- import("./search-vkkfg27q.js"),
30
+ import("./project-embedding-registry-wwbhm9rf.js"),
31
+ import("./search-tgv2rdac.js"),
32
32
  import("./compartment-chunk-embedding-pkk5beqp.js"),
33
33
  import("./embedding-activity-ew6dshfd.js"),
34
34
  import("./harness-9872e0ym.js"),
@@ -33,7 +33,7 @@ import"./index-48twbev2.js";
33
33
  import {
34
34
  LATEST_SUPPORTED_VERSION,
35
35
  enforceSchemaFence
36
- } from "./index-5d506f7y.js";
36
+ } from "./index-y5x5wt5t.js";
37
37
  import"./index-0s14xaca.js";
38
38
  import"./index-g026ztby.js";
39
39
  import"./index-135e8hvg.js";
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  ensureMemoryEmbeddings2
3
- } from "./index-wjbqw6r1.js";
4
- import"./index-xa90f88m.js";
3
+ } from "./index-4nny4r40.js";
4
+ import"./index-0jykn0dw.js";
5
5
  import"./index-9p40dgkm.js";
6
6
  import"./index-yhzhdp3m.js";
7
7
  import"./index-4zemngt7.js";
@@ -52,7 +52,7 @@ import {
52
52
  getProjectEmbeddingSnapshot2,
53
53
  embedTextForProject2,
54
54
  embedItemsForProject2
55
- } from "./index-xa90f88m.js";
55
+ } from "./index-0jykn0dw.js";
56
56
  import {
57
57
  saveEmbeddingIfHashMatches,
58
58
  getProjectEmbeddings2
@@ -62,7 +62,7 @@ import {
62
62
  isEmbeddingEnabled,
63
63
  embedText,
64
64
  ensureMemoryEmbeddings2
65
- } from "./index-wjbqw6r1.js";
65
+ } from "./index-4nny4r40.js";
66
66
  import {
67
67
  getMemorySelectColumns2,
68
68
  isMemoryRow2,
@@ -82,7 +82,7 @@ import {
82
82
  keywordRelevance,
83
83
  matchedSearchSnippet,
84
84
  getIndexedMessageCorpusSize
85
- } from "./index-v0ht940m.js";
85
+ } from "./index-74bc8ts8.js";
86
86
  import {
87
87
  MESSAGE_FTS_SESSION_FILTER_SQL,
88
88
  withMessageFtsSessionFilter
@@ -1529,7 +1529,9 @@ async function indexCommitsForProject(db, projectPath, directory, options) {
1529
1529
  return result;
1530
1530
  }
1531
1531
  if (commits.length === 0) {
1532
- result.evicted = enforceProjectCap(db, projectPath, options.maxCommits);
1532
+ if (!options.skipRetention) {
1533
+ result.evicted = enforceProjectCap(db, projectPath, options.maxCommits);
1534
+ }
1533
1535
  log2(`[git-commits] no new commits for ${projectPath} (sinceMs=${sinceMs} latestIndexed=${latestIndexed?.slice(0, 7) ?? "none"} evicted=${result.evicted})`);
1534
1536
  return result;
1535
1537
  }
@@ -1537,7 +1539,9 @@ async function indexCommitsForProject(db, projectPath, directory, options) {
1537
1539
  const upsert = upsertCommits(db, projectPath, commits);
1538
1540
  result.inserted = upsert.inserted;
1539
1541
  result.updated = upsert.updated;
1540
- result.evicted = enforceProjectCap(db, projectPath, options.maxCommits);
1542
+ if (!options.skipRetention) {
1543
+ result.evicted = enforceProjectCap(db, projectPath, options.maxCommits);
1544
+ }
1541
1545
  const snapshot = getProjectEmbeddingSnapshot2(projectPath);
1542
1546
  if (options.skipEmbed || !snapshot?.gitCommitEnabled) {
1543
1547
  log2(`[git-commits] indexed ${projectPath}: scanned=${result.scanned} inserted=${result.inserted} updated=${result.updated} evicted=${result.evicted} embedded=0 (embedding skipped: skipEmbed=${options.skipEmbed === true} gitCommitEnabled=${snapshot?.gitCommitEnabled === true})`);
@@ -1371,6 +1371,7 @@ function snapshotFor(registration) {
1371
1371
  runtimeFingerprint: registration.runtimeFingerprint,
1372
1372
  generation: registration.generation,
1373
1373
  features: { ...registration.features },
1374
+ ...registration.memoryDisabledReason ? { memoryDisabledReason: registration.memoryDisabledReason } : {},
1374
1375
  enabled,
1375
1376
  historyEnabled,
1376
1377
  gitCommitEnabled,
@@ -2340,7 +2341,7 @@ async function runShadowWorker() {
2340
2341
  await new Promise((resolve) => setTimeout(resolve, 0));
2341
2342
  }
2342
2343
  }
2343
- function registerProjectInObservationMode2(db, projectIdentity, sourceDirectory, failedConfig, failureSummary) {
2344
+ function registerProjectInObservationMode2(db, projectIdentity, sourceDirectory, failedConfig, failureSummary, memoryDisabledReason) {
2344
2345
  const prior = projectRegistrations.get(projectIdentity);
2345
2346
  const runtimeFingerprint = `observation:${sha256Prefix(failureSummary)}`;
2346
2347
  const generation = prior?.runtimeFingerprint === runtimeFingerprint && prior.observationMode ? prior.generation : ++globalRegistrationGeneration;
@@ -2355,7 +2356,8 @@ function registerProjectInObservationMode2(db, projectIdentity, sourceDirectory,
2355
2356
  features: { memoryEnabled: false, gitCommitEnabled: false },
2356
2357
  modelId: "off",
2357
2358
  chunkModelId: "off",
2358
- observationMode: true
2359
+ observationMode: true,
2360
+ memoryDisabledReason
2359
2361
  };
2360
2362
  projectRegistrations.set(projectIdentity, registration);
2361
2363
  disposeProvider(prior?.provider ?? null);
@@ -15,7 +15,7 @@ import {
15
15
  } from "./index-2qtx0q6h.js";
16
16
  import {
17
17
  createFailClosedBlockingError
18
- } from "./index-5d506f7y.js";
18
+ } from "./index-y5x5wt5t.js";
19
19
  import {
20
20
  createWorkerShutdown
21
21
  } from "./index-54wmg4rj.js";
@@ -15,7 +15,7 @@ import {
15
15
  OpenAICompatibleEmbeddingProvider,
16
16
  getProjectEmbeddingSnapshot2,
17
17
  embedBatchForProject2
18
- } from "./index-xa90f88m.js";
18
+ } from "./index-0jykn0dw.js";
19
19
  import {
20
20
  isEmbeddingHostBusy2
21
21
  } from "./index-9p40dgkm.js";
@@ -6,7 +6,7 @@ import {
6
6
  } from "./index-my0dn413.js";
7
7
  import {
8
8
  readRawSessionMessageIdOrdinalsForRange2
9
- } from "./index-kagezf2h.js";
9
+ } from "./index-n2ayqhbx.js";
10
10
 
11
11
  // ../plugin/src/tools/ctx-expand/search-archive.ts
12
12
  var archiveReadsOnThisThread = 0;
@@ -9,7 +9,7 @@ import {
9
9
  } from "./index-my0dn413.js";
10
10
  import {
11
11
  cleanUserText2
12
- } from "./index-kagezf2h.js";
12
+ } from "./index-n2ayqhbx.js";
13
13
  import {
14
14
  recordMessageFtsRowid2,
15
15
  recordIndexedMessageTime2,
@@ -61,13 +61,12 @@ import {
61
61
  logPiCompactionMarkerClear,
62
62
  withReadOnlySessionDb,
63
63
  expandToolPart,
64
- isCoveredInstructionRow,
65
64
  hasRawMessageProvider2,
66
65
  setRawMessageProvider2,
67
66
  visitRawSessionMessages2,
68
67
  readRawSessionMessageById2,
69
68
  readSessionChunk2
70
- } from "./index-kagezf2h.js";
69
+ } from "./index-n2ayqhbx.js";
71
70
  import {
72
71
  isRecord,
73
72
  providerVisibleMessage,
@@ -107,7 +106,7 @@ import {
107
106
  isPidAlive,
108
107
  readProcessStartTime,
109
108
  getErrorMessage
110
- } from "./index-5d506f7y.js";
109
+ } from "./index-y5x5wt5t.js";
111
110
  import {
112
111
  BoundedSessionMap,
113
112
  resolveOpenCodeDbPath,
@@ -141,10 +140,10 @@ import {
141
140
  unregisterProjectEmbedding2,
142
141
  getProjectEmbeddingSnapshot2,
143
142
  embedTextForProject2
144
- } from "./index-xa90f88m.js";
143
+ } from "./index-0jykn0dw.js";
145
144
  import {
146
145
  getLastIndexedOrdinal
147
- } from "./index-v0ht940m.js";
146
+ } from "./index-74bc8ts8.js";
148
147
  import {
149
148
  V2_MEMORY_CATEGORIES,
150
149
  CATEGORY_PRIORITY,
@@ -181,7 +180,7 @@ import {
181
180
  resolveMemoriesByIdsForSearch2,
182
181
  unifiedSearch2,
183
182
  formatSearchResults2
184
- } from "./index-sdsnb5b6.js";
183
+ } from "./index-0cq3g9y5.js";
185
184
  import {
186
185
  computeCueContentHash,
187
186
  getMuralCueState,
@@ -212,7 +211,7 @@ import {
212
211
  } from "./index-6wdwv3a6.js";
213
212
  import {
214
213
  renderSearchArchive2
215
- } from "./index-vea2d9ka.js";
214
+ } from "./index-5qh6z3sn.js";
216
215
  import {
217
216
  computeNormalizedHash
218
217
  } from "./index-9x1f96r8.js";
@@ -273,6 +272,30 @@ function migrateLegacyAgentEnabledInMemory(rawConfig, warnings) {
273
272
  return patched;
274
273
  }
275
274
 
275
+ // ../plugin/src/config/commit-retention-recovery.ts
276
+ var pausedRetention = new WeakSet;
277
+ var RETENTION_FIELD = "memory.git_commit_indexing.max_commits";
278
+ function applyCommitRetentionRecovery(config, recoveredFieldPaths, warnings) {
279
+ if (!recoveredFieldPaths.some((path) => RETENTION_FIELD === path || RETENTION_FIELD.startsWith(`${path}.`)))
280
+ return;
281
+ pausedRetention.add(config.memory.git_commit_indexing);
282
+ const message = `${RETENTION_FIELD}: retention eviction is paused until the invalid value is fixed.`;
283
+ const index = warnings.findIndex((warning) => warning.includes(RETENTION_FIELD));
284
+ if (index >= 0)
285
+ warnings[index] = `${warnings[index]} ${message}`;
286
+ else
287
+ warnings.push(message);
288
+ }
289
+ function isCommitRetentionPaused(settings) {
290
+ return pausedRetention.has(settings);
291
+ }
292
+ function copyCommitRetentionRecovery(from, to) {
293
+ if (pausedRetention.has(from))
294
+ pausedRetention.add(to);
295
+ else
296
+ pausedRetention.delete(to);
297
+ }
298
+
276
299
  // ../plugin/src/shared/config-diagnostics.ts
277
300
  var CONFIG_WARNING_CLASS = {
278
301
  FILE_PARSE: "file-parse",
@@ -2269,7 +2292,11 @@ function restoreTrustedValuesOverInvalidProjectValues(args) {
2269
2292
  if (!changed)
2270
2293
  break;
2271
2294
  }
2272
- return { warnings, restoredTopLevelKeys: [...restoredTopLevelKeys] };
2295
+ return {
2296
+ warnings,
2297
+ restoredTopLevelKeys: [...restoredTopLevelKeys],
2298
+ restoredFieldPaths: [...restored]
2299
+ };
2273
2300
  }
2274
2301
 
2275
2302
  // ../plugin/src/config/prune-config-leaf.ts
@@ -3364,9 +3391,10 @@ function closeConnection(connection) {
3364
3391
  counters.readersClosed += 1;
3365
3392
  }
3366
3393
  }
3367
- function messageTimesQuery(count) {
3394
+ function messageTimesQuery(count, withVersions = false) {
3368
3395
  return `SELECT id, COALESCE(time_created, json_extract(data, '$.time.created')) AS created,
3369
3396
  json_extract(data, '$.time.completed') AS completed
3397
+ ${withVersions ? ", type, seq, time_created AS version_created, time_updated AS version_updated" : ""}
3370
3398
  FROM session_message WHERE +session_id = ? AND id IN (${Array.from({ length: count }, () => "?").join(",")})`;
3371
3399
  }
3372
3400
 
@@ -3591,16 +3619,46 @@ class V2StoreReader {
3591
3619
  return row ? decode(row) : null;
3592
3620
  });
3593
3621
  }
3594
- messageTimes(sessionID, ids) {
3595
- const times = new Map;
3622
+ messageTimeVersions(sessionID, ids, span) {
3623
+ const versions = new Map;
3624
+ if (ids.length > 0 && span && span.last - span.first < ids.length * 2) {
3625
+ const wanted = new Set(ids);
3626
+ const rows = this.prepare(`SELECT id, type, seq, time_created AS created, time_updated AS updated
3627
+ FROM session_message WHERE session_id = ? AND seq >= ? AND seq <= ?`).all(sessionID, span.first, span.last);
3628
+ for (const row of rows)
3629
+ if (wanted.has(row.id))
3630
+ versions.set(row.id, row);
3631
+ for (const [id, version] of this.messageTimeVersions(sessionID, ids.filter((id) => !versions.has(id))))
3632
+ versions.set(id, version);
3633
+ return versions;
3634
+ }
3596
3635
  for (let offset = 0;offset < ids.length; offset += 500) {
3597
3636
  const batch = ids.slice(offset, offset + 500);
3598
- const rows = this.prepare(messageTimesQuery(batch.length)).all(sessionID, ...batch);
3637
+ const rows = this.prepare(`SELECT id, type, seq, time_created AS created, time_updated AS updated
3638
+ FROM session_message WHERE +session_id = ? AND id IN (${batch.map(() => "?").join(",")})`).all(sessionID, ...batch);
3599
3639
  for (const row of rows)
3640
+ versions.set(row.id, row);
3641
+ }
3642
+ return versions;
3643
+ }
3644
+ messageTimes(sessionID, ids, versions) {
3645
+ const times = new Map;
3646
+ for (let offset = 0;offset < ids.length; offset += 500) {
3647
+ const batch = ids.slice(offset, offset + 500);
3648
+ const rows = this.prepare(messageTimesQuery(batch.length, versions !== undefined)).all(sessionID, ...batch);
3649
+ for (const row of rows) {
3600
3650
  times.set(row.id, {
3601
3651
  created: typeof row.created === "number" ? row.created : undefined,
3602
3652
  completed: typeof row.completed === "number" ? row.completed : undefined
3603
3653
  });
3654
+ versions?.set(row.id, {
3655
+ id: row.id,
3656
+ type: row.type,
3657
+ seq: row.seq,
3658
+ created: row.version_created,
3659
+ updated: row.version_updated
3660
+ });
3661
+ }
3604
3662
  }
3605
3663
  return times;
3606
3664
  }
@@ -5529,6 +5587,12 @@ function noteLkgCapturedPrefix(sessionId) {
5529
5587
  }
5530
5588
 
5531
5589
  // ../plugin/src/hooks/magic-context/lkg-slot.ts
5590
+ var POSITIONAL_SYSTEM_KEY = "\x00mc-system:";
5591
+ function lkgInputIdentity(id, role, index) {
5592
+ if (typeof id === "string" && id.length > 0)
5593
+ return id.startsWith(POSITIONAL_SYSTEM_KEY) ? null : id;
5594
+ return role === "system" ? `${POSITIONAL_SYSTEM_KEY}${index}` : null;
5595
+ }
5532
5596
  var LKG_SINGLE_SLOT_BYTES = 72 * 1024 * 1024;
5533
5597
  var LKG_TOTAL_BYTES = 160 * 1024 * 1024;
5534
5598
  var LKG_METADATA_BYTES = 256;
@@ -5957,11 +6021,8 @@ function noteEntry(sessionId, input) {
5957
6021
  const slot = getSlot(sessionId);
5958
6022
  if (!slot)
5959
6023
  return null;
5960
- const messages = input.some((message) => isCoveredInstructionRow(message.info)) ? input.filter((message) => !isCoveredInstructionRow(message.info)) : input;
5961
- const entryInputIds = messages.map((message) => {
5962
- const id = message.info?.id;
5963
- return typeof id === "string" ? id : "";
5964
- });
6024
+ const messages = input;
6025
+ const entryInputIds = messages.map((message, index) => lkgInputIdentity(message.info?.id, message.info?.role, index) ?? "");
5965
6026
  const anchorIndex = entryInputIds.indexOf(slot.lastInputMessageId);
5966
6027
  if (anchorIndex < 0)
5967
6028
  return null;
@@ -10441,28 +10502,28 @@ var EMBEDDING_AFFECTING_KEYS = new Set([
10441
10502
  "embedding.query_instruction",
10442
10503
  "embedding.document_prefix",
10443
10504
  "embedding.fallback_provider",
10444
- "subc",
10505
+ "embedding.local_runtime",
10506
+ "embedding.local_dtype",
10445
10507
  "subc.connection_file",
10446
- "shadow_embedding"
10508
+ "shadow_embedding.enabled",
10509
+ "memory.enabled",
10510
+ "memory.git_commit_indexing.enabled",
10511
+ "allow_home_project"
10447
10512
  ]);
10448
10513
  var LITERAL_CONFIG_TOKEN_RE = /\{(?:env|file):[^}]+\}/;
10449
- function embeddingConfigHasLiteralTokens(embedding) {
10450
- if (!embedding)
10451
- return false;
10452
- for (const value of Object.values(embedding)) {
10514
+ function affectsEmbeddingRegistration(path) {
10515
+ return [...EMBEDDING_AFFECTING_KEYS].some((field) => field === path || field.startsWith(`${path}.`));
10516
+ }
10517
+ function untrustedConfigFieldPaths(detailed) {
10518
+ const paths = (detailed.recoveredFieldPaths ?? detailed.recoveredTopLevelKeys).filter(affectsEmbeddingRegistration);
10519
+ paths.push(...detailed.substitutionFailures.map((failure) => failure.keyPath).filter(affectsEmbeddingRegistration));
10520
+ for (const [key, value] of Object.entries(detailed.config.embedding)) {
10453
10521
  if (typeof value === "string" && LITERAL_CONFIG_TOKEN_RE.test(value)) {
10454
- return true;
10522
+ paths.push(`embedding.${key}`);
10455
10523
  }
10456
10524
  }
10457
- return false;
10525
+ return [...new Set(paths)].sort();
10458
10526
  }
10459
- var EMBEDDING_AFFECTING_TOP_LEVEL_KEYS = new Set([
10460
- "embedding",
10461
- "memory",
10462
- "experimental",
10463
- "subc",
10464
- "shadow_embedding"
10465
- ]);
10466
10527
  var EMBEDDING_WARNING_TERMS = [
10467
10528
  "api_key",
10468
10529
  "endpoint",
@@ -10487,21 +10548,12 @@ function isConfigLoadUntrusted(detailed) {
10487
10548
  return true;
10488
10549
  }
10489
10550
  for (const failure of detailed.substitutionFailures) {
10490
- if (EMBEDDING_AFFECTING_KEYS.has(failure.keyPath)) {
10491
- return true;
10492
- }
10493
10551
  if (failure.keyPath === "<unknown>" && warningLooksEmbeddingRelated(failure.message)) {
10494
10552
  return true;
10495
10553
  }
10496
10554
  }
10497
- for (const recoveredKey of detailed.recoveredTopLevelKeys) {
10498
- if (EMBEDDING_AFFECTING_TOP_LEVEL_KEYS.has(recoveredKey)) {
10499
- return true;
10500
- }
10501
- }
10502
- if (embeddingConfigHasLiteralTokens(detailed.config.embedding)) {
10555
+ if (untrustedConfigFieldPaths(detailed).length > 0)
10503
10556
  return true;
10504
- }
10505
10557
  return false;
10506
10558
  }
10507
10559
  function describeFailure(detailed) {
@@ -10514,8 +10566,9 @@ function describeFailure(detailed) {
10514
10566
  if (detailed.substitutionFailures.length > 0) {
10515
10567
  parts.push(`substitution=${detailed.substitutionFailures.map((failure) => `${failure.source}:${failure.keyPath}`).join(",")}`);
10516
10568
  }
10517
- if (detailed.recoveredTopLevelKeys.length > 0) {
10518
- parts.push(`recovered=${detailed.recoveredTopLevelKeys.join(",")}`);
10569
+ const recovered = detailed.recoveredFieldPaths ?? detailed.recoveredTopLevelKeys;
10570
+ if (recovered.length > 0) {
10571
+ parts.push(`recovered=${recovered.join(",")}`);
10519
10572
  }
10520
10573
  return parts.length > 0 ? parts.join("; ") : detailed.loadOutcome;
10521
10574
  }
@@ -10523,7 +10576,8 @@ function logConfigFailureOnce(projectIdentity, detailed) {
10523
10576
  const signature = sha256Prefix(JSON.stringify({
10524
10577
  outcomes: detailed.sources,
10525
10578
  substitutions: detailed.substitutionFailures.map((failure) => `${failure.source}:${failure.keyPath}:${failure.message}`).sort(),
10526
- recoveredTopLevelKeys: [...detailed.recoveredTopLevelKeys].sort()
10579
+ recoveredTopLevelKeys: [...detailed.recoveredTopLevelKeys].sort(),
10580
+ recoveredFieldPaths: detailed.recoveredFieldPaths?.slice().sort()
10527
10581
  }));
10528
10582
  const existing = loggedFailureSignatures.get(projectIdentity) ?? new Set;
10529
10583
  if (existing.has(signature))
@@ -10539,9 +10593,14 @@ function handleUntrustedLoad(db, projectIdentity, directory, detailed) {
10539
10593
  logConfigFailureOnce(projectIdentity, detailed);
10540
10594
  return true;
10541
10595
  }
10542
- registerProjectInObservationMode2(db, projectIdentity, directory, detailed.config.embedding, describeFailure(detailed));
10596
+ registerProjectInObservationMode2(db, projectIdentity, directory, detailed.config.embedding, describeFailure(detailed), untrustedConfigMemoryMessage(detailed));
10543
10597
  return true;
10544
10598
  }
10599
+ function untrustedConfigMemoryMessage(detailed) {
10600
+ const fields = untrustedConfigFieldPaths(detailed);
10601
+ const cause = fields.length > 0 ? `has invalid embedding or project identity settings: ${fields.join(", ")}` : Object.values(detailed.sources).includes("legacy-config-unmigrated") ? "is awaiting config migration" : Object.values(detailed.sources).some((source) => source === "project-file-parse-error" || source === "project-file-io-error") ? "could not be read or parsed" : "has invalid embedding settings";
10602
+ return `Cross-session memory is off for this project because magic-context.jsonc ${cause}.`;
10603
+ }
10545
10604
 
10546
10605
  // ../plugin/src/plugin/embedding-routing.ts
10547
10606
  var SYNAPSE_PROBE_TTL_MS = 60000;
@@ -10823,7 +10882,7 @@ function mergeRawConfigs(base, override) {
10823
10882
  }
10824
10883
  return merged;
10825
10884
  }
10826
- function parsePiConfig(rawConfig, recoveredTopLevelKeys = []) {
10885
+ function parsePiConfig(rawConfig, recoveredTopLevelKeys = [], recoveredFieldPaths = []) {
10827
10886
  const preMigrationWarnings = [];
10828
10887
  if (Object.hasOwn(rawConfig, "clear_reasoning_age")) {
10829
10888
  preMigrationWarnings.push("clear_reasoning_age is deprecated and ignored. Magic Context now keeps reasoning up to a token budget, keep_reasoning_tokens (default 10,000). Remove the key, or set keep_reasoning_tokens to a token count.");
@@ -10888,10 +10947,12 @@ function parsePiConfig(rawConfig, recoveredTopLevelKeys = []) {
10888
10947
  }
10889
10948
  if (prunedLeaves.length === issuePaths.length) {
10890
10949
  patched[key] = prunedBlock;
10950
+ recoveredFieldPaths.push(...prunedLeaves.map((leaf) => `${key}.${leaf}`));
10891
10951
  warnings.push(`"${key}": invalid nested field(s) ${prunedLeaves.map((leaf) => `"${key}.${leaf}"`).join(", ")}, using defaults for those.`);
10892
10952
  continue;
10893
10953
  }
10894
10954
  }
10955
+ recoveredFieldPaths.push(key);
10895
10956
  if (isAgentConfig) {
10896
10957
  delete patched[key];
10897
10958
  warnings.push(`"${key}": invalid agent configuration, ignoring. Check your magic-context.jsonc.`);
@@ -10911,6 +10972,7 @@ function parsePiConfig(rawConfig, recoveredTopLevelKeys = []) {
10911
10972
  return { config: retryParsed.data, warnings };
10912
10973
  }
10913
10974
  warnings.push("Config recovery failed, using all defaults.");
10975
+ recoveredFieldPaths.push("embedding", "memory", "subc", "shadow_embedding", "allow_home_project");
10914
10976
  return { config: defaults, warnings };
10915
10977
  }
10916
10978
  function collectPiSchemaIssuePaths(rawConfig) {
@@ -11041,6 +11103,7 @@ function loadPiConfigDetailed(opts = {}, applyRuntimeGlobals = true) {
11041
11103
  let rawConfig = trustedProfiledRaw;
11042
11104
  const trustedBaseConfig = parsePiConfig(trustedProfiledRaw).config;
11043
11105
  let projectRestoredTopLevelKeys = [];
11106
+ let projectRestoredFieldPaths = [];
11044
11107
  if (projectLayer) {
11045
11108
  rawConfig = mergeRawConfigs(rawConfig, profileResolution.projectBase);
11046
11109
  for (const warning of dropInheritedEmbeddingKeyOnRedirect(projectRaw, rawConfig, profileResolution.userBase)) {
@@ -11063,11 +11126,14 @@ function loadPiConfigDetailed(opts = {}, applyRuntimeGlobals = true) {
11063
11126
  warnings.push(`[project config] ${warning}`);
11064
11127
  }
11065
11128
  projectRestoredTopLevelKeys = restoredOverProject.restoredTopLevelKeys;
11129
+ projectRestoredFieldPaths = restoredOverProject.restoredFieldPaths;
11066
11130
  }
11067
11131
  const hasDeprecatedProtectedTags = Object.hasOwn(userRaw, "protected_tags") || Object.hasOwn(projectRaw, "protected_tags") || Object.hasOwn(rawConfig, "protected_tags");
11068
11132
  const recoveredTopLevelKeys = [];
11133
+ const recoveredFieldPaths = [];
11069
11134
  const cacheTtlConfigured = Object.hasOwn(rawConfig, "cache_ttl");
11070
- const parsed = parsePiConfig(rawConfig, recoveredTopLevelKeys);
11135
+ const parsed = parsePiConfig(rawConfig, recoveredTopLevelKeys, recoveredFieldPaths);
11136
+ recoveredFieldPaths.push(...projectRestoredFieldPaths);
11071
11137
  Object.defineProperty(parsed.config, "cacheTtlConfigured", {
11072
11138
  value: cacheTtlConfigured
11073
11139
  });
@@ -11084,6 +11150,7 @@ function loadPiConfigDetailed(opts = {}, applyRuntimeGlobals = true) {
11084
11150
  if (applyRuntimeGlobals) {
11085
11151
  setOutputReserveConfig(parsed.config.output_reserve);
11086
11152
  }
11153
+ applyCommitRetentionRecovery(parsed.config, recoveredFieldPaths, parsed.warnings);
11087
11154
  warnings.push(...parsed.warnings.map((warning) => `[merged config] ${warning}`));
11088
11155
  const substitutionFailures = loadedFiles.flatMap(bindSubstitutionFailures);
11089
11156
  const userLoaded = loadedFiles.find((loaded) => loaded.scope === "user");
@@ -11113,6 +11180,7 @@ function loadPiConfigDetailed(opts = {}, applyRuntimeGlobals = true) {
11113
11180
  sources,
11114
11181
  substitutionFailures,
11115
11182
  recoveredTopLevelKeys,
11183
+ recoveredFieldPaths,
11116
11184
  configParseFailures,
11117
11185
  warningDetails,
11118
11186
  cacheTtlConfigured,
@@ -12748,7 +12816,7 @@ function createCtxMemoryTool(deps) {
12748
12816
  const memoryOwnedByTool = (memory) => workspaceIdentitySet.identities.length > 1 ? targetIdentityForStoredPath(memory.projectPath) === projectIdentity : storedPathBelongsToIdentity(memory.projectPath, projectIdentity);
12749
12817
  const snapshot = getProjectEmbeddingSnapshot2(projectIdentity);
12750
12818
  if (snapshot ? !snapshot.features.memoryEnabled : deps.memoryEnabled === false) {
12751
- return err2("Cross-session memory is disabled for this project.");
12819
+ return err2(snapshot?.memoryDisabledReason ?? "Cross-session memory is disabled for this project.");
12752
12820
  }
12753
12821
  const sessionId = ctx.sessionManager.getSessionId();
12754
12822
  let curateSuccessor = null;
@@ -14853,4 +14921,4 @@ function registerMagicContextTools(pi, opts) {
14853
14921
  }
14854
14922
  }
14855
14923
 
14856
- export { COMPACTION_ENABLED_PATH, isDreamerRunnable, isCompactionEnabled, formatConfigParseStatusLine, formatConfigParseNotice, claimConfigParseFailuresOnce, parseJsoncRecovering, detectConfigFile, OPENCODE_OUTPUT_CAP, MIN_PLAUSIBLE_CONTEXT_LIMIT, catalogOutputReserve, deriveWindowGeometry, hasTrustedAbsoluteWall, applyProvenInputFloor, formatWindowDerivationLine, formatWindowSource, isSaneLimit, resolveOutputReserve, getSdkWindowGeometry, getSdkContextLimit, getSdkOutputLimit, getSdkInputLimit, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, migrateMagicContextConfigLocations, getProtectedTokensTierOverrides, LkgRecoveryFenceError, clearLkgFenceProcessState, lkgFenceRequiresRebuild, lkgRecoveryFenceUnclean, ownsLkgDirtyFence, invalidateCleanLkgRecoveryFence, markLkgRecoveryDirty, rememberUnpublishedAutoSearchNoHint, getUnpublishedAutoSearchNoHint, forgetUnpublishedAutoSearchNoHint, registerAutoSearchWork, cancelAutoSearchWork, readSessionActivity, observeSessionActivity, backfillSessionActivity, readSessionMeta, getOrCreateSessionMeta, updateSessionMeta, advanceToolReclaimWatermark, retryPendingSessionCleanups, retryPendingRustSessionCleanupsForProject, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLease, releaseCompartmentLeaseBestEffort, isCompartmentLeaseHeld, isNoContentCompartment, HAS_COMPARTMENT_CONTENT_SQL, queueM0Mutation, getMaxM0MutationId, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getCompartmentsByEndMessageId, appendCompartments, saveRecompStagingPass, getRecompStaging, clearRecompStaging, getRecompPartialRange, setRecompPartialRange, escapeXmlAttr, escapeXmlContent, getUncoveredCompartmentEndThrough, isPartialCompartmentEnd, readProjectDocsCanonical, providerResponseFailed, isSuccessfulProviderCompletion, requestPendingMaterialization, pendingMaterializationOrigin, hasPendingMaterializationOrigin, clearPendingMaterialization, recordSystemRefreshOwnership, recordSystemPromptForRequest, recordHeldHeadForRequest, bindSystemPromptResponse, acknowledgeSystemPromptDelivery, deferDeliveredSystemRefresh, clearSystemPromptDelivery, saveLkgSlotToDb, loadPersistedLkgSlot, drainStaleLkgSlots, createDbLkgPersistence, replayLkg, registerLkgPersistence, LKG_SNAPSHOT_ARRAY, LKG_SNAPSHOT_OBJECT, LKG_SNAPSHOT_KEY, LKG_SNAPSHOT_STRING, LKG_SNAPSHOT_NUMBER, LKG_SNAPSHOT_BOOLEAN, LKG_SNAPSHOT_NULL, LKG_SNAPSHOT_UNDEFINED, contentSnapshotValue, signatureForFields, lkgContentFields, lkgContentDigestFromFields, isLegacyLkgDigest, legacyLkgDigestFromFields, lkgFieldsMatchDigest, exactReusablePrefix, incrementalLkgContentDigests, lkgSlotRejection, captureSlot, getInMemorySlot, getSlot, dropSlot, TOOL_SWEEP_SCOPED_MARKER, encodePiContentDecision, decodePiContentDecision, getPiContentDecisions, freezePiContentDecision, getNativeReplayState, saveNativeToolInputs, addNativeReasoningIds, copySessionStateForClone, externalHistorianFailureReason, subprocessExitHistorianFailureReason, countHistorianRuns, recordHistorianRun, summarizeImportance, tallyFactsByCategory, queueMemoryMutation, getMemoryMutationsForRender, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationId, getMaxMemoryMutationIdForProjects, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectUserProfileVersion, saveSourceContent, getSourceContents, recordSubagentInvocation, getLatestHistorianInvocationId, noteTouchedAt, noteNudgePickIndex, formatNoteNudge, systemPromptFingerprint, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, SYNTH_USER_ID_PREFIX, resolvePiStableId, resolvePiRealStableId, isPiContentFallbackId, isPiIndexFallbackId, piContentFallbackIds, readPiSessionSnapshot, readPiSessionMessages, readPiSessionMessagePage, findRestartModelSeedFromBranch, iterateEntriesToRawMessageRange, iterateAsyncEntriesToRawMessageRange, convertEntriesToRawMessages, convertPiAssistantEntryById, convertEntriesToRawMessagePage, countPiRawMessages, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getTaskScheduleState, getFailingDreamTasks, getSkippedDreamTasks, getMostRecentTaskRunAt, pruneNonCanonicalTaskRows, deleteTaskScheduleRowsForProject, seedTaskScheduleState, writeTaskScheduleState, isRetrospectiveWindowProcessed, recordRetrospectiveWindowProcessed, curateCategoryForMemoryCategory, peekCurateCategoryScope, beginCurateCategoryRun, curateTaskStateAfterSuccess, MEMORY_MURAL_BLOCK, buildMagicContextSection, resolveMuralWire, updateCompactionMarkerAfterPublication, COMPARTMENT_RENDER_EPOCH, MEMORY_RENDER_FORMAT_EPOCH, encodeCachedM0UpgradeIdentity, decodeCachedM0UpgradeIdentity, withCachedM0MemoryIds, readCachedM0MemoryIds, renderBudgetIdentityChanged, renderedBudgetSnapshot, renderedBudgetShrinkReason, DEFAULT_HISTORY_BUDGET_TOKENS, renderCompartmentAtTier, renderDecayedCompartments, extractM0Block, TEMPORAL_MARKER_PATTERN, TEMPORAL_MARKER_REPLAY_PATTERN, temporalMarkerPrefix, renderUserProfileContent, clearInjectionCache, getVisibleMemoryIds, orderHistorianMemories, renderHistorianMemoryBlock, DEFAULT_MEMORY_BUDGET_TOKENS, DEFAULT_USER_PROFILE_BUDGET_TOKENS, trimMemoriesToBudgetV2, trimWorkspaceMemoriesToBudgetV2, trimUserMemoriesToBudget, renderMemoryBlockV2, stripMemoryMuralBlock, resetPrefixTrimFallbackState, isDirectiveShapedProjectRule, takeCurateSafetyRefusalCount, wakePlaneStatus, loadPiConfig, loadPiConfigDetailed, unregisterPiProjectEmbeddings, ensureProjectRegisteredFromPiDirectory, neutralizeOmpMentions, restoreOmpMentions, resolvePiHarnessDetection, resolvePiHarnessKind, resolvePiOrdinalAlignment, piRawOrdinalOffsetSource, resolvePiOrdinalAlignmentForContext, isPiOrdinalAlignmentUnanchored, clearPiOrdinalAlignmentSession, rememberTodowriteToolCallTodos, parseTodos, setTodoSnapshot, registerTodoOverlay, registerTodoStateLifecycle, syncCtxMemoryToolEnabled, registerMagicContextTools };
14924
+ export { COMPACTION_ENABLED_PATH, isDreamerRunnable, isCompactionEnabled, isCommitRetentionPaused, copyCommitRetentionRecovery, formatConfigParseStatusLine, formatConfigParseNotice, claimConfigParseFailuresOnce, parseJsoncRecovering, detectConfigFile, OPENCODE_OUTPUT_CAP, MIN_PLAUSIBLE_CONTEXT_LIMIT, catalogOutputReserve, deriveWindowGeometry, hasTrustedAbsoluteWall, applyProvenInputFloor, formatWindowDerivationLine, formatWindowSource, isSaneLimit, resolveOutputReserve, getSdkWindowGeometry, getSdkContextLimit, getSdkOutputLimit, getSdkInputLimit, cortexKitUserConfigBasePath, cortexKitProjectConfigBasePath, migrateMagicContextConfigLocations, getProtectedTokensTierOverrides, LkgRecoveryFenceError, clearLkgFenceProcessState, lkgFenceRequiresRebuild, lkgRecoveryFenceUnclean, ownsLkgDirtyFence, invalidateCleanLkgRecoveryFence, markLkgRecoveryDirty, rememberUnpublishedAutoSearchNoHint, getUnpublishedAutoSearchNoHint, forgetUnpublishedAutoSearchNoHint, registerAutoSearchWork, cancelAutoSearchWork, readSessionActivity, observeSessionActivity, backfillSessionActivity, readSessionMeta, getOrCreateSessionMeta, updateSessionMeta, advanceToolReclaimWatermark, retryPendingSessionCleanups, retryPendingRustSessionCleanupsForProject, COMPARTMENT_LEASE_RENEWAL_MS, acquireCompartmentLease, renewCompartmentLease, releaseCompartmentLease, releaseCompartmentLeaseBestEffort, isCompartmentLeaseHeld, isNoContentCompartment, HAS_COMPARTMENT_CONTENT_SQL, queueM0Mutation, getMaxM0MutationId, getCompartments, getLastCompartmentEndMessage, getLastCompartmentEndMessageId, getCompartmentsByEndMessageId, appendCompartments, saveRecompStagingPass, getRecompStaging, clearRecompStaging, getRecompPartialRange, setRecompPartialRange, escapeXmlAttr, escapeXmlContent, getUncoveredCompartmentEndThrough, isPartialCompartmentEnd, readProjectDocsCanonical, providerResponseFailed, isSuccessfulProviderCompletion, requestPendingMaterialization, pendingMaterializationOrigin, hasPendingMaterializationOrigin, clearPendingMaterialization, recordSystemRefreshOwnership, recordSystemPromptForRequest, recordHeldHeadForRequest, bindSystemPromptResponse, acknowledgeSystemPromptDelivery, deferDeliveredSystemRefresh, clearSystemPromptDelivery, saveLkgSlotToDb, loadPersistedLkgSlot, drainStaleLkgSlots, createDbLkgPersistence, replayLkg, registerLkgPersistence, LKG_SNAPSHOT_ARRAY, LKG_SNAPSHOT_OBJECT, LKG_SNAPSHOT_KEY, LKG_SNAPSHOT_STRING, LKG_SNAPSHOT_NUMBER, LKG_SNAPSHOT_BOOLEAN, LKG_SNAPSHOT_NULL, LKG_SNAPSHOT_UNDEFINED, contentSnapshotValue, signatureForFields, lkgContentFields, lkgContentDigestFromFields, isLegacyLkgDigest, legacyLkgDigestFromFields, lkgFieldsMatchDigest, exactReusablePrefix, incrementalLkgContentDigests, lkgSlotRejection, captureSlot, getInMemorySlot, getSlot, dropSlot, TOOL_SWEEP_SCOPED_MARKER, encodePiContentDecision, decodePiContentDecision, getPiContentDecisions, freezePiContentDecision, getNativeReplayState, saveNativeToolInputs, addNativeReasoningIds, copySessionStateForClone, externalHistorianFailureReason, subprocessExitHistorianFailureReason, countHistorianRuns, recordHistorianRun, summarizeImportance, tallyFactsByCategory, queueMemoryMutation, getMemoryMutationsForRender, getMemoryMutationsForRenderByProjects, getMaxMemoryMutationId, getMaxMemoryMutationIdForProjects, GLOBAL_USER_PROFILE_PROJECT_PATH, getProjectState, bumpProjectUserProfileVersion, saveSourceContent, getSourceContents, recordSubagentInvocation, getLatestHistorianInvocationId, noteTouchedAt, noteNudgePickIndex, formatNoteNudge, systemPromptFingerprint, createPromptSurfaceRuntime, createPromptSurfaceGuidanceEpochCache, SYNTH_USER_ID_PREFIX, resolvePiStableId, resolvePiRealStableId, isPiContentFallbackId, isPiIndexFallbackId, piContentFallbackIds, readPiSessionSnapshot, readPiSessionMessages, readPiSessionMessagePage, findRestartModelSeedFromBranch, iterateEntriesToRawMessageRange, iterateAsyncEntriesToRawMessageRange, convertEntriesToRawMessages, convertPiAssistantEntryById, convertEntriesToRawMessagePage, countPiRawMessages, USER_MEMORY_CANDIDATE_TTL_MS, insertUserMemoryCandidates, getUserMemoryCandidates, deleteUserMemoryCandidates, pruneExpiredUserMemoryCandidates, insertUserMemory, getActiveUserMemories, updateUserMemoryContent, dismissUserMemory, getTaskScheduleState, getFailingDreamTasks, getSkippedDreamTasks, getMostRecentTaskRunAt, pruneNonCanonicalTaskRows, deleteTaskScheduleRowsForProject, seedTaskScheduleState, writeTaskScheduleState, isRetrospectiveWindowProcessed, recordRetrospectiveWindowProcessed, curateCategoryForMemoryCategory, peekCurateCategoryScope, beginCurateCategoryRun, curateTaskStateAfterSuccess, MEMORY_MURAL_BLOCK, buildMagicContextSection, resolveMuralWire, updateCompactionMarkerAfterPublication, COMPARTMENT_RENDER_EPOCH, MEMORY_RENDER_FORMAT_EPOCH, encodeCachedM0UpgradeIdentity, decodeCachedM0UpgradeIdentity, withCachedM0MemoryIds, readCachedM0MemoryIds, renderBudgetIdentityChanged, renderedBudgetSnapshot, renderedBudgetShrinkReason, DEFAULT_HISTORY_BUDGET_TOKENS, renderCompartmentAtTier, renderDecayedCompartments, extractM0Block, TEMPORAL_MARKER_PATTERN, TEMPORAL_MARKER_REPLAY_PATTERN, temporalMarkerPrefix, renderUserProfileContent, clearInjectionCache, getVisibleMemoryIds, orderHistorianMemories, renderHistorianMemoryBlock, DEFAULT_MEMORY_BUDGET_TOKENS, DEFAULT_USER_PROFILE_BUDGET_TOKENS, trimMemoriesToBudgetV2, trimWorkspaceMemoriesToBudgetV2, trimUserMemoriesToBudget, renderMemoryBlockV2, stripMemoryMuralBlock, resetPrefixTrimFallbackState, isDirectiveShapedProjectRule, takeCurateSafetyRefusalCount, wakePlaneStatus, loadPiConfig, loadPiConfigDetailed, unregisterPiProjectEmbeddings, ensureProjectRegisteredFromPiDirectory, neutralizeOmpMentions, restoreOmpMentions, resolvePiHarnessDetection, resolvePiHarnessKind, resolvePiOrdinalAlignment, piRawOrdinalOffsetSource, resolvePiOrdinalAlignmentForContext, isPiOrdinalAlignmentUnanchored, clearPiOrdinalAlignmentSession, rememberTodowriteToolCallTodos, parseTodos, setTodoSnapshot, registerTodoOverlay, registerTodoStateLifecycle, syncCtxMemoryToolEnabled, registerMagicContextTools };
@@ -2784,8 +2784,8 @@ function resolveEpochFloorForPass(db, sessionId, inputs) {
2784
2784
  }
2785
2785
 
2786
2786
  // ../plugin/src/hooks/magic-context/read-session-db.ts
2787
- function openCodeDbExists() {
2788
- return harnessOwnsOpenCodeStore2() && openCodeDbPathExists(resolveOpenCodeDbPath());
2787
+ function openCodeDbExists(generation = "v1") {
2788
+ return harnessOwnsOpenCodeStore2() && openCodeDbPathExists(resolveOpenCodeDbPath(generation));
2789
2789
  }
2790
2790
  var cachedReadOnlyDbs = {
2791
2791
  v1: null,
@@ -2808,7 +2808,7 @@ function getReadOnlySessionDb(generation = "v1") {
2808
2808
  if (!harnessOwnsOpenCodeStore2()) {
2809
2809
  throw new Error("OpenCode session database is not readable from a Pi-compatible process; its history lives in Pi sessions");
2810
2810
  }
2811
- const resolution = resolveOpenCodeDbPath();
2811
+ const resolution = resolveOpenCodeDbPath(generation);
2812
2812
  const dbPath = resolution.path;
2813
2813
  if (!openCodeDbPathExists(resolution)) {
2814
2814
  throw new Error(`OpenCode session database is unavailable at ${dbPath} (source=${resolution.source})`);
@@ -2829,8 +2829,8 @@ function getReadOnlySessionDb(generation = "v1") {
2829
2829
  clearOpenCodeDbReadFailure();
2830
2830
  return db;
2831
2831
  }
2832
- function withReadOnlySessionDb(fn) {
2833
- return fn(getReadOnlySessionDb());
2832
+ function withReadOnlySessionDb(fn, generation = "v1") {
2833
+ return fn(getReadOnlySessionDb(generation));
2834
2834
  }
2835
2835
  function getRawSessionMessageCountFromDb(db, sessionId) {
2836
2836
  const row = db.prepare(`SELECT COUNT(*) as count FROM message WHERE session_id = ?
@@ -3027,10 +3027,6 @@ function retreatPastHostUnservedRows(messages, exclusiveEnd, floor) {
3027
3027
  end -= 1;
3028
3028
  return end;
3029
3029
  }
3030
- var COVERED_INSTRUCTION_ROW = "coveredInstructionRow";
3031
- function isCoveredInstructionRow(value) {
3032
- return typeof value === "object" && value !== null && value[COVERED_INSTRUCTION_ROW] === true;
3033
- }
3034
3030
 
3035
3031
  // ../plugin/src/hooks/magic-context/read-session-true-raw-tokens.ts
3036
3032
  function completedToolArcCrossesBoundary(invOrdinal, resOrdinal, boundary) {
@@ -4020,9 +4016,15 @@ function hasAnthropicReasoning(messages) {
4020
4016
  });
4021
4017
  }
4022
4018
 
4019
+ // ../plugin/src/shared/marker-only-text.ts
4020
+ var MARKER_ONLY_PATTERN = /^(?:(?:§\d+§|\[dropped\s*(?:\d+|§\d*§)?\]|\[cleared\])\s*)+$/;
4021
+ function isMarkerOnlyText(text) {
4022
+ const trimmed = text.trim();
4023
+ return trimmed.length > 0 && MARKER_ONLY_PATTERN.test(trimmed);
4024
+ }
4025
+
4023
4026
  // ../plugin/src/hooks/magic-context/served-shape-repair.ts
4024
4027
  var sources = new WeakMap;
4025
-
4026
4028
  // ../plugin/src/hooks/magic-context/strip-content.ts
4027
4029
  var METADATA_PART_TYPES = new Set([
4028
4030
  "step-start",
@@ -5043,6 +5045,10 @@ function readSessionChunk2(sessionId, tokenBudget, offset = 1, eligibleEndOrdina
5043
5045
  const meta = { ordinal: msg.ordinal, messageId: msg.id };
5044
5046
  if (isHostUnservedRow(msg))
5045
5047
  markHostUnservedRow(meta);
5048
+ if (msg.role === "system") {
5049
+ recordFilteredNoise(meta);
5050
+ continue;
5051
+ }
5046
5052
  if (msg.role === "user" && !hasMeaningfulChunkUserText(msg.parts)) {
5047
5053
  const tcSummaries = msg.parts.flatMap((part) => {
5048
5054
  if (expandedResults.has(part))
@@ -5214,4 +5220,4 @@ function readRawSessionSeedTail2(sessionId, boundaryId, onQuery) {
5214
5220
  });
5215
5221
  }
5216
5222
 
5217
- export { detectThinkingBindingMismatch, detectLatestTurnThinkingMismatch, isPrefixBoundThinkingModel, detectOverflow, MAX_EXECUTE_THRESHOLD, escalationBands, MERGED_REASONING_PARTS_PREFIX, decodeMergedReasoningParts, HYGIENE_PROVIDER_UNITS_VERSION, sessionDecisionCalibration, transitionSessionHygieneUnits, computeProtectionWindow, readEpochFloorSnapshot, getProtectionWindowForSession, SESSION_META_SELECT_COLUMNS, META_COLUMNS, BOOLEAN_META_KEYS, NULL_BIND_META_KEYS, isSessionMetaRow, getDefaultSessionMeta, ensureSessionMetaRow, toSessionMeta, persistCachedM0, clearCachedM0M1, isRustMarkerAdmissionFenced, ReplayDocumentError, readReplayEnvelope, readReplayDocument, updateReplayDocument, writeReplayDocument, isProviderOverflowFailClosedProven, getEmergencyRecoveryArmedAt, describeProtectedTailDrainBudgetSkip, loadProtectedTailMeta, markProtectedTailPolicyV3Seeded, recordProtectedTailPublicationFloor, recordProtectedTailNoEligibleHead, getWrapupInProgressState, isWrapupInProgress, acquireWrapupInProgress, updateWrapupInProgress, releaseWrapupInProgress, resolveCompactionModeRecord, getCompactionModeRecord, setCompactionModeRecord, EMERGENCY_DRAIN_FAILURE_BACKOFF_MS, getProtectedTailDrainBudgetSkip, reserveProtectedTailDrainTokens, clearEmergencyDrainLatch, recordHistorianDrainFailure, clearHistorianDrainFailure, rollbackProtectedTailDrainReservation, clearPersistedReasoningWatermark, getEmergencyInputSample, setEmergencyDropSample, clearEmergencyDropSample, getLastNudgeUndropped, setLastNudgeUndropped, getChannel1NudgeState, setChannel1NudgeState, markChannel1PostReduceGracePending, captureChannel1PostReduceGraceBaseline, getChannel2NudgeState, getChannel2NudgeClaim, setChannel2NudgeState, casChannel2NudgeState, claimChannel2NudgeState, casChannel2NudgeClaim, getPersistedNoteNudge, setPersistedNoteNudgeTrigger, setPersistedNoteNudgeTriggerMessageId, getNoteNudgeAnchors, getAutoSearchHintDecisions, deliverNoteNudgeAtomic, appendAutoSearchHintDecision, pruneNoteNudgeAnchors, queueAutoSearchHintDecisionRetirement, flushAutoSearchHintDecisionRetirement, getPersistedTodoSyntheticAnchor, setPersistedTodoSyntheticAnchor, clearPersistedTodoSyntheticAnchor, getNoteLastReadAt, setNoteLastReadAt, getHistorianFailureState, incrementHistorianFailure, clearHistorianFailureState, getOverflowState, recordOverflowDetected, clearEmergencyRecovery, clearDetectedContextLimit, getPersistedCompactionMarkerState, setPersistedCompactionMarkerState, parseStrippedPlaceholderState, serializeStrippedPlaceholderState, getStrippedPlaceholderIds, applyStrippedPlaceholderDelta, THINKING_BINDING_RECOVERY_FROZEN_PREFIX, THINKING_BINDING_STRIP_ORDER_END_MARKER, thinkingBindingRecoveryFrozenId, COMPACTION_OFF_THINKING_FROZEN_PREFIX, getThinkingBindingRecoveryTarget, armThinkingBindingRecovery, clearThinkingBindingRecoveryIf, getMergedReasoningStrippedIds, addMergedReasoningStrippedIds, getProcessedImageStrippedIds, parseProcessedImageMarkers, serializeProcessedImageMarkers, addProcessedImageStrippedIds, getPendingCompactionMarkerState, getCompactionMarkerHealth, loadPostprocessReplaySnapshot, clearPendingCompactionMarkerStateIf, getPendingPiCompactionMarkerState, setPendingPiCompactionMarkerState, clearPendingPiCompactionMarkerStateIf, logPiCompactionMarkerClear, getSessionsWithPendingPiMarker, setSessionWorkMetrics, getSessionWorkMetrics, resolveEpochFloorForPass, withReadOnlySessionDb, expandToolPart, askAnswerLines, retreatPastHostUnservedRows, isCoveredInstructionRow, completedToolArcCrossesBoundary, estimateTrueRawMessageTokens, buildToolArcs, fenceBoundaryForCompletedToolArcs, fenceBoundaryForToolArcs, buildTrueRawTokenIndex, computeRawRangeFingerprint, invalidateTrueRawTokenCache, stripSystemInjection, isFilePart, hasUserAnswerMetadata, DreamTokenBudgetExceeded, TOKEN_BUDGET_FINALIZE_MESSAGE, TOKEN_BUDGET_TOOL_REFUSAL, registerBudgetFinalizeChild, releaseBudgetFinalizeChild, createDreamTokenBudget, droppedInputMarker, createDroppedInputGuard, isEditTool, applyEditMarkerToInput, modelAcceptsEmptyContent, isAnthropicFamilyRoute, variantChangeBustsProviderCache, isInActiveAnthropicTurn, activeAnthropicTurnStart, hasAnthropicReasoning, findLatestAssistantReasoningMutationExemptMessage, DEFAULT_KEEP_REASONING_TOKENS, resolveKeepReasoningTokens, reasoningStepCost, reasoningBudgetCutoff, reasoningTextAndOpaque, opaqueThinkingCost, estimatePartImageTokens, SKELETON_REAL_INPUT_MAX_BYTES, toolInputStringBytes, resolveHostServedBoundaryId2, hasRawMessageProvider2, setRawMessageProvider2, setBoundedRawMessageProvider2, withRawMessageProvider2, cleanUserText2, withRawSessionMessageCache2, readRawSessionMessages2, readRawSessionMessagePage2, getRawSessionMessageOrdinalCount2, RAW_MESSAGE_VISIT_PAGE_SIZE2, visitRawSessionMessages2, visitRawSessionMessagesAsync2, readRawSessionMessageRange2, prepareRawSessionOrdinals2, primeTailRawMessageCache2, getCachedAbsoluteMessageCount2, primeInMemoryTailRawMessageCache2, readRawSessionMessageOrdinalPage2, getRawSessionStoredMessageCount2, readRawSessionMessageIdOrdinalsForRange2, readRawSessionMessageIdOrdinals2, readRawSessionMessagePartsById2, readRawSessionBoundaryEndpoints2, hasRawSessionMessageById2, readRawSessionMessageOrdinalById2, resolveHistorianChunkStart2, compareRawSessionMessageOrder2, readRawSessionMessageById2, getRawSessionMessageCount2, RAW_SESSION_TAG_KEY_PAGE_SIZE2, getRawSessionTagKeysThrough2, getLegacyProtectedTailStartOrdinal2, getProtectedTailStartOrdinal2, readSessionChunk2, getRawSessionMessageIdsThrough2, readRawSessionSeedTail2 };
5223
+ export { detectThinkingBindingMismatch, detectLatestTurnThinkingMismatch, isPrefixBoundThinkingModel, detectOverflow, MAX_EXECUTE_THRESHOLD, escalationBands, MERGED_REASONING_PARTS_PREFIX, decodeMergedReasoningParts, HYGIENE_PROVIDER_UNITS_VERSION, sessionDecisionCalibration, transitionSessionHygieneUnits, computeProtectionWindow, readEpochFloorSnapshot, getProtectionWindowForSession, SESSION_META_SELECT_COLUMNS, META_COLUMNS, BOOLEAN_META_KEYS, NULL_BIND_META_KEYS, isSessionMetaRow, getDefaultSessionMeta, ensureSessionMetaRow, toSessionMeta, persistCachedM0, clearCachedM0M1, isRustMarkerAdmissionFenced, ReplayDocumentError, readReplayEnvelope, readReplayDocument, updateReplayDocument, writeReplayDocument, isProviderOverflowFailClosedProven, getEmergencyRecoveryArmedAt, describeProtectedTailDrainBudgetSkip, loadProtectedTailMeta, markProtectedTailPolicyV3Seeded, recordProtectedTailPublicationFloor, recordProtectedTailNoEligibleHead, getWrapupInProgressState, isWrapupInProgress, acquireWrapupInProgress, updateWrapupInProgress, releaseWrapupInProgress, resolveCompactionModeRecord, getCompactionModeRecord, setCompactionModeRecord, EMERGENCY_DRAIN_FAILURE_BACKOFF_MS, getProtectedTailDrainBudgetSkip, reserveProtectedTailDrainTokens, clearEmergencyDrainLatch, recordHistorianDrainFailure, clearHistorianDrainFailure, rollbackProtectedTailDrainReservation, clearPersistedReasoningWatermark, getEmergencyInputSample, setEmergencyDropSample, clearEmergencyDropSample, getLastNudgeUndropped, setLastNudgeUndropped, getChannel1NudgeState, setChannel1NudgeState, markChannel1PostReduceGracePending, captureChannel1PostReduceGraceBaseline, getChannel2NudgeState, getChannel2NudgeClaim, setChannel2NudgeState, casChannel2NudgeState, claimChannel2NudgeState, casChannel2NudgeClaim, getPersistedNoteNudge, setPersistedNoteNudgeTrigger, setPersistedNoteNudgeTriggerMessageId, getNoteNudgeAnchors, getAutoSearchHintDecisions, deliverNoteNudgeAtomic, appendAutoSearchHintDecision, pruneNoteNudgeAnchors, queueAutoSearchHintDecisionRetirement, flushAutoSearchHintDecisionRetirement, getPersistedTodoSyntheticAnchor, setPersistedTodoSyntheticAnchor, clearPersistedTodoSyntheticAnchor, getNoteLastReadAt, setNoteLastReadAt, getHistorianFailureState, incrementHistorianFailure, clearHistorianFailureState, getOverflowState, recordOverflowDetected, clearEmergencyRecovery, clearDetectedContextLimit, getPersistedCompactionMarkerState, setPersistedCompactionMarkerState, parseStrippedPlaceholderState, serializeStrippedPlaceholderState, getStrippedPlaceholderIds, applyStrippedPlaceholderDelta, THINKING_BINDING_RECOVERY_FROZEN_PREFIX, THINKING_BINDING_STRIP_ORDER_END_MARKER, thinkingBindingRecoveryFrozenId, COMPACTION_OFF_THINKING_FROZEN_PREFIX, getThinkingBindingRecoveryTarget, armThinkingBindingRecovery, clearThinkingBindingRecoveryIf, getMergedReasoningStrippedIds, addMergedReasoningStrippedIds, getProcessedImageStrippedIds, parseProcessedImageMarkers, serializeProcessedImageMarkers, addProcessedImageStrippedIds, getPendingCompactionMarkerState, getCompactionMarkerHealth, loadPostprocessReplaySnapshot, clearPendingCompactionMarkerStateIf, getPendingPiCompactionMarkerState, setPendingPiCompactionMarkerState, clearPendingPiCompactionMarkerStateIf, logPiCompactionMarkerClear, getSessionsWithPendingPiMarker, setSessionWorkMetrics, getSessionWorkMetrics, resolveEpochFloorForPass, withReadOnlySessionDb, expandToolPart, askAnswerLines, retreatPastHostUnservedRows, completedToolArcCrossesBoundary, estimateTrueRawMessageTokens, buildToolArcs, fenceBoundaryForCompletedToolArcs, fenceBoundaryForToolArcs, buildTrueRawTokenIndex, computeRawRangeFingerprint, invalidateTrueRawTokenCache, stripSystemInjection, isFilePart, hasUserAnswerMetadata, DreamTokenBudgetExceeded, TOKEN_BUDGET_FINALIZE_MESSAGE, TOKEN_BUDGET_TOOL_REFUSAL, registerBudgetFinalizeChild, releaseBudgetFinalizeChild, createDreamTokenBudget, droppedInputMarker, createDroppedInputGuard, isEditTool, applyEditMarkerToInput, modelAcceptsEmptyContent, isAnthropicFamilyRoute, variantChangeBustsProviderCache, isInActiveAnthropicTurn, activeAnthropicTurnStart, hasAnthropicReasoning, isMarkerOnlyText, findLatestAssistantReasoningMutationExemptMessage, DEFAULT_KEEP_REASONING_TOKENS, resolveKeepReasoningTokens, reasoningStepCost, reasoningBudgetCutoff, reasoningTextAndOpaque, opaqueThinkingCost, estimatePartImageTokens, SKELETON_REAL_INPUT_MAX_BYTES, toolInputStringBytes, resolveHostServedBoundaryId2, hasRawMessageProvider2, setRawMessageProvider2, setBoundedRawMessageProvider2, withRawMessageProvider2, cleanUserText2, withRawSessionMessageCache2, readRawSessionMessages2, readRawSessionMessagePage2, getRawSessionMessageOrdinalCount2, RAW_MESSAGE_VISIT_PAGE_SIZE2, visitRawSessionMessages2, visitRawSessionMessagesAsync2, readRawSessionMessageRange2, prepareRawSessionOrdinals2, primeTailRawMessageCache2, getCachedAbsoluteMessageCount2, primeInMemoryTailRawMessageCache2, readRawSessionMessageOrdinalPage2, getRawSessionStoredMessageCount2, readRawSessionMessageIdOrdinalsForRange2, readRawSessionMessageIdOrdinals2, readRawSessionMessagePartsById2, readRawSessionBoundaryEndpoints2, hasRawSessionMessageById2, readRawSessionMessageOrdinalById2, resolveHistorianChunkStart2, compareRawSessionMessageOrder2, readRawSessionMessageById2, getRawSessionMessageCount2, RAW_SESSION_TAG_KEY_PAGE_SIZE2, getRawSessionTagKeysThrough2, getLegacyProtectedTailStartOrdinal2, getProtectedTailStartOrdinal2, readSessionChunk2, getRawSessionMessageIdsThrough2, readRawSessionSeedTail2 };
@@ -2003,7 +2003,7 @@ function finishDatabaseOpen(db, dbPath, explicitDbPath, latestSupportedVersion)
2003
2003
  state.running = startMessageFtsRowidMapBackfill2(db, signal).then(async () => {
2004
2004
  if (signal.aborted || !readsOpenCodeStore)
2005
2005
  return;
2006
- const { readRawSessionMessagePage, readRawSessionMessages } = await importPluginModule(() => import("./read-session-chunk-1rfprgc1.js"));
2006
+ const { readRawSessionMessagePage, readRawSessionMessages } = await importPluginModule(() => import("./read-session-chunk-73kd0ans.js"));
2007
2007
  const { startMessageTimeBackfill } = await importPluginModule(() => import("./message-time-backfill-e3r8ddh1.js"));
2008
2008
  if (signal.aborted)
2009
2009
  return;
package/dist/index.js CHANGED
@@ -22,6 +22,8 @@ import {
22
22
  COMPACTION_ENABLED_PATH,
23
23
  isDreamerRunnable,
24
24
  isCompactionEnabled,
25
+ isCommitRetentionPaused,
26
+ copyCommitRetentionRecovery,
25
27
  formatConfigParseStatusLine,
26
28
  formatConfigParseNotice,
27
29
  claimConfigParseFailuresOnce,
@@ -260,7 +262,7 @@ import {
260
262
  registerTodoStateLifecycle,
261
263
  syncCtxMemoryToolEnabled,
262
264
  registerMagicContextTools
263
- } from "./index-bkcwcghx.js";
265
+ } from "./index-gxjppvsh.js";
264
266
  import"./index-4knyh1kt.js";
265
267
  import {
266
268
  canonicalModelIdentity,
@@ -302,7 +304,7 @@ import {
302
304
  openCurrentDatabase,
303
305
  openDatabaseAsync,
304
306
  closeDatabase
305
- } from "./index-5d506f7y.js";
307
+ } from "./index-y5x5wt5t.js";
306
308
  import {
307
309
  sameProjectDirectory,
308
310
  pruneMissingProjectIdentities,
@@ -448,6 +450,7 @@ import {
448
450
  isInActiveAnthropicTurn,
449
451
  activeAnthropicTurnStart,
450
452
  hasAnthropicReasoning,
453
+ isMarkerOnlyText,
451
454
  findLatestAssistantReasoningMutationExemptMessage,
452
455
  DEFAULT_KEEP_REASONING_TOKENS,
453
456
  resolveKeepReasoningTokens,
@@ -478,7 +481,7 @@ import {
478
481
  getRawSessionTagKeysThrough2,
479
482
  getLegacyProtectedTailStartOrdinal2,
480
483
  readSessionChunk2
481
- } from "./index-kagezf2h.js";
484
+ } from "./index-n2ayqhbx.js";
482
485
  import {
483
486
  UNKNOWN_FIT_RATIO,
484
487
  hasMeasuredDecisionCalibration,
@@ -596,6 +599,7 @@ import {
596
599
  stableStringify,
597
600
  closeQuietly,
598
601
  isKnownAutocommit,
602
+ getTableColumnNames,
599
603
  observeTemporalDecisions,
600
604
  freezeTemporalDecisions,
601
605
  tagIdentityRevisionKey
@@ -665,7 +669,7 @@ import {
665
669
  embedSessionCompartmentChunks2,
666
670
  getEmbeddingCoverageStatus2,
667
671
  getAutoEmbeddingSessionCoverage2
668
- } from "./index-xa90f88m.js";
672
+ } from "./index-0jykn0dw.js";
669
673
  import {
670
674
  clearCompressionDepth,
671
675
  clearCompressionDepthRange,
@@ -678,7 +682,7 @@ import {
678
682
  isMessageIndexReconciledThrough,
679
683
  indexSingleMessage,
680
684
  indexMessagesAfterOrdinal
681
- } from "./index-v0ht940m.js";
685
+ } from "./index-74bc8ts8.js";
682
686
  import {
683
687
  rememberV1HiddenRun
684
688
  } from "./index-6x556c2q.js";
@@ -743,7 +747,7 @@ import {
743
747
  normalizeVerificationFiles,
744
748
  indexCommitsForProject,
745
749
  embedUnembeddedCommits
746
- } from "./index-sdsnb5b6.js";
750
+ } from "./index-0cq3g9y5.js";
747
751
  import {
748
752
  setEmbeddingSessionBusy2,
749
753
  isEmbeddingHostBusy2
@@ -779,7 +783,7 @@ import {
779
783
  } from "./index-wqpjhx1p.js";
780
784
  import {
781
785
  cosineSimilarity
782
- } from "./index-wjbqw6r1.js";
786
+ } from "./index-4nny4r40.js";
783
787
  import"./index-6wdwv3a6.js";
784
788
  import {
785
789
  DREAMER_PRIMER_INVESTIGATOR_ALLOWED_TOOLS,
@@ -807,10 +811,10 @@ import {
807
811
  drainPiTagSnapshotSession,
808
812
  assertPiTagSnapshotReady,
809
813
  ensurePiTagSnapshotReady
810
- } from "./index-xw070axm.js";
814
+ } from "./index-2pnhk4gc.js";
811
815
  import"./index-jn44h81p.js";
812
816
  import"./index-1cvyaw9a.js";
813
- import"./index-vea2d9ka.js";
817
+ import"./index-5qh6z3sn.js";
814
818
  import {
815
819
  __toESM
816
820
  } from "./index-22jkk6wg.js";
@@ -1169,7 +1173,13 @@ function sampleLiveConfig(boot, fresh) {
1169
1173
  if (leaf !== undefined)
1170
1174
  target[leaf] = value;
1171
1175
  }
1172
- return result;
1176
+ const sampled = result;
1177
+ const freshCommitIndexing = fresh.memory?.git_commit_indexing;
1178
+ const sampledCommitIndexing = sampled.memory?.git_commit_indexing;
1179
+ if (freshCommitIndexing && sampledCommitIndexing) {
1180
+ copyCommitRetentionRecovery(freshCommitIndexing, sampledCommitIndexing);
1181
+ }
1182
+ return sampled;
1173
1183
  }
1174
1184
  function removeLeaf(root, parts) {
1175
1185
  const parents = parts.slice(0, -1);
@@ -3549,7 +3559,7 @@ function startHostStallProfilerSwitch() {
3549
3559
  // package.json
3550
3560
  var package_default = {
3551
3561
  name: "@cortexkit/pi-magic-context",
3552
- version: "0.49.28",
3562
+ version: "0.49.30",
3553
3563
  type: "module",
3554
3564
  description: "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
3555
3565
  main: "dist/index.js",
@@ -10937,7 +10947,7 @@ async function runHiddenSingleShotPrompt(args) {
10937
10947
  let timer;
10938
10948
  try {
10939
10949
  const completion = await Promise.race([
10940
- args.executor.collect(handle, 200),
10950
+ args.executor.collectPartial?.(handle, 200) ?? args.executor.collect(handle, 200),
10941
10951
  new Promise((resolve) => {
10942
10952
  timer = setTimeout(() => resolve(null), 5000);
10943
10953
  })
@@ -13580,6 +13590,7 @@ Remember: output only the JSON object described by the system prompt.`;
13580
13590
  let childSessionId = null;
13581
13591
  let promptSettled = false;
13582
13592
  let invocationRecorded = false;
13593
+ let completionUsage;
13583
13594
  const recordInvocation = (params) => {
13584
13595
  if (!args.db || !args.parentSessionId || invocationRecorded)
13585
13596
  return;
@@ -13593,6 +13604,7 @@ Remember: output only the JSON object described by the system prompt.`;
13593
13604
  startedAt,
13594
13605
  status: params.status,
13595
13606
  messages: params.messages,
13607
+ tokens: args.hiddenCompletionExecutor?.capabilities.harness === "opencode2" ? completionUsage : undefined,
13596
13608
  attemptedModel: args.model,
13597
13609
  configuredModels: args.fallbackModels,
13598
13610
  error: params.error
@@ -13617,11 +13629,15 @@ Remember: output only the JSON object described by the system prompt.`;
13617
13629
  timeoutMs: remainingMs,
13618
13630
  signal: args.signal,
13619
13631
  metadata: { task: "evaluate-smart-notes" },
13632
+ onFailureOutput: (completion) => {
13633
+ completionUsage = completion.usage;
13634
+ },
13620
13635
  parse: parseCompilerOutput
13621
13636
  });
13622
13637
  promptSettled = true;
13623
13638
  response = carried.validated;
13624
13639
  outputMessages = carried.completion.messages;
13640
+ completionUsage = carried.completion.usage;
13625
13641
  } else {
13626
13642
  const client = args.client;
13627
13643
  if (!client) {
@@ -14342,6 +14358,7 @@ async function confirmReadOnly(args, noteId, content, surfaceCondition, leaseSig
14342
14358
  startedAt,
14343
14359
  status: params.status,
14344
14360
  messages: params.messages,
14361
+ tokens: args.hiddenCompletionExecutor?.capabilities.harness === "opencode2" ? params.tokens : undefined,
14345
14362
  attemptedModel: args.model,
14346
14363
  configuredModels: args.fallbackModels,
14347
14364
  error: params.error
@@ -14369,7 +14386,11 @@ async function confirmReadOnly(args, noteId, content, surfaceCondition, leaseSig
14369
14386
  parse: parseConfirmationVerdict
14370
14387
  });
14371
14388
  promptSettled = true;
14372
- recordInvocation({ status: "completed", messages: run.completion.messages });
14389
+ recordInvocation({
14390
+ status: "completed",
14391
+ messages: run.completion.messages,
14392
+ tokens: run.completion.usage
14393
+ });
14373
14394
  return run.validated;
14374
14395
  } finally {
14375
14396
  promptSignal.cleanup();
@@ -15037,7 +15058,8 @@ async function mapOneBatch(args, batch, sliceMs, signal) {
15037
15058
  });
15038
15059
  recordInvocation2(args, startedAt, {
15039
15060
  status: "completed",
15040
- messages: run.completion.messages ?? []
15061
+ messages: run.completion.messages ?? [],
15062
+ tokens: run.completion.usage
15041
15063
  });
15042
15064
  stage = "apply";
15043
15065
  const outcome = await applyParsedBatchMappings(args, batch, run.validated, budgetFinalized, true);
@@ -15112,7 +15134,8 @@ async function mapOneBatch(args, batch, sliceMs, signal) {
15112
15134
  recordInvocation2(args, startedAt, {
15113
15135
  status: failedInvocationStatus(error),
15114
15136
  error,
15115
- messages
15137
+ messages,
15138
+ tokens: failedCompletion?.usage
15116
15139
  });
15117
15140
  if (error instanceof DreamerModuleFailureError)
15118
15141
  throw error;
@@ -15279,6 +15302,7 @@ function recordInvocation2(args, startedAt, params) {
15279
15302
  startedAt,
15280
15303
  status: params.status,
15281
15304
  messages: params.messages,
15305
+ tokens: args.hiddenCompletionExecutor?.capabilities.harness === "opencode2" ? params.tokens : undefined,
15282
15306
  attemptedModel: args.model,
15283
15307
  configuredModels: args.fallbackModels,
15284
15308
  error: params.error
@@ -16530,7 +16554,8 @@ async function git2(root, args) {
16530
16554
  cwd: root,
16531
16555
  timeout: 1e4,
16532
16556
  maxBuffer: MAX_DIFF_BYTES,
16533
- encoding: "utf8"
16557
+ encoding: "utf8",
16558
+ windowsHide: true
16534
16559
  });
16535
16560
  return stdout;
16536
16561
  }
@@ -17172,7 +17197,8 @@ async function verifyOneBatch(args, batch, sliceMs, signal) {
17172
17197
  });
17173
17198
  recordInvocation4(args, startedAt, {
17174
17199
  status: "completed",
17175
- messages: run.completion.messages ?? []
17200
+ messages: run.completion.messages ?? [],
17201
+ tokens: run.completion.usage
17176
17202
  });
17177
17203
  reportUsage(run.completion.messages ?? [], run.childSessionId, run.completion.usage.input + (run.completion.usage.cacheRead ?? 0) + (run.completion.usage.cacheWrite ?? 0));
17178
17204
  return await applyParsedVerifyManifest(args, batch, run.validated, evidence?.head ?? headAtPrompt, budgetFinalized);
@@ -17246,7 +17272,8 @@ async function verifyOneBatch(args, batch, sliceMs, signal) {
17246
17272
  recordInvocation4(args, startedAt, {
17247
17273
  status: failedInvocationStatus(error),
17248
17274
  error,
17249
- messages
17275
+ messages,
17276
+ tokens: failedCompletion?.usage
17250
17277
  });
17251
17278
  if (error instanceof DreamerModuleFailureError || signal.aborted)
17252
17279
  throw error;
@@ -17505,6 +17532,7 @@ function recordInvocation4(args, startedAt, params) {
17505
17532
  startedAt,
17506
17533
  status: params.status,
17507
17534
  messages: params.messages,
17535
+ tokens: args.hiddenCompletionExecutor?.capabilities.harness === "opencode2" ? params.tokens : undefined,
17508
17536
  attemptedModel: args.model,
17509
17537
  configuredModels: args.fallbackModels,
17510
17538
  error: params.error
@@ -17574,6 +17602,15 @@ function classifyFailure(error) {
17574
17602
  const transient = explicitTransient || name === "AbortError" || /abort|lease|timeout|timed out|econn|socket|network|rate.?limit|429|503|overloaded|sqlite_busy|database is locked/.test(combined);
17575
17603
  return { transient, brief };
17576
17604
  }
17605
+ function sumCompletionUsages(usages) {
17606
+ return usages.reduce((total, usage) => ({
17607
+ input: total.input + usage.input,
17608
+ output: total.output + usage.output,
17609
+ cacheRead: total.cacheRead + usage.cacheRead,
17610
+ cacheWrite: total.cacheWrite + usage.cacheWrite,
17611
+ ...total.reasoning !== undefined || usage.reasoning !== undefined ? { reasoning: (total.reasoning ?? 0) + (usage.reasoning ?? 0) } : {}
17612
+ }), emptyTokenTotals());
17613
+ }
17577
17614
  function newIds(beforeIds, afterIds) {
17578
17615
  const before = new Set(beforeIds);
17579
17616
  const out = [];
@@ -18381,6 +18418,7 @@ async function runRetrospectiveTask(config, ctx, helpers) {
18381
18418
  }, ctx.leaseAcquisition);
18382
18419
  let childSessionId = null;
18383
18420
  let hiddenHandle = null;
18421
+ const hiddenUsages = [];
18384
18422
  let promptSettled = false;
18385
18423
  let invocationRecorded = false;
18386
18424
  const recordInvocation = (status, messages, error) => {
@@ -18396,6 +18434,7 @@ async function runRetrospectiveTask(config, ctx, helpers) {
18396
18434
  startedAt: helpers.invocationStartedAt,
18397
18435
  status,
18398
18436
  messages,
18437
+ tokens: deps.hiddenCompletionExecutor?.capabilities.harness === "opencode2" && hiddenUsages.length ? sumCompletionUsages(hiddenUsages) : undefined,
18399
18438
  attemptedModel: config.model,
18400
18439
  configuredModels: config.fallbackModels,
18401
18440
  error
@@ -18481,6 +18520,8 @@ async function runRetrospectiveTask(config, ctx, helpers) {
18481
18520
  }
18482
18521
  });
18483
18522
  promptSettled = true;
18523
+ if (hiddenHandle)
18524
+ hiddenUsages.push(run.output.usage);
18484
18525
  const output = hiddenHandle ? run.output.messages ?? [] : run.output;
18485
18526
  return { ...run, output };
18486
18527
  };
@@ -18651,6 +18692,7 @@ async function runAgenticTask(config, ctx, helpers) {
18651
18692
  let childSessionId = null;
18652
18693
  let promptSettled = false;
18653
18694
  let expiredArchived = 0;
18695
+ const hiddenUsages = [];
18654
18696
  let invocationRecorded = false;
18655
18697
  const recordInvocation = (status, messages, error) => {
18656
18698
  if (!parent || !childSessionId || invocationRecorded)
@@ -18665,6 +18707,7 @@ async function runAgenticTask(config, ctx, helpers) {
18665
18707
  startedAt: invocationStartedAt,
18666
18708
  status,
18667
18709
  messages,
18710
+ tokens: deps.hiddenCompletionExecutor?.capabilities.harness === "opencode2" && hiddenUsages.length ? sumCompletionUsages(hiddenUsages) : undefined,
18668
18711
  attemptedModel: config.model,
18669
18712
  configuredModels: config.fallbackModels,
18670
18713
  error
@@ -18782,6 +18825,7 @@ async function runAgenticTask(config, ctx, helpers) {
18782
18825
  }
18783
18826
  });
18784
18827
  childSessionId = hidden.childSessionId;
18828
+ hiddenUsages.push(hidden.completion.usage);
18785
18829
  run = { output: hidden.completion.messages ?? [], validated: hidden.validated };
18786
18830
  promptSettled = true;
18787
18831
  } else {
@@ -19917,7 +19961,8 @@ async function sweepGitCommits(args) {
19917
19961
  try {
19918
19962
  const result = await indexCommitsForProject(db, projectIdentity, directory, {
19919
19963
  sinceDays: gitCommitIndexing.since_days,
19920
- maxCommits: gitCommitIndexing.max_commits
19964
+ maxCommits: gitCommitIndexing.max_commits,
19965
+ skipRetention: isCommitRetentionPaused(gitCommitIndexing)
19921
19966
  });
19922
19967
  if (result.nonIndexable) {
19923
19968
  if (!parkGitSweepNonIndexable(db, projectIdentity, holderId)) {
@@ -33337,6 +33382,26 @@ async function executeContextRecompWithResult(deps, options = {}) {
33337
33382
  }
33338
33383
 
33339
33384
  // ../plugin/src/hooks/magic-context/history-boundary-repair.ts
33385
+ function readStoreBoundaries(db, sessionId) {
33386
+ const columns = getTableColumnNames(db, "compartments");
33387
+ const numbers = ["id", "sequence", "start_message", "end_message", "created_at"];
33388
+ const strings = ["session_id", "start_message_id", "end_message_id", "title", "content"];
33389
+ const predicates = [...numbers, ...strings].every((column) => columns.has(column)) ? [
33390
+ ...numbers.map((column) => `typeof(${column}) IN ('integer', 'real')`),
33391
+ ...strings.map((column) => `typeof(${column}) = 'text'`)
33392
+ ] : ["0"];
33393
+ for (const column of ["p1", "p2", "p3", "p4", "episode_type"]) {
33394
+ if (columns.has(column))
33395
+ predicates.push(`typeof(${column}) IN ('text', 'null')`);
33396
+ }
33397
+ for (const column of ["importance", "legacy"]) {
33398
+ if (columns.has(column))
33399
+ predicates.push(`typeof(${column}) IN ('integer', 'real', 'null')`);
33400
+ }
33401
+ return db.prepare(`SELECT sequence, ${columns.has("end_message_id") ? "end_message_id" : "NULL"} AS endMessageId
33402
+ FROM compartments WHERE session_id = ? AND ${predicates.join(" AND ")}
33403
+ ORDER BY sequence ASC`).all(sessionId);
33404
+ }
33340
33405
  function readBaseline(db, sessionId) {
33341
33406
  const row = db.prepare("SELECT cached_m0_bytes IS NOT NULL AS hasM0, cached_m0_last_baseline_end_message_id AS boundary FROM session_meta WHERE session_id = ?").get(sessionId);
33342
33407
  return {
@@ -33403,7 +33468,7 @@ function dropCompartmentsAfter(db, sessionId, anchor, holderId, activeBranch = f
33403
33468
  }
33404
33469
  function repairMissingHistoryBoundary(args) {
33405
33470
  const { db, sessionId, isInHostStore, scope = "store" } = args;
33406
- const compartments = scope === "active-branch" ? db.prepare("SELECT sequence, COALESCE(end_message_id, '') AS endMessageId FROM compartments WHERE session_id = ? ORDER BY sequence").all(sessionId) : getCompartments(db, sessionId);
33471
+ const compartments = scope === "active-branch" ? db.prepare("SELECT sequence, COALESCE(end_message_id, '') AS endMessageId FROM compartments WHERE session_id = ? ORDER BY sequence").all(sessionId) : readStoreBoundaries(db, sessionId);
33407
33472
  let latestIndex = compartments.length - 1;
33408
33473
  while (latestIndex >= 0 && !compartments[latestIndex]?.endMessageId)
33409
33474
  latestIndex -= 1;
@@ -33447,7 +33512,7 @@ function repairMissingHistoryBoundary(args) {
33447
33512
  let dropped;
33448
33513
  let anchorForDrop = anchor;
33449
33514
  try {
33450
- if (scope === "active-branch" && anchor) {
33515
+ if (anchor) {
33451
33516
  const row = db.prepare("SELECT end_message AS endMessage FROM compartments WHERE session_id = ? AND sequence = ?").get(sessionId, anchor.sequence);
33452
33517
  if (!row)
33453
33518
  return { kind: "unresolved", reason: "busy", missingEndMessageId: missing };
@@ -41974,11 +42039,6 @@ function replayPiReminderStrips(args) {
41974
42039
  }
41975
42040
 
41976
42041
  // src/strip-placeholders-pi.ts
41977
- var MARKER_ONLY_PATTERN = /^(?:(?:§\d+§|\[dropped(?: §\d+§)?\]|\[cleared\])\s*)+$/;
41978
- function isPiMarkerOnlyText(text) {
41979
- const trimmed = text.trim();
41980
- return trimmed.length > 0 && MARKER_ONLY_PATTERN.test(trimmed);
41981
- }
41982
42042
  function messageIsPlaceholderOnly(message) {
41983
42043
  if (!message || typeof message !== "object")
41984
42044
  return false;
@@ -41986,7 +42046,7 @@ function messageIsPlaceholderOnly(message) {
41986
42046
  if (msg.role !== "assistant")
41987
42047
  return false;
41988
42048
  if (typeof msg.content === "string")
41989
- return msg.content.trim().length === 0 || isPiMarkerOnlyText(msg.content);
42049
+ return msg.content.trim().length === 0 || isMarkerOnlyText(msg.content);
41990
42050
  if (!Array.isArray(msg.content))
41991
42051
  return false;
41992
42052
  if (msg.content.length === 0)
@@ -42000,7 +42060,7 @@ function messageIsPlaceholderOnly(message) {
42000
42060
  if (typeof text !== "string")
42001
42061
  return false;
42002
42062
  sawVisibleContent = true;
42003
- if (text.trim().length > 0 && !isPiMarkerOnlyText(text))
42063
+ if (text.trim().length > 0 && !isMarkerOnlyText(text))
42004
42064
  return false;
42005
42065
  }
42006
42066
  return sawVisibleContent;
@@ -13,7 +13,7 @@ import"./index-399p688g.js";
13
13
  import"./index-54wmg4rj.js";
14
14
  import"./index-6981g1xv.js";
15
15
  import"./index-23t8ryqw.js";
16
- import"./index-kagezf2h.js";
16
+ import"./index-n2ayqhbx.js";
17
17
  import"./index-6x556c2q.js";
18
18
  import {
19
19
  MESSAGE_INDEX_MAX_FTS_BYTES,
@@ -22,7 +22,7 @@ import {
22
22
  markMessageIndexDirty,
23
23
  getIndexableContent,
24
24
  indexSingleMessage
25
- } from "./index-v0ht940m.js";
25
+ } from "./index-74bc8ts8.js";
26
26
  import"./index-bvpar0bg.js";
27
27
  import"./index-hqw0rt9k.js";
28
28
 
@@ -18,7 +18,7 @@ import"./index-48twbev2.js";
18
18
  import {
19
19
  setSqlitePragmaConfig,
20
20
  initializeDatabase
21
- } from "./index-5d506f7y.js";
21
+ } from "./index-y5x5wt5t.js";
22
22
  import"./index-fapenpch.js";
23
23
  import"./index-399p688g.js";
24
24
  import"./index-54wmg4rj.js";
@@ -33,7 +33,7 @@ import {
33
33
  sweepAllRegisteredProjects2,
34
34
  _setTestProviderFactoryForProject2,
35
35
  _resetProjectEmbeddingRegistryForTests2
36
- } from "./index-xa90f88m.js";
36
+ } from "./index-0jykn0dw.js";
37
37
  import"./index-9p40dgkm.js";
38
38
  import"./index-yhzhdp3m.js";
39
39
  import"./index-4zemngt7.js";
@@ -51,7 +51,7 @@ async function main() {
51
51
  await runMessageFtsRowidMapBackfill(db);
52
52
  reply = { kind: "fts-rowid-backfill" };
53
53
  } else if (input.searchArchive) {
54
- const { renderSearchArchive } = await import("./search-archive-mpjeecwj.js");
54
+ const { renderSearchArchive } = await import("./search-archive-ck531w6h.js");
55
55
  const { readRawSessionMessageIdOrdinalsForRangeFromDb } = await import("./read-session-raw-g9b1zdn5.js");
56
56
  const archive = input.searchArchive;
57
57
  let raw;
@@ -81,7 +81,7 @@ async function main() {
81
81
  const { setHarness } = await import("./harness-9872e0ym.js");
82
82
  setHarness(input.harness ?? "opencode");
83
83
  const [{ indexMessageInShortChunks }, { configureContextDatabasePragmas }] = await Promise.all([
84
- import("./message-index-bounded-avbaa7wa.js"),
84
+ import("./message-index-bounded-vkqx693v.js"),
85
85
  import("./sqlite-context-pragmas-gcgch6qz.js")
86
86
  ]);
87
87
  configureContextDatabasePragmas(db);
@@ -36,7 +36,7 @@ import {
36
36
  readSessionChunk2,
37
37
  getRawSessionMessageIdsThrough2,
38
38
  readRawSessionSeedTail2
39
- } from "./index-kagezf2h.js";
39
+ } from "./index-n2ayqhbx.js";
40
40
  import"./index-0x1c054v.js";
41
41
  import"./index-6x556c2q.js";
42
42
  import"./index-ccanzg8p.js";
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  renderSearchArchive2
3
- } from "./index-vea2d9ka.js";
3
+ } from "./index-5qh6z3sn.js";
4
4
  import"./index-1cvyaw9a.js";
5
- import"./index-kagezf2h.js";
5
+ import"./index-n2ayqhbx.js";
6
6
  import"./index-0x1c054v.js";
7
7
  import"./index-6x556c2q.js";
8
8
  import"./index-ccanzg8p.js";
@@ -5,17 +5,17 @@ import {
5
5
  resolveMemoriesByIdsForSearch2,
6
6
  unifiedSearch2,
7
7
  formatSearchResults2
8
- } from "./index-sdsnb5b6.js";
8
+ } from "./index-0cq3g9y5.js";
9
9
  import"./index-1cvyaw9a.js";
10
- import"./index-v0ht940m.js";
11
- import"./index-wjbqw6r1.js";
12
- import"./index-xa90f88m.js";
10
+ import"./index-74bc8ts8.js";
11
+ import"./index-4nny4r40.js";
12
+ import"./index-0jykn0dw.js";
13
13
  import"./index-9p40dgkm.js";
14
14
  import"./index-29nw7n1r.js";
15
15
  import"./index-yhzhdp3m.js";
16
16
  import"./index-4zemngt7.js";
17
17
  import"./index-kmk3xpf9.js";
18
- import"./index-kagezf2h.js";
18
+ import"./index-n2ayqhbx.js";
19
19
  import"./index-0x1c054v.js";
20
20
  import"./index-6x556c2q.js";
21
21
  import"./index-wqpjhx1p.js";
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  TOKEN_BUDGET_TOOL_REFUSAL
3
- } from "./index-kagezf2h.js";
3
+ } from "./index-n2ayqhbx.js";
4
4
  import {
5
5
  setHarness2
6
6
  } from "./index-0h2mkab2.js";
@@ -13,7 +13,7 @@ import {
13
13
  import"./index-2qtx0q6h.js";
14
14
  import {
15
15
  openDatabase
16
- } from "./index-5d506f7y.js";
16
+ } from "./index-y5x5wt5t.js";
17
17
  import"./index-fapenpch.js";
18
18
  import"./index-399p688g.js";
19
19
  import"./index-54wmg4rj.js";
@@ -30,22 +30,22 @@ import {
30
30
  ensureProjectRegisteredFromPiDirectory,
31
31
  resolvePiHarnessKind,
32
32
  registerMagicContextTools
33
- } from "./index-bkcwcghx.js";
33
+ } from "./index-gxjppvsh.js";
34
34
  import"./index-ccanzg8p.js";
35
35
  import"./index-gwxaz0z5.js";
36
36
  import"./index-kmk3xpf9.js";
37
37
  import"./index-wqpjhx1p.js";
38
- import"./index-xa90f88m.js";
38
+ import"./index-0jykn0dw.js";
39
39
  import"./index-9p40dgkm.js";
40
40
  import"./index-4zemngt7.js";
41
41
  import"./index-yhzhdp3m.js";
42
- import"./index-wjbqw6r1.js";
43
- import"./index-v0ht940m.js";
42
+ import"./index-4nny4r40.js";
43
+ import"./index-74bc8ts8.js";
44
44
  import"./index-0x1c054v.js";
45
45
  import"./index-6x556c2q.js";
46
- import"./index-sdsnb5b6.js";
46
+ import"./index-0cq3g9y5.js";
47
47
  import"./index-1cvyaw9a.js";
48
- import"./index-vea2d9ka.js";
48
+ import"./index-5qh6z3sn.js";
49
49
  import"./index-29nw7n1r.js";
50
50
  import"./index-6wdwv3a6.js";
51
51
  import"./index-hqw0rt9k.js";
@@ -7,7 +7,7 @@ import"./index-fgs78jyd.js";
7
7
  import {
8
8
  LATEST_SUPPORTED_VERSION,
9
9
  getPersistedSchemaVersion
10
- } from "./index-5d506f7y.js";
10
+ } from "./index-y5x5wt5t.js";
11
11
  import"./index-fapenpch.js";
12
12
  import"./index-399p688g.js";
13
13
  import {
@@ -30,7 +30,7 @@ import {
30
30
  encodePiHydrationOperation,
31
31
  PI_FALLBACK_ROW_COLUMNS,
32
32
  PI_FALLBACK_ROW_PREDICATE
33
- } from "./index-xw070axm.js";
33
+ } from "./index-2pnhk4gc.js";
34
34
  import"./index-hqw0rt9k.js";
35
35
 
36
36
  // src/tag-snapshot-worker-pi.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/pi-magic-context",
3
- "version": "0.49.28",
3
+ "version": "0.49.30",
4
4
  "type": "module",
5
5
  "description": "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
6
6
  "main": "dist/index.js",