@cortexkit/pi-magic-context 0.49.55 → 0.49.56

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.
@@ -70,7 +70,7 @@ import {
70
70
  renderMessageByOrdinal2,
71
71
  renderVerboseRange2,
72
72
  renderItemByTag2
73
- } from "./index-k2z7r444.js";
73
+ } from "./index-ywmt8sdr.js";
74
74
  import {
75
75
  getLastIndexedOrdinal
76
76
  } from "./index-2pptpxq8.js";
@@ -140,8 +140,8 @@ async function serveV2ArchiveReads2(port, openConnections) {
140
140
  import("./store-reader-mmfw2h48.js"),
141
141
  import("./store-0hhs1db3.js"),
142
142
  import("./read-session-chunk-jyfcykg4.js"),
143
- import("./render-bqqx15n8.js"),
144
- import("./search-archive-31054zxj.js"),
143
+ import("./render-gj0nzrg0.js"),
144
+ import("./search-archive-vpxem4pj.js"),
145
145
  import("./expand-attachments-8sxeyj26.js")
146
146
  ]);
147
147
  const pool = new V2StoreReaderPool;
@@ -559,6 +559,28 @@ function resolveIsSubagentFromOpenCode2Db(sessionId) {
559
559
  }
560
560
  }
561
561
 
562
+ // ../plugin/src/features/magic-context/pi-identity-fold-guards.ts
563
+ var PI_IDENTITY_FOLD_GUARD_PREFIX = "pi_identity_fold_guards:";
564
+ var PI_IDENTITY_FOLD_GUARD_LIMIT = 16384;
565
+ function piIdentityFoldGuardKey(sessionId) {
566
+ return `${PI_IDENTITY_FOLD_GUARD_PREFIX}${sessionId}`;
567
+ }
568
+ function readPiIdentityFoldGuards(db, sessionId) {
569
+ const row = db.prepare("SELECT value FROM schema_migrations_meta WHERE key = ?").get(piIdentityFoldGuardKey(sessionId));
570
+ if (!row)
571
+ return new Set;
572
+ const parsed = JSON.parse(row.value);
573
+ if (!Array.isArray(parsed) || !parsed.every((value) => typeof value === "string"))
574
+ throw new Error("Invalid persisted Pi identity fold guards");
575
+ return new Set(parsed);
576
+ }
577
+ function writePiIdentityFoldGuards(db, sessionId, guards) {
578
+ if (guards.size > PI_IDENTITY_FOLD_GUARD_LIMIT)
579
+ throw new Error("Pi identity fold guards exceed their limit");
580
+ db.prepare(`INSERT INTO schema_migrations_meta (key, value) VALUES (?, ?)
581
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value`).run(piIdentityFoldGuardKey(sessionId), JSON.stringify([...guards]));
582
+ }
583
+
562
584
  // ../plugin/src/features/magic-context/session-activity.ts
563
585
  var PREFIX = "retrospective_activity:";
564
586
  var INTERVAL_MS = 15000;
@@ -758,6 +780,9 @@ function deleteSessionScopedRows(db, sessionIds, harness, options = {}) {
758
780
  statement.run(...deletableSessionIds);
759
781
  }
760
782
  deleteSessionActivity(db, deletableSessionIds);
783
+ const deleteFoldGuards = cleanupStatement(db, "DELETE FROM schema_migrations_meta WHERE key = ? AND NOT EXISTS (SELECT 1 FROM session_meta WHERE session_id = ?)");
784
+ for (const id of deletableSessionIds)
785
+ deleteFoldGuards.run(piIdentityFoldGuardKey(id), id);
761
786
  if (!options.preserveTagRevisionTombstones) {
762
787
  const retireOwner = cleanupStatement(db, harness === undefined ? "DELETE FROM schema_migrations_meta WHERE key >= ? AND key < ?" : "DELETE FROM schema_migrations_meta WHERE key = ?");
763
788
  const survivingRows = harnessTables.map((definition) => `EXISTS (SELECT 1 FROM ${definition.table} WHERE session_id = ?${definition.extraPredicate ? ` AND ${definition.extraPredicate}` : ""})`).join(" OR ");
@@ -4661,4 +4686,4 @@ function renderItemByTag2(db, sessionId, number, textIndexDomain = "part", attac
4661
4686
  return selected ? renderPartFull(selected) ?? "" : `Tag ${number}'s original text part is no longer in stored history.`;
4662
4687
  }
4663
4688
 
4664
- export { 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, getUncoveredCompartmentEndsThrough, isPartialCompartmentEnd, readProjectDocsCanonical, providerResponseFailed, isSuccessfulProviderCompletion, requestPendingMaterialization, pendingMaterializationOrigin, hasPendingMaterializationOrigin, clearPendingMaterialization, recordSystemRefreshOwnership, recordSystemPromptForRequest, recordHeldHeadForRequest, bindSystemPromptResponse, acknowledgeSystemPromptDelivery, deferDeliveredSystemRefresh, clearSystemPromptDelivery, saveLkgSlotToDb, loadPersistedLkgSlot, drainStaleLkgSlots, createDbLkgPersistence, replayLkg, beginServedRequest, noteServedPassPermission, noteServedReplay, countServedRefusal, dropServedRecord, commitServedRequest, 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, withNativeReplayWriteBarrier, 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, renderMessageByOrdinal2, renderVerboseRange2, renderVerboseRangeForTool2, renderItemByTag2 };
4689
+ export { LkgRecoveryFenceError, clearLkgFenceProcessState, lkgFenceRequiresRebuild, lkgRecoveryFenceUnclean, ownsLkgDirtyFence, invalidateCleanLkgRecoveryFence, markLkgRecoveryDirty, rememberUnpublishedAutoSearchNoHint, getUnpublishedAutoSearchNoHint, forgetUnpublishedAutoSearchNoHint, registerAutoSearchWork, cancelAutoSearchWork, PI_IDENTITY_FOLD_GUARD_LIMIT, readPiIdentityFoldGuards, writePiIdentityFoldGuards, 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, getUncoveredCompartmentEndsThrough, isPartialCompartmentEnd, readProjectDocsCanonical, providerResponseFailed, isSuccessfulProviderCompletion, requestPendingMaterialization, pendingMaterializationOrigin, hasPendingMaterializationOrigin, clearPendingMaterialization, recordSystemRefreshOwnership, recordSystemPromptForRequest, recordHeldHeadForRequest, bindSystemPromptResponse, acknowledgeSystemPromptDelivery, deferDeliveredSystemRefresh, clearSystemPromptDelivery, saveLkgSlotToDb, loadPersistedLkgSlot, drainStaleLkgSlots, createDbLkgPersistence, replayLkg, beginServedRequest, noteServedPassPermission, noteServedReplay, countServedRefusal, dropServedRecord, commitServedRequest, 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, withNativeReplayWriteBarrier, 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, renderMessageByOrdinal2, renderVerboseRange2, renderVerboseRangeForTool2, renderItemByTag2 };
package/dist/index.js CHANGED
@@ -154,7 +154,7 @@ import {
154
154
  registerTodoStateLifecycle,
155
155
  syncCtxMemoryToolEnabled,
156
156
  registerMagicContextTools
157
- } from "./index-tn38he5d.js";
157
+ } from "./index-9x1jpjeb.js";
158
158
  import"./index-4knyh1kt.js";
159
159
  import {
160
160
  canonicalModelIdentity,
@@ -467,6 +467,9 @@ import {
467
467
  forgetUnpublishedAutoSearchNoHint,
468
468
  registerAutoSearchWork,
469
469
  cancelAutoSearchWork,
470
+ PI_IDENTITY_FOLD_GUARD_LIMIT,
471
+ readPiIdentityFoldGuards,
472
+ writePiIdentityFoldGuards,
470
473
  readSessionActivity,
471
474
  observeSessionActivity,
472
475
  backfillSessionActivity,
@@ -576,7 +579,7 @@ import {
576
579
  getSourceContents,
577
580
  recordSubagentInvocation,
578
581
  getLatestHistorianInvocationId
579
- } from "./index-k2z7r444.js";
582
+ } from "./index-ywmt8sdr.js";
580
583
  import {
581
584
  resolveOpenCodeDbPath,
582
585
  assertOpenCodeStoreGeneration,
@@ -842,7 +845,7 @@ import {
842
845
  } from "./index-nhpvvdhw.js";
843
846
  import"./index-yjgkjkjs.js";
844
847
  import"./index-8d2z6503.js";
845
- import"./index-6ahmfva8.js";
848
+ import"./index-b1q0h16h.js";
846
849
  import"./index-9kaj9ty1.js";
847
850
  import {
848
851
  __toESM
@@ -3595,7 +3598,7 @@ function startHostStallProfilerSwitch() {
3595
3598
  // package.json
3596
3599
  var package_default = {
3597
3600
  name: "@cortexkit/pi-magic-context",
3598
- version: "0.49.55",
3601
+ version: "0.49.56",
3599
3602
  type: "module",
3600
3603
  description: "Pi and OMP coding agent extension for Magic Context — cross-session memory and context management",
3601
3604
  main: "dist/index.js",
@@ -44194,16 +44197,15 @@ function piRenderedTagNumbers(messages) {
44194
44197
  }
44195
44198
  return numbers;
44196
44199
  }
44197
- function piCachedToolSurvivor(sessionId, callId, timestamp, rows) {
44198
- const cached = readPiServedCachedArray(sessionId);
44200
+ function piCachedToolSurvivor(sessionId, callId, timestamp, rows, view) {
44201
+ const cached = view === undefined ? createPiServedCachedView(sessionId) : view;
44199
44202
  if (!cached)
44200
44203
  return;
44201
- const { messages } = cached;
44202
- const owners = messages.filter((m) => m.role === "assistant" && contentParts(m).some((p) => p.type === "toolCall" && p.id === callId));
44204
+ const owners = cached.toolCallOwners().get(callId) ?? [];
44203
44205
  const owner = owners[0];
44204
44206
  if (!owner || owners.length !== 1 || owner.timestamp !== timestamp || contentParts(owner).filter((p) => p.type === "toolCall" && p.id === callId).length !== 1)
44205
44207
  return;
44206
- const rendered = piRenderedTagNumbers(messages);
44208
+ const rendered = cached.rendered();
44207
44209
  const present = rows.filter((row) => rendered.has(row.tagNumber));
44208
44210
  const winner = present[0];
44209
44211
  if (present.length !== 1 || !winner)
@@ -44211,11 +44213,62 @@ function piCachedToolSurvivor(sessionId, callId, timestamp, rows) {
44211
44213
  const { tagNumber: number, status } = winner;
44212
44214
  if (status !== "active" && status !== "dropped")
44213
44215
  return;
44214
- const results = messages.filter((m) => m.role === "toolResult" && m.toolCallId === callId);
44216
+ const results = cached.toolResults().get(callId) ?? [];
44215
44217
  if (!results.some((m) => contentParts(m).some((p) => p.type === "text" && (status === "dropped" ? p.text === `[dropped §${number}§]` : typeof p.text === "string" && p.text.startsWith(`§${number}§ `)))))
44216
44218
  return;
44217
44219
  return number;
44218
44220
  }
44221
+ function createPiServedCachedView(sessionId) {
44222
+ const cached = readPiServedCachedArray(sessionId);
44223
+ if (!cached)
44224
+ return null;
44225
+ const { messages } = cached;
44226
+ const memos = new Map;
44227
+ const memo = (key, build) => {
44228
+ if (!memos.has(key))
44229
+ memos.set(key, build());
44230
+ return memos.get(key);
44231
+ };
44232
+ return {
44233
+ messages,
44234
+ rendered: () => memo("rendered", () => piRenderedTagNumbers(messages)),
44235
+ toolCallOwners: () => memo("toolCallOwners", () => {
44236
+ const owners = new Map;
44237
+ for (const message of messages) {
44238
+ if (message.role !== "assistant")
44239
+ continue;
44240
+ const ids = new Set;
44241
+ for (const part of contentParts(message))
44242
+ if (part.type === "toolCall")
44243
+ ids.add(part.id);
44244
+ for (const id of ids) {
44245
+ if (typeof id !== "string")
44246
+ continue;
44247
+ const list = owners.get(id);
44248
+ if (list)
44249
+ list.push(message);
44250
+ else
44251
+ owners.set(id, [message]);
44252
+ }
44253
+ }
44254
+ return owners;
44255
+ }),
44256
+ toolResults: () => memo("toolResults", () => {
44257
+ const results = new Map;
44258
+ for (const message of messages) {
44259
+ if (message.role !== "toolResult" || typeof message.toolCallId !== "string")
44260
+ continue;
44261
+ const list = results.get(message.toolCallId);
44262
+ if (list)
44263
+ list.push(message);
44264
+ else
44265
+ results.set(message.toolCallId, [message]);
44266
+ }
44267
+ return results;
44268
+ }),
44269
+ memo
44270
+ };
44271
+ }
44219
44272
  function readPiServedCachedArray(sessionId) {
44220
44273
  const memory = getPiLastServedArray(sessionId);
44221
44274
  const slot = memory === undefined ? getSlot(sessionId) : undefined;
@@ -44277,14 +44330,14 @@ function textParts(message) {
44277
44330
  return p.type === "text" && typeof p.text === "string" ? [p.text] : [];
44278
44331
  }) : [];
44279
44332
  }
44280
- function piCachedMessageSurvivor(sessionId, fingerprint, ordinal, rows) {
44281
- const cached = readPiServedCachedArray(sessionId);
44333
+ function piCachedMessageSurvivor(sessionId, fingerprint, ordinal, rows, view) {
44334
+ const cached = view === undefined ? createPiServedCachedView(sessionId) : view;
44282
44335
  if (!cached)
44283
44336
  return;
44284
44337
  const header = fingerprintHeader(fingerprint);
44285
44338
  if (header === undefined)
44286
44339
  return;
44287
- const rendered = piRenderedTagNumbers(cached.messages);
44340
+ const rendered = cached.rendered();
44288
44341
  const present = rows.filter((row) => rendered.has(row.tagNumber));
44289
44342
  const winner = present[0];
44290
44343
  if (present.length !== 1 || !winner)
@@ -44292,7 +44345,18 @@ function piCachedMessageSurvivor(sessionId, fingerprint, ordinal, rows) {
44292
44345
  if (winner.status !== "active" && winner.status !== "dropped")
44293
44346
  return;
44294
44347
  const shows = (text) => winner.status === "dropped" ? text === `[dropped §${winner.tagNumber}§]` : text?.startsWith(`§${winner.tagNumber}§ `) === true;
44295
- const carriers = cached.messages.filter((message) => messageHeader(message) === header && shows(textParts(message)[ordinal]));
44348
+ const carriers = (cached.memo("messagesByHeader", () => {
44349
+ const byHeader = new Map;
44350
+ for (const message of cached.messages) {
44351
+ const key = messageHeader(message);
44352
+ const list = byHeader.get(key);
44353
+ if (list)
44354
+ list.push(message);
44355
+ else
44356
+ byHeader.set(key, [message]);
44357
+ }
44358
+ return byHeader;
44359
+ }).get(header) ?? []).filter((message) => shows(textParts(message)[ordinal]));
44296
44360
  return carriers.length === 1 ? winner.tagNumber : undefined;
44297
44361
  }
44298
44362
 
@@ -44852,10 +44916,15 @@ function readPiRequestToolsFingerprint(pi, wireSchema, messages, route = {}) {
44852
44916
  // src/pi-tag-identity-repair.ts
44853
44917
  var PI_TAG_IDENTITY_REPAIR_REASON = "tag_identity_repair";
44854
44918
  var unreadableLedgerLogged = new Set;
44919
+ function isPiPassEndingError(error) {
44920
+ return error instanceof PiContextDeadlineError || error instanceof PiContextSupersededError || error instanceof Error && error.name === "AbortError";
44921
+ }
44855
44922
  function readPiIdentityDecisions(db, sessionId) {
44856
44923
  try {
44857
44924
  return getPiContentDecisions(db, sessionId);
44858
44925
  } catch (error) {
44926
+ if (isPiPassEndingError(error))
44927
+ throw error;
44859
44928
  if (!unreadableLedgerLogged.has(sessionId)) {
44860
44929
  if (unreadableLedgerLogged.size > 1e4)
44861
44930
  unreadableLedgerLogged.clear();
@@ -44871,25 +44940,109 @@ function freezeIdentityDecision(db, sessionId, kind, value) {
44871
44940
  try {
44872
44941
  return freezePiContentDecision(db, sessionId, kind, value);
44873
44942
  } catch (error) {
44943
+ if (isPiPassEndingError(error))
44944
+ throw error;
44874
44945
  sessionLog2(sessionId, `tag identity decision ${kind} could not be written; serving duplicates unmerged: ${error instanceof Error ? error.message : String(error)}`);
44875
44946
  return false;
44876
44947
  }
44877
44948
  }
44949
+ var unreadableGuardsLogged = new Set;
44950
+ function readFoldGuards(db, sessionId) {
44951
+ try {
44952
+ return readPiIdentityFoldGuards(db, sessionId);
44953
+ } catch (error) {
44954
+ if (isPiPassEndingError(error))
44955
+ throw error;
44956
+ if (!unreadableGuardsLogged.has(sessionId)) {
44957
+ if (unreadableGuardsLogged.size > 1e4)
44958
+ unreadableGuardsLogged.clear();
44959
+ unreadableGuardsLogged.add(sessionId);
44960
+ sessionLog2(sessionId, `Pi identity fold guards unreadable: tag identity duplicates are served unmerged and the stored row is left untouched: ${error instanceof Error ? error.message : String(error)}`);
44961
+ }
44962
+ return null;
44963
+ }
44964
+ }
44965
+
44966
+ class PiIdentityRepairBatch {
44967
+ db;
44968
+ sessionId;
44969
+ ledger = null;
44970
+ guards = null;
44971
+ pending = false;
44972
+ refuseNewGuards = false;
44973
+ constructor(db, sessionId) {
44974
+ this.db = db;
44975
+ this.sessionId = sessionId;
44976
+ }
44977
+ load() {
44978
+ this.pending = false;
44979
+ this.ledger = readPiIdentityDecisions(this.db, this.sessionId);
44980
+ this.guards = readFoldGuards(this.db, this.sessionId);
44981
+ }
44982
+ decisions() {
44983
+ return this.ledger;
44984
+ }
44985
+ peek(key, legacyKeys = []) {
44986
+ const ledger = this.ledger;
44987
+ const guards = this.guards;
44988
+ if (ledger === null)
44989
+ return "unpersisted";
44990
+ const candidates = [key, ...legacyKeys];
44991
+ if (candidates.some((candidate) => ledger.has(encodePiContentDecision("tag-identity-repair-once", candidate))))
44992
+ return "recurring";
44993
+ if (guards === null)
44994
+ return "unpersisted";
44995
+ if (candidates.some((candidate) => guards.has(candidate)))
44996
+ return "recurring";
44997
+ if (this.refuseNewGuards || guards.size >= PI_IDENTITY_FOLD_GUARD_LIMIT)
44998
+ return "unpersisted";
44999
+ return "claimed";
45000
+ }
45001
+ claim(key, legacyKeys = []) {
45002
+ const claim = this.peek(key, legacyKeys);
45003
+ if (claim !== "claimed")
45004
+ return claim;
45005
+ this.guards?.add(key);
45006
+ this.pending = true;
45007
+ return "claimed";
45008
+ }
45009
+ flush() {
45010
+ if (!this.pending || !this.guards)
45011
+ return;
45012
+ writePiIdentityFoldGuards(this.db, this.sessionId, this.guards);
45013
+ this.pending = false;
45014
+ }
45015
+ recordRecurrence(key) {
45016
+ return recordPiIdentityRecurrence(this.db, this.sessionId, key, this.ledger);
45017
+ }
45018
+ }
44878
45019
  function claimPiIdentityRepair(db, sessionId, key, legacyKeys = []) {
44879
- const decisions = readPiIdentityDecisions(db, sessionId);
44880
- if (decisions === null)
45020
+ try {
45021
+ return db.transaction(() => {
45022
+ const batch = new PiIdentityRepairBatch(db, sessionId);
45023
+ batch.load();
45024
+ const claim = batch.claim(key, legacyKeys);
45025
+ if (claim === "claimed")
45026
+ batch.flush();
45027
+ return claim;
45028
+ }).immediate();
45029
+ } catch (error) {
45030
+ if (isPiPassEndingError(error))
45031
+ throw error;
45032
+ sessionLog2(sessionId, `tag identity fold guard could not be written; serving the duplicate unmerged: ${error instanceof Error ? error.message : String(error)}`);
44881
45033
  return "unpersisted";
44882
- if ([key, ...legacyKeys].some((candidate) => decisions.has(encodePiContentDecision("tag-identity-repair-once", candidate))))
44883
- return "recurring";
44884
- return freezeIdentityDecision(db, sessionId, "tag-identity-repair-once", key) ? "claimed" : "unpersisted";
45034
+ }
44885
45035
  }
44886
45036
  var unrecordedRecurrenceLogged = new Set;
44887
- function recordPiIdentityRecurrence(db, sessionId, key) {
45037
+ function recordPiIdentityRecurrence(db, sessionId, key, decisions) {
44888
45038
  const entry = encodePiContentDecision("tag-identity-recurring", key);
44889
- if (readPiIdentityDecisions(db, sessionId)?.has(entry))
45039
+ const known = decisions === undefined ? readPiIdentityDecisions(db, sessionId) : decisions;
45040
+ if (known?.has(entry))
44890
45041
  return false;
44891
- if (freezeIdentityDecision(db, sessionId, "tag-identity-recurring", key))
45042
+ if (freezeIdentityDecision(db, sessionId, "tag-identity-recurring", key)) {
45043
+ decisions?.add(entry);
44892
45044
  return true;
45045
+ }
44893
45046
  const logKey = `${sessionId}\x00${key}`;
44894
45047
  if (unrecordedRecurrenceLogged.has(logKey))
44895
45048
  return false;
@@ -48198,6 +48351,13 @@ function settlePiFallbackOccurrences(db, sessionId, ids) {
48198
48351
 
48199
48352
  class PiIdentityRebuildUnrecorded extends Error {
48200
48353
  }
48354
+ var PI_ADOPTION_RESERVE_MS = 1e4;
48355
+ var piAdoptionReserveMs = PI_ADOPTION_RESERVE_MS;
48356
+ var PI_ADOPTION_CHUNK_ROWS = 256;
48357
+ var PI_ADOPTION_CHUNK_MS = 250;
48358
+
48359
+ class PiIdentityGuardsUnwritten extends Error {
48360
+ }
48201
48361
  function readPiAdoptionRevision(db) {
48202
48362
  return {
48203
48363
  external: db.prepare("PRAGMA data_version").get(),
@@ -48305,8 +48465,17 @@ function adoptPiFallbackTags(db, sessionId, tagger, fingerprintById, options = {
48305
48465
  };
48306
48466
  const claimed = new Set;
48307
48467
  const repairing = new Set;
48468
+ const unguardedKeys = new Set;
48308
48469
  let servedNumbers;
48309
48470
  const readServedNumbers = () => servedNumbers ??= getPiServedTagNumbers(sessionId, undefined, db);
48471
+ let servedView;
48472
+ const readServedView = () => {
48473
+ if (servedView === undefined)
48474
+ servedView = createPiServedCachedView(sessionId);
48475
+ return servedView;
48476
+ };
48477
+ const batch = new PiIdentityRepairBatch(db, sessionId);
48478
+ let afterCommit = [];
48310
48479
  const newRebuilds = [];
48311
48480
  const recurrences = [];
48312
48481
  const plan = (rows, key, legacyKeys, served, cached) => {
@@ -48314,24 +48483,26 @@ function adoptPiFallbackTags(db, sessionId, tagger, fingerprintById, options = {
48314
48483
  if (!proven && options.deferUnprovenRebuild)
48315
48484
  return null;
48316
48485
  if (proven && options.allowUnprovenRebuild) {
48317
- const decisions = readPiIdentityDecisions(db, sessionId);
48318
- let unmerged = decisions === null || decisions.has(encodePiContentDecision("tag-identity-recurring", key));
48319
- if (!unmerged && !claimed.has(key)) {
48320
- unmerged = claimPiIdentityRepair(db, sessionId, key, legacyKeys) === "unpersisted";
48486
+ const decisions = batch.decisions();
48487
+ if (decisions?.has(encodePiContentDecision("tag-identity-recurring", key)))
48488
+ return null;
48489
+ if (decisions === null || unguardedKeys.has(key)) {
48490
+ unguardedKeys.add(key);
48491
+ return null;
48492
+ }
48493
+ if (!claimed.has(key)) {
48494
+ const claim = batch.claim(key, legacyKeys);
48321
48495
  claimed.add(key);
48496
+ if (claim === "unpersisted") {
48497
+ unguardedKeys.add(key);
48498
+ return null;
48499
+ }
48322
48500
  }
48323
- if (!unmerged)
48324
- return { rebuilding: undefined };
48325
- recurrences.push({
48326
- key,
48327
- numbers: rows.map((row) => row.tagNumber).sort((x, y) => x - y),
48328
- fresh: recordPiIdentityRecurrence(db, sessionId, key)
48329
- });
48330
- return null;
48501
+ return { rebuilding: undefined };
48331
48502
  }
48332
48503
  if (proven || !options.allowUnprovenRebuild) {
48333
48504
  if (!claimed.has(key)) {
48334
- claimPiIdentityRepair(db, sessionId, key, legacyKeys);
48505
+ batch.claim(key, legacyKeys);
48335
48506
  claimed.add(key);
48336
48507
  }
48337
48508
  return { rebuilding: undefined };
@@ -48339,16 +48510,22 @@ function adoptPiFallbackTags(db, sessionId, tagger, fingerprintById, options = {
48339
48510
  const newest = Math.max(...rows.map((row) => row.tagNumber));
48340
48511
  if (repairing.has(key))
48341
48512
  return { rebuilding: newest };
48342
- const claim = claimed.has(key) ? "recurring" : claimPiIdentityRepair(db, sessionId, key, legacyKeys);
48513
+ if (unguardedKeys.has(key))
48514
+ return null;
48515
+ const claim = claimed.has(key) ? "recurring" : batch.claim(key, legacyKeys);
48343
48516
  claimed.add(key);
48344
48517
  if (claim === "claimed") {
48345
48518
  repairing.add(key);
48346
48519
  return { rebuilding: newest };
48347
48520
  }
48521
+ if (claim === "unpersisted") {
48522
+ unguardedKeys.add(key);
48523
+ return null;
48524
+ }
48348
48525
  recurrences.push({
48349
48526
  key,
48350
48527
  numbers: rows.map((row) => row.tagNumber).sort((x, y) => x - y),
48351
- fresh: recordPiIdentityRecurrence(db, sessionId, key)
48528
+ fresh: batch.recordRecurrence(key)
48352
48529
  });
48353
48530
  return null;
48354
48531
  };
@@ -48372,6 +48549,8 @@ function adoptPiFallbackTags(db, sessionId, tagger, fingerprintById, options = {
48372
48549
  return result;
48373
48550
  }).immediate();
48374
48551
  } catch (error) {
48552
+ if (isPiPassEndingError(error))
48553
+ throw error;
48375
48554
  if (!(error instanceof PiIdentityRebuildUnrecorded) && !options.allowUnprovenRebuild)
48376
48555
  throw error;
48377
48556
  if (!(error instanceof PiIdentityRebuildUnrecorded))
@@ -48379,14 +48558,18 @@ function adoptPiFallbackTags(db, sessionId, tagger, fingerprintById, options = {
48379
48558
  recurrences.push({
48380
48559
  key: guardKey,
48381
48560
  numbers: [],
48382
- fresh: recordPiIdentityRecurrence(db, sessionId, guardKey)
48561
+ fresh: batch.recordRecurrence(guardKey)
48383
48562
  });
48384
48563
  return { action: "skipped" };
48385
48564
  }
48386
48565
  if (adoption.action === "folded") {
48387
- outcome.protectedTagNumbers.add(adoption.tagNumber);
48388
- if (repair)
48389
- newRebuilds.push(repair);
48566
+ const folded = adoption;
48567
+ const declared = repair;
48568
+ afterCommit.push(() => {
48569
+ outcome.protectedTagNumbers.add(folded.tagNumber);
48570
+ if (declared)
48571
+ newRebuilds.push(declared);
48572
+ });
48390
48573
  }
48391
48574
  return adoption;
48392
48575
  };
@@ -48402,43 +48585,130 @@ function adoptPiFallbackTags(db, sessionId, tagger, fingerprintById, options = {
48402
48585
  const targetsFor = (fingerprints) => [...fingerprints].flatMap((fingerprint) => (realIdsByFingerprint.get(fingerprint) ?? []).map((id) => [id, fingerprint]));
48403
48586
  const fallbackTargetsFor = (fingerprints) => [...fingerprints].flatMap((fingerprint) => (fallbackIdsByFingerprint.get(fingerprint) ?? []).map((id) => [id, fingerprint]));
48404
48587
  const discoveredTargets = targetsFor(discovered);
48405
- const adoptMessageCandidates = (targetId, fingerprint, candidates) => {
48406
- for (const c of candidates) {
48407
- const ordinalMatch = /:p(\d+)$/.exec(c.messageId);
48408
- if (!ordinalMatch)
48409
- continue;
48410
- const realContentId = `${targetId}:p${ordinalMatch[1]}`;
48411
- const served = readServedNumbers();
48412
- const canonical = getPiMessageTagCandidates2(db, sessionId, realContentId);
48413
- const collisionRows = [
48414
- ...getTagsByNumbers2(db, sessionId, [c.tagNumber]),
48415
- ...canonical
48416
- ];
48417
- const cachedSurvivor = canonical.length ? piCachedMessageSurvivor(sessionId, fingerprint, Number(ordinalMatch[1]), collisionRows) : undefined;
48418
- const repairKey = JSON.stringify(["message", realContentId]);
48419
- const guardKey = JSON.stringify([
48420
- "message",
48421
- fingerprint,
48422
- Number(ordinalMatch[1])
48423
- ]);
48424
- const decision = canonical.length ? plan(collisionRows, guardKey, [repairKey], served, cachedSurvivor) : { rebuilding: undefined };
48425
- if (decision === null)
48426
- continue;
48427
- const rebuilding = decision.rebuilding;
48428
- if (canonical.length && !collisionRows.some((row) => served.has(row.tagNumber)) && cachedSurvivor === undefined && rebuilding === undefined) {
48429
- throw new PiTagIdentityConflictError2("duplicate message identities have no proven served-byte survivor", "message");
48430
- }
48431
- const adoption = fold(() => adoptPiFallbackMessageTag2(db, sessionId, c.tagNumber, c.messageId, realContentId, served, cachedSurvivor, rebuilding), repairKey, guardKey, "message", rebuilding);
48432
- if (adoption.action !== "skipped") {
48433
- tagger.unbindTag(sessionId, c.messageId);
48434
- if (adoption.action === "folded") {
48435
- tagger.unbindTag(sessionId, realContentId);
48436
- }
48437
- tagger.bindTag(sessionId, realContentId, adoption.tagNumber);
48438
- }
48588
+ let messageItems = [];
48589
+ let toolRows = [];
48590
+ let prepared = false;
48591
+ let next = 0;
48592
+ let pausedDuplicates = 0;
48593
+ let chunkRows = 0;
48594
+ const passBudgetSpent = () => options.remainingMs !== undefined && options.remainingMs() <= piAdoptionReserveMs;
48595
+ const awaitsFold = (rows, key, legacyKeys, served, cached) => {
48596
+ const proven = cached !== undefined || rows.filter((row) => served.has(row.tagNumber)).length === 1;
48597
+ if (!proven && options.deferUnprovenRebuild)
48598
+ return false;
48599
+ if (unguardedKeys.has(key))
48600
+ return false;
48601
+ const decisions = batch.decisions();
48602
+ if (proven && options.allowUnprovenRebuild) {
48603
+ if (decisions === null || decisions.has(encodePiContentDecision("tag-identity-recurring", key)))
48604
+ return false;
48605
+ return claimed.has(key) || batch.peek(key, legacyKeys) !== "unpersisted";
48606
+ }
48607
+ if (proven || !options.allowUnprovenRebuild)
48608
+ return true;
48609
+ if (repairing.has(key))
48610
+ return true;
48611
+ return !claimed.has(key) && batch.peek(key, legacyKeys) === "claimed";
48612
+ };
48613
+ const adoptMessageCandidate = ({
48614
+ targetId,
48615
+ fingerprint,
48616
+ candidate: c
48617
+ }) => {
48618
+ const ordinalMatch = /:p(\d+)$/.exec(c.messageId);
48619
+ if (!ordinalMatch)
48620
+ return;
48621
+ const realContentId = `${targetId}:p${ordinalMatch[1]}`;
48622
+ const served = readServedNumbers();
48623
+ const canonical = getPiMessageTagCandidates2(db, sessionId, realContentId);
48624
+ if (canonical.length)
48625
+ chunkRows++;
48626
+ const collisionRows = [
48627
+ ...getTagsByNumbers2(db, sessionId, [c.tagNumber]),
48628
+ ...canonical
48629
+ ];
48630
+ const cachedSurvivor = canonical.length ? piCachedMessageSurvivor(sessionId, fingerprint, Number(ordinalMatch[1]), collisionRows, readServedView()) : undefined;
48631
+ const repairKey = JSON.stringify(["message", realContentId]);
48632
+ const guardKey = JSON.stringify([
48633
+ "message",
48634
+ fingerprint,
48635
+ Number(ordinalMatch[1])
48636
+ ]);
48637
+ if (canonical.length && passBudgetSpent()) {
48638
+ if (awaitsFold(collisionRows, guardKey, [repairKey], served, cachedSurvivor))
48639
+ pausedDuplicates++;
48640
+ return;
48641
+ }
48642
+ const decision = canonical.length ? plan(collisionRows, guardKey, [repairKey], served, cachedSurvivor) : { rebuilding: undefined };
48643
+ if (decision === null)
48644
+ return;
48645
+ const rebuilding = decision.rebuilding;
48646
+ if (canonical.length && !collisionRows.some((row) => served.has(row.tagNumber)) && cachedSurvivor === undefined && rebuilding === undefined) {
48647
+ throw new PiTagIdentityConflictError2("duplicate message identities have no proven served-byte survivor", "message");
48648
+ }
48649
+ const adoption = fold(() => adoptPiFallbackMessageTag2(db, sessionId, c.tagNumber, c.messageId, realContentId, served, cachedSurvivor, rebuilding), repairKey, guardKey, "message", rebuilding);
48650
+ if (adoption.action === "skipped")
48651
+ return;
48652
+ const { action, tagNumber } = adoption;
48653
+ afterCommit.push(() => {
48654
+ tagger.unbindTag(sessionId, c.messageId);
48655
+ if (action === "folded")
48656
+ tagger.unbindTag(sessionId, realContentId);
48657
+ tagger.bindTag(sessionId, realContentId, tagNumber);
48658
+ });
48659
+ };
48660
+ const adoptToolRow = (row) => {
48661
+ if (!ownerMap)
48662
+ return;
48663
+ const parsed = parsePiFallbackToolOwnerId(row.toolOwnerMessageId);
48664
+ if (parsed?.role !== "assistant")
48665
+ return;
48666
+ const owners = ownerMap.get(piToolOwnerMapKey(parsed.timestamp, row.callId));
48667
+ if (owners?.size !== 1)
48668
+ return;
48669
+ const [realOwnerId] = owners;
48670
+ if (!realOwnerId || realOwnerId === row.toolOwnerMessageId)
48671
+ return;
48672
+ const existingNumber = getToolTagNumberByOwner2(db, sessionId, row.callId, realOwnerId);
48673
+ if (existingNumber !== null)
48674
+ chunkRows++;
48675
+ const served = readServedNumbers();
48676
+ const cachedSurvivor = existingNumber === null ? undefined : piCachedToolSurvivor(sessionId, row.callId, parsed.timestamp, getTagsByNumbers2(db, sessionId, [row.tagNumber, existingNumber]), readServedView());
48677
+ const repairKey = JSON.stringify(["tool", parsed.timestamp, row.callId]);
48678
+ const legacyKeys = [JSON.stringify(["tool", realOwnerId, row.callId])];
48679
+ const rows = [
48680
+ { tagNumber: row.tagNumber },
48681
+ { tagNumber: existingNumber ?? row.tagNumber }
48682
+ ];
48683
+ if (existingNumber !== null && passBudgetSpent()) {
48684
+ if (awaitsFold(rows, repairKey, legacyKeys, served, cachedSurvivor))
48685
+ pausedDuplicates++;
48686
+ return;
48439
48687
  }
48688
+ const decision = existingNumber === null ? { rebuilding: undefined } : plan(rows, repairKey, legacyKeys, served, cachedSurvivor);
48689
+ if (decision === null)
48690
+ return;
48691
+ const rebuilding = decision.rebuilding;
48692
+ if (existingNumber !== null && !served.has(existingNumber) && !served.has(row.tagNumber) && cachedSurvivor === undefined && rebuilding === undefined) {
48693
+ throw new PiTagIdentityConflictError2("duplicate tool identities have no proven served-byte survivor");
48694
+ }
48695
+ const adoption = fold(() => adoptPiFallbackToolOwnerTag2(db, sessionId, row.tagNumber, row.callId, row.toolOwnerMessageId, realOwnerId, served.size === 0 && cachedSurvivor !== undefined ? new Set([cachedSurvivor]) : served, cachedSurvivor, rebuilding), repairKey, repairKey, "tool", rebuilding);
48696
+ if (adoption.action === "skipped")
48697
+ return;
48698
+ const { action, tagNumber } = adoption;
48699
+ const accounting = getPersistedToolTagAccounting2(db, sessionId, tagNumber);
48700
+ afterCommit.push(() => {
48701
+ tagger.unbindToolTag(sessionId, row.toolOwnerMessageId, row.callId);
48702
+ if (action === "folded")
48703
+ tagger.unbindToolTag(sessionId, realOwnerId, row.callId);
48704
+ tagger.bindToolTag(sessionId, row.callId, realOwnerId, tagNumber);
48705
+ if (accounting)
48706
+ tagger.setToolTagAccounting(sessionId, tagNumber, accounting);
48707
+ });
48440
48708
  };
48441
- runImmediateTransaction(db, () => {
48709
+ const prepare = () => {
48710
+ messageItems = [];
48711
+ toolRows = [];
48442
48712
  const admitted = revision();
48443
48713
  const unchangedSinceDiscovery = beforeDiscovery.external.data_version === admitted.external.data_version && beforeDiscovery.local.changes === admitted.local.changes;
48444
48714
  const preflight = options.preflightRevision;
@@ -48494,7 +48764,13 @@ function adoptPiFallbackTags(db, sessionId, tagger, fingerprintById, options = {
48494
48764
  }
48495
48765
  if (base === undefined)
48496
48766
  continue;
48497
- adoptMessageCandidates(realMessageId, fingerprint, candidates.filter((c) => piFallbackBaseId(c.messageId) === base));
48767
+ for (const candidate of candidates)
48768
+ if (piFallbackBaseId(candidate.messageId) === base)
48769
+ messageItems.push({
48770
+ targetId: realMessageId,
48771
+ fingerprint,
48772
+ candidate
48773
+ });
48498
48774
  }
48499
48775
  for (const [fallbackId, fingerprint] of fallbackTargetsFor(adoptable)) {
48500
48776
  if (realIdsByFingerprint.has(fingerprint))
@@ -48504,54 +48780,90 @@ function adoptPiFallbackTags(db, sessionId, tagger, fingerprintById, options = {
48504
48780
  const legacy = findAdoptableFallbackTags2(db, sessionId, fingerprint).filter((c) => isPiIndexFallbackId(piFallbackBaseId(c.messageId)));
48505
48781
  legacy.sort((left, right) => left.tagNumber - right.tagNumber);
48506
48782
  for (const base of new Set(legacy.map((c) => piFallbackBaseId(c.messageId))))
48507
- adoptMessageCandidates(fallbackId, fingerprint, legacy.filter((c) => piFallbackBaseId(c.messageId) === base));
48783
+ for (const candidate of legacy)
48784
+ if (piFallbackBaseId(candidate.messageId) === base)
48785
+ messageItems.push({
48786
+ targetId: fallbackId,
48787
+ fingerprint,
48788
+ candidate
48789
+ });
48508
48790
  }
48509
48791
  }
48510
- if (ownerMap && (unchangedSinceDiscovery ? discoveredToolOwnerFallback : hasPiFallbackToolOwnerTags2(db, sessionId))) {
48511
- for (const row of findPiFallbackToolOwnerTags2(db, sessionId)) {
48512
- const parsed = parsePiFallbackToolOwnerId(row.toolOwnerMessageId);
48513
- if (parsed?.role !== "assistant")
48514
- continue;
48515
- const owners = ownerMap.get(piToolOwnerMapKey(parsed.timestamp, row.callId));
48516
- if (owners?.size !== 1)
48517
- continue;
48518
- const [realOwnerId] = owners;
48519
- if (!realOwnerId || realOwnerId === row.toolOwnerMessageId)
48520
- continue;
48521
- const existingNumber = getToolTagNumberByOwner2(db, sessionId, row.callId, realOwnerId);
48522
- const served = readServedNumbers();
48523
- const cachedSurvivor = existingNumber === null ? undefined : piCachedToolSurvivor(sessionId, row.callId, parsed.timestamp, getTagsByNumbers2(db, sessionId, [
48524
- row.tagNumber,
48525
- existingNumber
48526
- ]));
48527
- const repairKey = JSON.stringify([
48528
- "tool",
48529
- parsed.timestamp,
48530
- row.callId
48531
- ]);
48532
- const legacyKeys = [JSON.stringify(["tool", realOwnerId, row.callId])];
48533
- const decision = existingNumber === null ? { rebuilding: undefined } : plan([{ tagNumber: row.tagNumber }, { tagNumber: existingNumber }], repairKey, legacyKeys, served, cachedSurvivor);
48534
- if (decision === null)
48535
- continue;
48536
- const rebuilding = decision.rebuilding;
48537
- if (existingNumber !== null && !served.has(existingNumber) && !served.has(row.tagNumber) && cachedSurvivor === undefined && rebuilding === undefined) {
48538
- throw new PiTagIdentityConflictError2("duplicate tool identities have no proven served-byte survivor");
48539
- }
48540
- const adoption = fold(() => adoptPiFallbackToolOwnerTag2(db, sessionId, row.tagNumber, row.callId, row.toolOwnerMessageId, realOwnerId, served.size === 0 && cachedSurvivor !== undefined ? new Set([cachedSurvivor]) : served, cachedSurvivor, rebuilding), repairKey, repairKey, "tool", rebuilding);
48541
- if (adoption.action !== "skipped") {
48542
- tagger.unbindToolTag(sessionId, row.toolOwnerMessageId, row.callId);
48543
- if (adoption.action === "folded") {
48544
- tagger.unbindToolTag(sessionId, realOwnerId, row.callId);
48545
- }
48546
- tagger.bindToolTag(sessionId, row.callId, realOwnerId, adoption.tagNumber);
48547
- const accounting = getPersistedToolTagAccounting2(db, sessionId, adoption.tagNumber);
48548
- if (accounting) {
48549
- tagger.setToolTagAccounting(sessionId, adoption.tagNumber, accounting);
48792
+ if (ownerMap && (unchangedSinceDiscovery ? discoveredToolOwnerFallback : hasPiFallbackToolOwnerTags2(db, sessionId)))
48793
+ toolRows = findPiFallbackToolOwnerTags2(db, sessionId);
48794
+ };
48795
+ const runSlice = () => {
48796
+ if (!prepared) {
48797
+ prepare();
48798
+ prepared = true;
48799
+ }
48800
+ const started = performance.now();
48801
+ chunkRows = 0;
48802
+ while (next < messageItems.length + toolRows.length && chunkRows < PI_ADOPTION_CHUNK_ROWS && performance.now() - started < PI_ADOPTION_CHUNK_MS) {
48803
+ const index = next++;
48804
+ chunkRows++;
48805
+ const message = messageItems[index];
48806
+ if (message)
48807
+ adoptMessageCandidate(message);
48808
+ else {
48809
+ const row = toolRows[index - messageItems.length];
48810
+ if (row)
48811
+ adoptToolRow(row);
48812
+ }
48813
+ }
48814
+ };
48815
+ const runChunk = () => {
48816
+ const start = {
48817
+ next,
48818
+ prepared,
48819
+ pausedDuplicates,
48820
+ recurrences: recurrences.length
48821
+ };
48822
+ for (let attempt = 0;; attempt++) {
48823
+ afterCommit = [];
48824
+ try {
48825
+ runImmediateTransaction(db, () => {
48826
+ batch.load();
48827
+ runSlice();
48828
+ try {
48829
+ batch.flush();
48830
+ } catch (error) {
48831
+ if (isPiPassEndingError(error))
48832
+ throw error;
48833
+ throw new PiIdentityGuardsUnwritten(error instanceof Error ? error.message : String(error));
48550
48834
  }
48551
- }
48835
+ });
48836
+ } catch (error) {
48837
+ afterCommit = [];
48838
+ if (!(error instanceof PiIdentityGuardsUnwritten))
48839
+ throw error;
48840
+ next = start.next;
48841
+ prepared = start.prepared;
48842
+ pausedDuplicates = start.pausedDuplicates;
48843
+ recurrences.length = start.recurrences;
48844
+ if (attempt > 0)
48845
+ return false;
48846
+ sessionLog2(sessionId, `tag identity fold guards could not be written; duplicates that need one are served unmerged this pass: ${error.message}`);
48847
+ batch.refuseNewGuards = true;
48848
+ claimed.clear();
48849
+ repairing.clear();
48850
+ continue;
48552
48851
  }
48852
+ const committed = afterCommit;
48853
+ afterCommit = [];
48854
+ for (const effect of committed)
48855
+ effect();
48856
+ return true;
48553
48857
  }
48554
- });
48858
+ };
48859
+ do {
48860
+ if (!runChunk())
48861
+ break;
48862
+ } while (next < messageItems.length + toolRows.length);
48863
+ if (pausedDuplicates > 0)
48864
+ sessionLog2(sessionId, `tag identity adoption reached the pass budget: session=${sessionId} ${pausedDuplicates} duplicated identities stay unmerged until the next pass`);
48865
+ if (unguardedKeys.size > 0)
48866
+ sessionLog2(sessionId, `tag identity repairs without a stored guard: ${unguardedKeys.size} duplicated identities served unmerged this pass (guard store full or unreadable)`);
48555
48867
  for (const recurrence of recurrences) {
48556
48868
  if (!recurrence.fresh)
48557
48869
  continue;
@@ -49246,6 +49558,7 @@ function registerPiContextHandler(pi, baseOptions) {
49246
49558
  recoveryPrefix: recovery.prefix,
49247
49559
  recoveryRebuildReason: recovery.rebuildReason,
49248
49560
  assertCurrentPass,
49561
+ remainingPassMs: budget.remainingOutcome,
49249
49562
  db: options.db,
49250
49563
  tagger,
49251
49564
  sessionId,
@@ -51346,6 +51659,7 @@ async function runPipeline(args) {
51346
51659
  realIdPositions: fallbackIndex.positions,
51347
51660
  hasFallbackMessageTags,
51348
51661
  preflightRevision,
51662
+ remainingMs: args.remainingPassMs,
51349
51663
  rebuildFingerprints: args.reusableMessageIds?.size ? () => {
51350
51664
  args.assertCurrentPass?.();
51351
51665
  const full = fallbackIndex.fingerprints(readPiFallbackFingerprintHeaders(args.db, args.sessionId));
@@ -19,7 +19,7 @@ serveWorkerJobs(async (input, port) => {
19
19
  await main();
20
20
  async function main() {
21
21
  if (input.v2ArchiveReader) {
22
- const { serveV2ArchiveReads } = await import("./v2-archive-reader-hg4c36em.js");
22
+ const { serveV2ArchiveReads } = await import("./v2-archive-reader-r96gp6nc.js");
23
23
  await serveV2ArchiveReads(port, openConnections);
24
24
  return;
25
25
  }
@@ -51,7 +51,7 @@ serveWorkerJobs(async (input, port) => {
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-31054zxj.js");
54
+ const { renderSearchArchive } = await import("./search-archive-vpxem4pj.js");
55
55
  const { readRawSessionMessageIdOrdinalsForRangeFromDb } = await import("./read-session-raw-75dcxtdy.js");
56
56
  const archive = input.searchArchive;
57
57
  let raw;
@@ -3,7 +3,7 @@ import {
3
3
  renderVerboseRange2,
4
4
  renderVerboseRangeForTool2,
5
5
  renderItemByTag2
6
- } from "./index-k2z7r444.js";
6
+ } from "./index-ywmt8sdr.js";
7
7
  import"./index-awpx91y5.js";
8
8
  import"./index-2pptpxq8.js";
9
9
  import"./index-hgd00nas.js";
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  renderSearchArchive2
3
3
  } from "./index-9kaj9ty1.js";
4
- import"./index-6ahmfva8.js";
4
+ import"./index-b1q0h16h.js";
5
5
  import"./index-8d2z6503.js";
6
6
  import"./index-rekymyxd.js";
7
7
  import"./index-5n3e2gq5.js";
@@ -34,7 +34,7 @@ import {
34
34
  resolvePiHarnessKind,
35
35
  reportSubagentStartupError,
36
36
  registerMagicContextTools
37
- } from "./index-tn38he5d.js";
37
+ } from "./index-9x1jpjeb.js";
38
38
  import"./index-vcegxfwg.js";
39
39
  import"./index-qm139qq2.js";
40
40
  import"./index-ndg15t3x.js";
@@ -45,14 +45,14 @@ import"./index-9p40dgkm.js";
45
45
  import"./index-zxm7ckvc.js";
46
46
  import"./index-yhzhdp3m.js";
47
47
  import"./index-jnh7a6a3.js";
48
- import"./index-k2z7r444.js";
48
+ import"./index-ywmt8sdr.js";
49
49
  import"./index-2pptpxq8.js";
50
50
  import"./index-5n3e2gq5.js";
51
51
  import"./index-6x556c2q.js";
52
52
  import"./index-nvh6d3bz.js";
53
53
  import"./index-awpx91y5.js";
54
54
  import"./index-8d2z6503.js";
55
- import"./index-6ahmfva8.js";
55
+ import"./index-b1q0h16h.js";
56
56
  import"./index-9kaj9ty1.js";
57
57
  import"./index-29nw7n1r.js";
58
58
  import"./index-c3mms4dp.js";
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  readV2ArchiveOffThread2,
3
3
  serveV2ArchiveReads2
4
- } from "./index-6ahmfva8.js";
4
+ } from "./index-b1q0h16h.js";
5
5
  import"./index-8sqebjzk.js";
6
6
  import"./index-2qtx0q6h.js";
7
7
  import"./index-x2n261wp.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/pi-magic-context",
3
- "version": "0.49.55",
3
+ "version": "0.49.56",
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",