@@ -1400,50 +1400,54 @@ export function registerPiContextHandler(
14001400 const tMeta = performance . now ( ) ;
14011401 const sessionMetaForUsage = getOrCreateSessionMeta ( options . db , sessionId ) ;
14021402 logTransformTiming ( sessionId , "getOrCreateSessionMeta" , tMeta ) ;
1403- if (
1404- ( isFirstContextPassForSession || modelChanged ) &&
1405- ( sessionMetaForUsage . lastContextPercentage > 0 ||
1406- sessionMetaForUsage . lastInputTokens > 0 )
1407- ) {
1408- const reason = isFirstContextPassForSession
1409- ? "first pass"
1410- : `model switch ${ previousModelKey } -> ${ currentModelKey } ` ;
1403+ const usageReset = {
1404+ lastContextPercentage : 0 ,
1405+ lastInputTokens : 0 ,
1406+ observedSafeInputTokens : 0 ,
1407+ cacheAlertSent : false ,
1408+ } ;
1409+ const hasStaleUsage =
1410+ sessionMetaForUsage . lastContextPercentage > 0 ||
1411+ sessionMetaForUsage . lastInputTokens > 0 ;
1412+ if ( modelChanged ) {
1413+ // Model change: clear UNCONDITIONALLY (not gated on stale usage).
1414+ // The reasoning watermark, historian failure/recovery state, and
1415+ // detected context limit were specific to the previous model and
1416+ // must be discarded so the new model gets a clean slate — even when
1417+ // the prior usage counters happen to read zero (e.g. a switch right
1418+ // after a reset). Mirrors OpenCode transform.ts model-change reset,
1419+ // which runs with no usage>0 guard.
14111420 sessionLog (
14121421 sessionId ,
1413- `transform: ${ reason } reset — percentage=${ sessionMetaForUsage . lastContextPercentage . toFixed ( 1 ) } % tokens=${ sessionMetaForUsage . lastInputTokens } — clearing stale usage state` ,
1422+ `transform: model switch ${ previousModelKey } -> ${ currentModelKey } reset — percentage=${ sessionMetaForUsage . lastContextPercentage . toFixed ( 1 ) } % tokens=${ sessionMetaForUsage . lastInputTokens } — clearing stale model-specific state` ,
14141423 ) ;
1415- // Usage-pressure fields are cleared on BOTH first pass and model
1416- // change — stale percentage/tokens from a prior model or pre-restart
1417- // state must not drive threshold checks before message_end refreshes.
1418- const usageReset = {
1419- lastContextPercentage : 0 ,
1420- lastInputTokens : 0 ,
1421- observedSafeInputTokens : 0 ,
1422- cacheAlertSent : false ,
1423- } ;
1424- if ( modelChanged ) {
1425- // Model change ONLY: the reasoning watermark and historian
1426- // failure/recovery state were specific to the previous model and
1427- // must be discarded so the new model gets a clean slate.
1428- updateSessionMeta ( options . db , sessionId , {
1429- ...usageReset ,
1430- clearedReasoningThroughTag : 0 ,
1431- } ) ;
1432- clearHistorianFailureState ( options . db , sessionId ) ;
1433- clearPersistedReasoningWatermark ( options . db , sessionId ) ;
1434- clearDetectedContextLimit ( options . db , sessionId ) ;
1435- clearEmergencyRecovery ( options . db , sessionId ) ;
1436- sessionMetaForUsage . clearedReasoningThroughTag = 0 ;
1437- } else {
1438- // First pass after restart (same model): clear ONLY usage fields.
1439- // historian-failure state and the reasoning watermark MUST be
1440- // preserved — restart recovery uses the failure backoff, and
1441- // clearing the reasoning watermark would resurface previously
1442- // cleared reasoning (a cache bust + larger prompt). Mirrors
1443- // OpenCode transform.ts first-pass reset ("Do NOT clear historian
1444- // failure state here — restart recovery uses it").
1445- updateSessionMeta ( options . db , sessionId , usageReset ) ;
1446- }
1424+ updateSessionMeta ( options . db , sessionId , {
1425+ ...usageReset ,
1426+ clearedReasoningThroughTag : 0 ,
1427+ } ) ;
1428+ clearHistorianFailureState ( options . db , sessionId ) ;
1429+ clearPersistedReasoningWatermark ( options . db , sessionId ) ;
1430+ clearDetectedContextLimit ( options . db , sessionId ) ;
1431+ clearEmergencyRecovery ( options . db , sessionId ) ;
1432+ sessionMetaForUsage . clearedReasoningThroughTag = 0 ;
1433+ sessionMetaForUsage . lastContextPercentage = 0 ;
1434+ sessionMetaForUsage . lastInputTokens = 0 ;
1435+ sessionMetaForUsage . observedSafeInputTokens = 0 ;
1436+ sessionMetaForUsage . cacheAlertSent = false ;
1437+ } else if ( isFirstContextPassForSession && hasStaleUsage ) {
1438+ // First pass after restart (same model): clear ONLY usage fields,
1439+ // and only when there is stale usage to clear. historian-failure
1440+ // state and the reasoning watermark MUST be preserved — restart
1441+ // recovery uses the failure backoff, and clearing the reasoning
1442+ // watermark would resurface previously cleared reasoning (a cache
1443+ // bust + larger prompt). Mirrors OpenCode transform.ts first-pass
1444+ // reset ("Do NOT clear historian failure state here — restart
1445+ // recovery uses it").
1446+ sessionLog (
1447+ sessionId ,
1448+ `transform: first pass reset — percentage=${ sessionMetaForUsage . lastContextPercentage . toFixed ( 1 ) } % tokens=${ sessionMetaForUsage . lastInputTokens } — clearing stale usage state` ,
1449+ ) ;
1450+ updateSessionMeta ( options . db , sessionId , usageReset ) ;
14471451 sessionMetaForUsage . lastContextPercentage = 0 ;
14481452 sessionMetaForUsage . lastInputTokens = 0 ;
14491453 sessionMetaForUsage . observedSafeInputTokens = 0 ;
@@ -1600,14 +1604,14 @@ export function registerPiContextHandler(
16001604 if ( stableIdSchemeCutover ) {
16011605 schedulerDecision = "execute" ;
16021606 signalPiPendingMaterialization ( sessionId ) ;
1603- try {
1604- setStrippedPlaceholderIds ( options . db , sessionId , new Set ( ) ) ;
1605- } catch ( err ) {
1606- sessionLog (
1607- sessionId ,
1608- `stable-id cutover: failed to clear stripped_placeholder_ids (continuing): ${ err instanceof Error ? err . message : String ( err ) } ` ,
1609- ) ;
1610- }
1607+ // Re-keying of stripped_placeholder_ids from pi-msg-* to real ids is
1608+ // done by the strip's own prune this pass (forceDiscovery + carried
1609+ // map → finalIds = idsToStrip ∩ presentIds, and stale pi-msg-* ids
1610+ // aren't in the real-id presentIds, so they're dropped atomically
1611+ // within the strip's persist). We deliberately do NOT pre-clear the
1612+ // set here: an early clear before the pass succeeds would lose the
1613+ // placeholder set on a mid-pass failure, and forceDiscovery keeps
1614+ // retrying every pass until the scheme stamps anyway.
16111615 sessionLog (
16121616 sessionId ,
16131617 `stable-id scheme cutover: stored=${ storedStableIdScheme } < current=${ PI_STABLE_ID_SCHEME } — forcing execute+materialize this pass` ,
@@ -1886,6 +1890,7 @@ export function registerPiContextHandler(
18861890 entryIdByRef : result . postCommitEntryIdByRef ,
18871891 hasRecentReduceCall : hasRecentPiCtxReduceExecution ( sessionId ) ,
18881892 isCacheBustingPass : cacheBustingPass ,
1893+ syntheticLeadingCount : result . syntheticLeadingCount ,
18891894 } ) ;
18901895 } catch ( err ) {
18911896 sessionLog (
@@ -1925,6 +1930,7 @@ export function registerPiContextHandler(
19251930 // Same signal OpenCode uses to gate sticky-anchor GC
19261931 // (isCacheBustingPass = history-refresh OR work executed).
19271932 isCacheBusting : isCacheBusting || result . executedWorkThisPass ,
1933+ syntheticLeadingCount : result . syntheticLeadingCount ,
19281934 } ) ;
19291935 } catch ( err ) {
19301936 sessionLog (
@@ -2702,6 +2708,13 @@ interface RunPipelineResult {
27022708 executedWorkThisPass : boolean ;
27032709 /** Whether <session-history> was written into message[0]. */
27042710 historyInjected : boolean ;
2711+ /**
2712+ * Count of synthetic id-less messages injection prepended (the m[0]/m[1]
2713+ * pair). Anchor-GC excludes these from its "all messages resolved"
2714+ * denominator — they never resolve to a real entry id, so without this
2715+ * exclusion `allResolved` is permanently false and pruning never runs.
2716+ */
2717+ syntheticLeadingCount : number ;
27052718 /** Aggregate counts for log parity with OpenCode. */
27062719 heuristicsResult : PiHeuristicCleanupResult | null ;
27072720 injectionResult : PiInjectionResult | null ;
@@ -3318,7 +3331,15 @@ async function runPipeline(args: RunPipelineArgs): Promise<RunPipelineResult> {
33183331 db : args . db ,
33193332 sessionId : args . sessionId ,
33203333 messages : args . messages ,
3321- isCacheBusting : args . isCacheBusting ,
3334+ // Discovery/prune must fire on ANY byte-mutating pass, not just a
3335+ // history-refresh. `args.isCacheBusting` alone is history-refresh-only;
3336+ // OpenCode gates discovery on `shouldApplyPendingOps || shouldRunHeuristics`.
3337+ // `executedWorkThisPass` is Pi's equivalent superset (set by pending-ops
3338+ // application, heuristic drops, AND reasoning clearing) — every one of
3339+ // those mutates the wire, so it IS a cache-busting pass and discovering /
3340+ // pruning there is byte-safe. Without this, a placeholder created on a
3341+ // drop-only execute pass (no history refresh) would never be discovered.
3342+ isCacheBusting : args . isCacheBusting || executedWorkThisPass ,
33223343 stableIdByRef : postCommitStableIdByRef ,
33233344 // F4 cutover: when the stable-id scheme just changed, force rediscovery so
33243345 // previously-stripped placeholders get re-keyed under the new scheme this
@@ -3446,6 +3467,7 @@ async function runPipeline(args: RunPipelineArgs): Promise<RunPipelineResult> {
34463467 heuristicsExecuted,
34473468 executedWorkThisPass,
34483469 historyInjected : injectionResult ?. injected ?? false ,
3470+ syntheticLeadingCount : injectionResult ?. syntheticLeadingCount ?? 0 ,
34493471 heuristicsResult,
34503472 injectionResult,
34513473 targetCount : targets . size ,
@@ -3535,6 +3557,13 @@ function applyStickyTurnReminder(args: {
35353557 entryIdByRef ?: ReadonlyMap < object , string > | null ;
35363558 hasRecentReduceCall : boolean ;
35373559 isCacheBustingPass : boolean ;
3560+ /**
3561+ * Count of synthetic id-less messages injection prepended (m[0]/m[1] pair).
3562+ * Excluded from the `allResolved` denominator — they never resolve to a real
3563+ * entry id, so without this every injected pass would have allResolved=false
3564+ * and pruning would never run.
3565+ */
3566+ syntheticLeadingCount ?: number ;
35383567} ) : PiAgentMessage [ ] {
35393568 const reminder = getPersistedStickyTurnReminder ( args . db , args . sessionId ) ;
35403569 if ( ! reminder ) return args . messages ;
@@ -3554,7 +3583,15 @@ function applyStickyTurnReminder(args: {
35543583 // (post-splice) messages — used to decide whether the anchored reminder
35553584 // message is still visible, instead of the stale positional `entryIds`.
35563585 const visibleResolvedIds = new Set < string > ( messageIdByIndex . values ( ) ) ;
3557- const allResolved = messageIdByIndex . size === args . messages . length ;
3586+ // "All REAL messages resolved" — exclude injection's synthetic id-less
3587+ // m[0]/m[1] prepends from the denominator. Those never resolve, so comparing
3588+ // against the raw length would leave allResolved permanently false on every
3589+ // injected pass and disable the guard's prune entirely.
3590+ const realMessageCount = Math . max (
3591+ 0 ,
3592+ args . messages . length - ( args . syntheticLeadingCount ?? 0 ) ,
3593+ ) ;
3594+ const allResolved = messageIdByIndex . size === realMessageCount ;
35583595 if ( reminder . messageId ) {
35593596 const reinjected = appendReminderToUserMessageByIdPi (
35603597 args . messages ,
@@ -3631,6 +3668,11 @@ function applyNoteNudges(args: {
36313668 * bytes could shift and bust the prompt cache.
36323669 */
36333670 isCacheBusting : boolean ;
3671+ /**
3672+ * Count of synthetic id-less messages injection prepended (m[0]/m[1] pair).
3673+ * Excluded from the anchor-GC `allResolved` denominator (see below).
3674+ */
3675+ syntheticLeadingCount ?: number ;
36343676} ) : PiAgentMessage [ ] {
36353677 const { sessionId, db, messages, projectIdentity, entryIds, entryIdByRef } =
36363678 args ;
@@ -3736,7 +3778,15 @@ function applyNoteNudges(args: {
37363778 // and wrongly prune its anchor).
37373779 if ( args . isCacheBusting ) {
37383780 const visibleIds = new Set < string > ( messageIdByIndex . values ( ) ) ;
3739- const allResolved = messageIdByIndex . size === messages . length ;
3781+ // "All REAL messages resolved" — exclude injection's synthetic id-less
3782+ // m[0]/m[1] prepends from the denominator (they never resolve to a real
3783+ // entry id). Without this, allResolved is permanently false on every
3784+ // injected pass and the prune never runs → unbounded anchor growth.
3785+ const realMessageCount = Math . max (
3786+ 0 ,
3787+ messages . length - ( args . syntheticLeadingCount ?? 0 ) ,
3788+ ) ;
3789+ const allResolved = messageIdByIndex . size === realMessageCount ;
37403790 if ( allResolved && visibleIds . size > 0 ) {
37413791 pruneNoteNudgeAnchors ( db , sessionId , visibleIds ) ;
37423792 pruneAutoSearchHintDecisions ( db , sessionId , visibleIds ) ;
0 commit comments