@@ -989,6 +989,14 @@ function stripPendingHistoryContextBeforeCurrentMessage(text: string): string {
989989 return candidateText . slice ( currentMessageIndex + CURRENT_MESSAGE_MARKER . length ) ;
990990}
991991
992+ function stripToCurrentMessageMarker ( text : string ) : string | null {
993+ const currentMessageIndex = text . lastIndexOf ( CURRENT_MESSAGE_MARKER ) ;
994+ if ( currentMessageIndex === - 1 ) {
995+ return null ;
996+ }
997+ return text . slice ( currentMessageIndex + CURRENT_MESSAGE_MARKER . length ) ;
998+ }
999+
9921000function stripLeadingCurrentMessageContextBeforeEnvelope ( text : string ) : string {
9931001 const candidateText = text . trimStart ( ) ;
9941002 if ( ! LEADING_CURRENT_MESSAGE_CONTEXT_RE . test ( candidateText ) ) {
@@ -1003,6 +1011,16 @@ function stripLeadingCurrentMessageContextBeforeEnvelope(text: string): string {
10031011 return candidateText . slice ( envelopeIndex ) ;
10041012}
10051013
1014+ function stripLeadingPlainTextMetadataBody ( text : string ) : string {
1015+ const candidateText = text . trimStart ( ) ;
1016+ const markerBody = stripToCurrentMessageMarker ( candidateText ) ;
1017+ if ( markerBody !== null ) {
1018+ return markerBody ;
1019+ }
1020+ const currentMessageBody = stripLeadingCurrentMessageContextBeforeEnvelope ( candidateText ) ;
1021+ return currentMessageBody === candidateText ? "" : currentMessageBody ;
1022+ }
1023+
10061024function stripLeadingInboundEnvelope ( text : string ) : string {
10071025 const candidateText = stripLeadingCurrentMessageContextBeforeEnvelope (
10081026 stripPendingHistoryContextBeforeCurrentMessage ( stripLeadingMessageToolDeliveryHints ( text ) ) ,
@@ -1126,9 +1144,17 @@ export function sanitizeForMemoryCapture(text: string): string {
11261144 cleaned = before ;
11271145 break ;
11281146 }
1129- // Metadata header is at the very beginning -- strip it so the user text
1130- // that follows survives. Loop continues so back-to-back headers at the new
1131- // start are also handled.
1147+ // Metadata header is at the very beginning. Fenced metadata was already
1148+ // removed above; malformed plain-text bodies are untrusted context unless a
1149+ // current-message boundary names the real user body.
1150+ if ( earliestMetaRe === INBOUND_META_LABEL_RE ) {
1151+ const lineEnd = cleaned . indexOf ( "\n" ) ;
1152+ const afterHeader = lineEnd === - 1 ? "" : cleaned . slice ( lineEnd + 1 ) ;
1153+ if ( ! afterHeader . trimStart ( ) . startsWith ( "```json" ) ) {
1154+ cleaned = stripLeadingPlainTextMetadataBody ( afterHeader ) ;
1155+ continue ;
1156+ }
1157+ }
11321158 cleaned = cleaned . replace ( earliestMetaRe , "" ) ;
11331159 }
11341160
0 commit comments