(args: {
sessionId: string;
db: Database;
messages: AgentMessage[];
entryIds?: readonly (string | undefined)[] | null;
/**
* Splice-safe message→entryId map keyed by AgentMessage reference. Resolved
* against branch entries; correct even though `messages` was spliced since
* the positional `entryIds` was computed. Takes precedence over `entryIds`.
*/
entryIdByRef?: ReadonlyMap<object, string> | null;
options: PiAutoSearchOptions;
})
| 272 | * if this implementation later switches to copy-on-write. |
| 273 | */ |
| 274 | export async function runAutoSearchHintForPi(args: { |
| 275 | sessionId: string; |
| 276 | db: Database; |
| 277 | messages: AgentMessage[]; |
| 278 | entryIds?: readonly (string | undefined)[] | null; |
| 279 | /** |
| 280 | * Splice-safe message→entryId map keyed by AgentMessage reference. Resolved |
| 281 | * against branch entries; correct even though `messages` was spliced since |
| 282 | * the positional `entryIds` was computed. Takes precedence over `entryIds`. |
| 283 | */ |
| 284 | entryIdByRef?: ReadonlyMap<object, string> | null; |
| 285 | options: PiAutoSearchOptions; |
| 286 | }): Promise<AgentMessage[]> { |
| 287 | const { sessionId, db, messages, options, entryIdByRef } = args; |
| 288 | const entryIds = |
| 289 | args.entryIds === undefined |
| 290 | ? messages.map((message, index) => { |
| 291 | const timestamp = (message as { timestamp?: unknown }).timestamp; |
| 292 | return `test-entry-${index}:${typeof timestamp === "number" ? timestamp : "no-ts"}`; |
| 293 | }) |
| 294 | : args.entryIds; |
| 295 | if (!options.enabled) return messages; |
| 296 | const strictResolutionFailed = entryIds === null; |
| 297 | const effectiveEntryIds = strictResolutionFailed |
| 298 | ? messages.map((message) => { |
| 299 | const id = (message as { id?: unknown }).id; |
| 300 | return typeof id === "string" ? id : undefined; |
| 301 | }) |
| 302 | : entryIds; |
| 303 | |
| 304 | const found = findLatestMeaningfulUserMessage( |
| 305 | messages, |
| 306 | effectiveEntryIds, |
| 307 | entryIdByRef, |
| 308 | ); |
| 309 | if (found === null) return messages; |
| 310 | |
| 311 | const { message: userMsg, messageId: userMsgId } = found; |
| 312 | const existing = getAutoSearchHintDecisions(db, sessionId); |
| 313 | const existingForMessage = existing.find( |
| 314 | (decision) => decision.messageId === userMsgId, |
| 315 | ); |
| 316 | if (existingForMessage) { |
| 317 | if (existingForMessage.decision === "hint") { |
| 318 | appendHintToUserMessage(userMsg, existingForMessage.text); |
| 319 | } |
| 320 | return messages; |
| 321 | } |
| 322 | if (strictResolutionFailed) { |
| 323 | sessionLog( |
| 324 | sessionId, |
| 325 | "Pi auto-search: strict entry-id resolution failed; replayed persisted decisions only", |
| 326 | ); |
| 327 | return messages; |
| 328 | } |
| 329 | |
| 330 | const writeNoHintAndReconcile = ( |
| 331 | reason: AutoSearchHintNoHintReason, |
no test coverage detected