Skip to content

Commit 934e5c3

Browse files
committed
fix(pi): round-5 control-flow + identity fixes (HIGH #3/#4/C5 + MEDs + LOWs)
- HIGH #3: model-change clears (reasoning watermark, historian-failure, detected-limit, emergency-recovery) now run UNCONDITIONALLY on model change, not gated on usage>0 — a zero-usage switch previously skipped them. First-pass usage clears stay gated. Mirrors OpenCode transform.ts. - HIGH C#5: placeholder strip no longer neutralizes user-role messages (they anchor turn boundaries). Pi's raw array carries tool results as role 'toolResult'; synthetic user folds live only in the transcript view, so only genuine prompts are user-role here. Parity with OpenCode. - HIGH #4: recomp stages the native compaction marker + refresh signals synchronously right after publish, before the async status send, closing the publish->stage yield window (impact bounded: wire trims every pass). - MED: placeholder discovery/prune gate broadened from history-refresh-only to executedWorkThisPass (Pi equiv of OpenCode shouldApplyPendingOps|| shouldRunHeuristics) so drop-only execute passes discover placeholders. - MED: removed the cutover placeholder pre-clear (lossy on mid-pass failure); the strip's own prune re-keys pi-msg-* -> real ids atomically. - MED: anchor-GC allResolved denominator excludes the synthetic m0/m1 prepends (id-less), which otherwise kept it permanently false -> no prune. - MED: session_before_switch keeps the durable DB m0 cache (reversible switch); only in-memory maps are cleared. Avoids a re-materialize bust on switch-back. session_before_compact still clears it. - LOW: large historian prompts (>96KB) delivered via piped stdin instead of argv to avoid Linux E2BIG (MAX_ARG_STRLEN); positional omitted to avoid Pi's stdin+argv concatenation duplicating the prompt. - LOW: removed dead stateFilePath + cleanupHistorianStateFile import. - LOW: corrected SYNTH_USER_ID_PREFIX comment (defer vs resolve by consumer).
1 parent e864834 commit 934e5c3

8 files changed

Lines changed: 217 additions & 87 deletions

File tree

‎packages/pi-plugin/src/commands/ctx-recomp.ts‎

Lines changed: 24 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,30 @@ export function registerCtxRecompCommand(
159159
},
160160
parsed.kind === "partial" ? { range: parsed.range } : {},
161161
);
162+
if (result.published) {
163+
// Stage the native compaction marker + refresh signals
164+
// SYNCHRONOUSLY right after publish, BEFORE the async
165+
// sendCtxStatusMessage below. queueAndApplyPiRecompMarker
166+
// persists pending state durably before applying, so once
167+
// entered the marker survives a crash; staging it ahead of the
168+
// async status send closes the publish→stage yield window where
169+
// a crash would drop the marker. (Impact is bounded regardless:
170+
// trimPiMessagesToBoundary trims the wire every pass independent
171+
// of the native marker, and the next incremental publish
172+
// re-stages a covering marker — so a lost marker only lags the
173+
// JSONL native boundary, never the model-visible context.)
174+
//
175+
// Mirrors OpenCode `hook.ts:477-480`: recomp publishes fresh
176+
// compartments + queues drops for the rebuilt range. Without
177+
// these signals the next pass would render stale
178+
// `<session-history>` until usage crossed execute, and the
179+
// queued drops would sit in `pending_ops` until 85%
180+
// force-materialization. Not signaled on the catch path — a
181+
// failed recomp didn't publish anything to refresh.
182+
queueAndApplyPiRecompMarker({ db: deps.db, sessionId, ctx });
183+
signalPiHistoryRefresh(sessionId);
184+
signalPiPendingMaterialization(sessionId);
185+
}
162186
sendCtxStatusMessage(pi, {
163187
title: "/ctx-recomp",
164188
text: result.message,
@@ -167,19 +191,6 @@ export function registerCtxRecompCommand(
167191
if (!result.published) {
168192
return;
169193
}
170-
// Mirrors OpenCode `hook.ts:477-480`: recomp publishes
171-
// fresh compartments + queues drops for the rebuilt
172-
// range. Without these signals the next pass would
173-
// render stale `<session-history>` until usage crossed
174-
// execute, and the queued drops would sit in
175-
// `pending_ops` until 85% force-materialization.
176-
//
177-
// We do NOT signal these on the catch path — a failed
178-
// recomp didn't publish anything, so there's nothing
179-
// for the next pass to refresh.
180-
queueAndApplyPiRecompMarker({ db: deps.db, sessionId, ctx });
181-
signalPiHistoryRefresh(sessionId);
182-
signalPiPendingMaterialization(sessionId);
183194
} catch (error) {
184195
sendCtxStatusMessage(pi, {
185196
title: "/ctx-recomp",

‎packages/pi-plugin/src/context-handler.ts‎

Lines changed: 102 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -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);

‎packages/pi-plugin/src/index.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1470,7 +1470,14 @@ export default async function (pi: ExtensionAPI): Promise<void> {
14701470
typeof outgoingSessionId === "string" &&
14711471
outgoingSessionId.length > 0
14721472
) {
1473-
clearPiM0Cache(db, outgoingSessionId, "session_before_switch");
1473+
// Clear ONLY the in-memory per-session maps (the actual leak that
1474+
// grows one entry per swap). Do NOT clear the durable DB m[0] cache
1475+
// here: session_before_switch is REVERSIBLE (the user can switch
1476+
// back), unlike OpenCode's session.deleted. The DB cache is bounded
1477+
// (one session_meta row per session) and self-invalidates via
1478+
// epoch/version/docs-hash checks in mustMaterializePi, so preserving
1479+
// it lets a switch-back reuse the cached prefix instead of forcing a
1480+
// full m[0] re-materialization (an avoidable prompt-cache bust).
14741481
clearPiSystemPromptSession(outgoingSessionId);
14751482
clearContextHandlerSession(outgoingSessionId);
14761483
}

‎packages/pi-plugin/src/inject-compartments-pi.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -510,6 +510,13 @@ export interface PiM0M1InjectionResult extends PiInjectionResult {
510510
m0Reason: string | null;
511511
m0Bytes: number;
512512
m1Bytes: number;
513+
/**
514+
* Number of synthetic, id-less messages prepended at the FRONT of the array
515+
* by this injection (the m[0] + m[1] pair). These never resolve to a real
516+
* SessionEntry id, so downstream anchor-GC must exclude them from its
517+
* "all messages resolved" denominator or pruning never runs.
518+
*/
519+
syntheticLeadingCount: number;
513520
}
514521

515522
function decodeCachedM0(value: Buffer | Uint8Array | null): string | null {
@@ -1329,6 +1336,8 @@ export function injectM0M1Pi(
13291336
m0Reason: decision.reason,
13301337
m0Bytes: m0.length,
13311338
m1Bytes: m1.length,
1339+
// prependM0M1Messages always unshifts exactly the m[0] + m[1] pair.
1340+
syntheticLeadingCount: 2,
13321341
};
13331342
}
13341343

‎packages/pi-plugin/src/pi-historian-runner.ts‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,6 @@ import {
7676
validateHistorianOutput,
7777
validateStoredCompartments,
7878
} from "@magic-context/core/hooks/magic-context/compartment-runner-validation";
79-
import { cleanupHistorianStateFile } from "@magic-context/core/hooks/magic-context/historian-state-file";
8079
import { renderMemoryBlock } from "@magic-context/core/hooks/magic-context/inject-compartments";
8180
import { onNoteTrigger } from "@magic-context/core/hooks/magic-context/note-nudger";
8281
import {
@@ -209,7 +208,6 @@ export async function runPiHistorian(deps: PiHistorianDeps): Promise<void> {
209208
};
210209

211210
updateSessionMeta(db, sessionId, { compartmentInProgress: true });
212-
let stateFilePath: string | undefined;
213211

214212
// historian_runs telemetry (migration v24) — recorded ONCE in finally so every
215213
// exit path is logged. Best-effort. Mirrors the OpenCode incremental runner.
@@ -911,9 +909,6 @@ export async function runPiHistorian(deps: PiHistorianDeps): Promise<void> {
911909
} catch {
912910
/* telemetry must not break compaction */
913911
}
914-
// Best-effort cleanup of the temp state file written when existing
915-
// state exceeded the inline threshold. Safe with undefined.
916-
cleanupHistorianStateFile(stateFilePath);
917912
}
918913
}
919914

‎packages/pi-plugin/src/read-session-pi.ts‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -77,11 +77,15 @@ import type { RawMessage } from "@magic-context/core/hooks/magic-context/read-se
7777
* entries is folded into a user turn (the toolResult→assistant transition). The
7878
* id is `${SYNTH_USER_ID_PREFIX}${firstRealToolResultEntryId}` — NOT a real
7979
* SessionEntry id. Pi's `getBranch()`/compaction replay matches against real
80-
* `entry.id`, and Pi never cuts a compaction boundary at a `toolResult` (the
81-
* kept tail must not start with an orphaned tool result), so any consumer that
82-
* needs a replay-safe real entry id (e.g. compaction `firstKeptEntryId`) must
83-
* detect this prefix and advance past it. Exported so those consumers share one
84-
* definition instead of re-deriving the `synth-user-` literal.
80+
* `entry.id`, so any consumer that needs a replay-safe real entry id must detect
81+
* this prefix and handle it — but the handling differs by consumer:
82+
* • compaction-boundary selection (`findFirstKeptEntryId`) DEFERS — it returns
83+
* null when the kept-start lands on a synthetic-user fold, so the marker is
84+
* re-tried next pass rather than cutting the tail at an orphaned toolResult.
85+
* • boundary trimming (`trimPiMessagesToBoundary`) RESOLVES — it strips the
86+
* prefix to recover the underlying real toolResult entry id and trims there.
87+
* Exported so those consumers share one definition instead of re-deriving the
88+
* `synth-user-` literal.
8589
*/
8690
export const SYNTH_USER_ID_PREFIX = "synth-user-";
8791

‎packages/pi-plugin/src/strip-placeholders-pi.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,15 @@ function isDroppedOnlyText(text: string): boolean {
4141
function messageIsPlaceholderOnly(message: unknown): boolean {
4242
if (!message || typeof message !== "object") return false;
4343
const msg = message as { role?: unknown; content?: unknown };
44-
if (msg.role !== "assistant" && msg.role !== "user") return false;
44+
// Only assistant messages may be neutralized/removed. User-role messages
45+
// anchor turn boundaries the AI SDK relies on to avoid merging consecutive
46+
// assistants — removing one can collapse a boundary. Mirrors OpenCode's
47+
// strip-content.ts ("Never neutralize user-role messages — they anchor turn
48+
// boundaries"). In Pi's raw array, tool results carry role "toolResult"
49+
// (synthetic tool-result user folds live only in the transcript view, never
50+
// written back to this array), so genuine user prompts are the only user-role
51+
// entries here — never all-[dropped] — making this a safe parity guard.
52+
if (msg.role !== "assistant") return false;
4553

4654
if (typeof msg.content === "string") return isDroppedOnlyText(msg.content);
4755
if (!Array.isArray(msg.content)) return false;

0 commit comments

Comments
 (0)