@caupulican/pi-agent-core 0.81.29 → 0.81.30
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.
- package/dist/compaction/branch-summarization.d.ts.map +1 -1
- package/dist/compaction/branch-summarization.js +5 -3
- package/dist/compaction/branch-summarization.js.map +1 -1
- package/dist/compaction/extraction.d.ts.map +1 -1
- package/dist/compaction/extraction.js +12 -2
- package/dist/compaction/extraction.js.map +1 -1
- package/dist/compaction/verification.d.ts.map +1 -1
- package/dist/compaction/verification.js +27 -14
- package/dist/compaction/verification.js.map +1 -1
- package/dist/proxy.d.ts.map +1 -1
- package/dist/proxy.js +30 -5
- package/dist/proxy.js.map +1 -1
- package/dist/session/session-manager.d.ts +12 -0
- package/dist/session/session-manager.d.ts.map +1 -1
- package/dist/session/session-manager.js +270 -46
- package/dist/session/session-manager.js.map +1 -1
- package/dist/utils/streaming-lines.d.ts +20 -0
- package/dist/utils/streaming-lines.d.ts.map +1 -0
- package/dist/utils/streaming-lines.js +79 -0
- package/dist/utils/streaming-lines.js.map +1 -0
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"branch-summarization.d.ts","sourceRoot":"","sources":["../../src/compaction/branch-summarization.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAA6B,KAAK,EAAuB,MAAM,mBAAmB,CAAC;AAS/F,OAAO,KAAK,EAAE,sBAAsB,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAC1F,OAAO,KAAK,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAE1D,OAAO,EAIN,KAAK,cAAc,EAInB,MAAM,YAAY,CAAC;AAMpB,MAAM,WAAW,mBAAmB;IACnC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC;IACrB,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;IACzB,OAAO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AAC,OAAO,EAAE,YAAY,EAAE,EAAE,WAAW,GAAE,MAAU,GAAG,iBAAiB,CAoDxG;AAyDD,wBAAsB,qBAAqB,CAC1C,OAAO,EAAE,YAAY,EAAE,EACvB,OAAO,EAAE,4BAA4B,GACnC,OAAO,CAAC,mBAAmB,CAAC,CAuF9B","sourcesContent":["/**\n * Branch summarization for tree navigation.\n *\n * When navigating to a different point in the session tree, this generates\n * a summary of the branch being left so context isn't lost.\n */\n\nimport type { AssistantMessage, Context, Model, SimpleStreamOptions } from \"@caupulican/pi-ai\";\nimport { completeSimple } from \"@caupulican/pi-ai\";\nimport {\n\tconvertToLlm,\n\tcreateBranchSummaryMessage,\n\tcreateCompactionSummaryMessage,\n\tcreateCustomMessage,\n} from \"../messages.ts\";\nimport { classifyFailure } from \"../reliability/classifier.ts\";\nimport type { ReadonlySessionManager, SessionEntry } from \"../session/session-manager.ts\";\nimport type { AgentMessage, StreamFn } from \"../types.ts\";\nimport { estimateTokens } from \"./compaction.ts\";\nimport {\n\tcomputeFileLists,\n\tcreateFileOps,\n\textractFileOpsFromMessage,\n\ttype FileOperations,\n\tformatFileOperations,\n\tSUMMARIZATION_SYSTEM_PROMPT,\n\tserializeConversation,\n} from \"./utils.ts\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface BranchSummaryResult {\n\tsummary?: string;\n\treadFiles?: string[];\n\tmodifiedFiles?: string[];\n\taborted?: boolean;\n\terror?: string;\n}\n\n/** Details stored in BranchSummaryEntry.details for file tracking */\nexport interface BranchSummaryDetails {\n\treadFiles: string[];\n\tmodifiedFiles: string[];\n}\n\nexport type { FileOperations } from \"./utils.ts\";\n\nexport interface BranchPreparation {\n\t/** Messages extracted for summarization, in chronological order */\n\tmessages: AgentMessage[];\n\t/** File operations extracted from tool calls */\n\tfileOps: FileOperations;\n\t/** Total estimated tokens in messages */\n\ttotalTokens: number;\n}\n\nexport interface CollectEntriesResult {\n\t/** Entries to summarize, in chronological order */\n\tentries: SessionEntry[];\n\t/** Common ancestor between old and new position, if any */\n\tcommonAncestorId: string | null;\n}\n\nexport interface GenerateBranchSummaryOptions {\n\t/** Model to use for summarization */\n\tmodel: Model<any>;\n\t/** API key for the model */\n\tapiKey: string;\n\t/** Request headers for the model */\n\theaders?: Record<string, string>;\n\t/** Abort signal for cancellation */\n\tsignal: AbortSignal;\n\t/** Optional custom instructions for summarization */\n\tcustomInstructions?: string;\n\t/** If true, customInstructions replaces the default prompt instead of being appended */\n\treplaceInstructions?: boolean;\n\t/** Tokens reserved for prompt + LLM response (default 16384) */\n\treserveTokens?: number;\n\t/** Optional wrapped stream function (watchdog/retry-capable host path). */\n\tstreamFn?: StreamFn;\n}\n\n// ============================================================================\n// Entry Collection\n// ============================================================================\n\n/**\n * Collect entries that should be summarized when navigating from one position to another.\n *\n * Walks from oldLeafId back to the common ancestor with targetId, collecting entries\n * along the way. Does NOT stop at compaction boundaries - those are included and their\n * summaries become context.\n *\n * @param session - Session manager (read-only access)\n * @param oldLeafId - Current position (where we're navigating from)\n * @param targetId - Target position (where we're navigating to)\n * @returns Entries to summarize and the common ancestor\n */\nexport function collectEntriesForBranchSummary(\n\tsession: ReadonlySessionManager,\n\toldLeafId: string | null,\n\ttargetId: string,\n): CollectEntriesResult {\n\t// If no old position, nothing to summarize\n\tif (!oldLeafId) {\n\t\treturn { entries: [], commonAncestorId: null };\n\t}\n\n\t// Find common ancestor (deepest node that's on both paths)\n\tconst oldPath = new Set(session.getBranch(oldLeafId).map((e) => e.id));\n\tconst targetPath = session.getBranch(targetId);\n\n\t// targetPath is root-first, so iterate backwards to find deepest common ancestor\n\tlet commonAncestorId: string | null = null;\n\tfor (let i = targetPath.length - 1; i >= 0; i--) {\n\t\tif (oldPath.has(targetPath[i].id)) {\n\t\t\tcommonAncestorId = targetPath[i].id;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// Collect entries from old leaf back to common ancestor\n\tconst entries: SessionEntry[] = [];\n\tlet current: string | null = oldLeafId;\n\n\twhile (current && current !== commonAncestorId) {\n\t\tconst entry = session.getEntry(current);\n\t\tif (!entry) break;\n\t\tentries.push(entry);\n\t\tcurrent = entry.parentId;\n\t}\n\n\t// Reverse to get chronological order\n\tentries.reverse();\n\n\treturn { entries, commonAncestorId };\n}\n\n// ============================================================================\n// Entry to Message Conversion\n// ============================================================================\n\n/**\n * Extract AgentMessage from a session entry.\n * Similar to getMessageFromEntry in compaction.ts but also handles compaction entries.\n */\nfunction getMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tswitch (entry.type) {\n\t\tcase \"message\":\n\t\t\t// Skip tool results - context is in assistant's tool call\n\t\t\tif (entry.message.role === \"toolResult\") return undefined;\n\t\t\treturn entry.message;\n\n\t\tcase \"custom_message\":\n\t\t\treturn createCustomMessage(entry.customType, entry.content, entry.display, entry.details, entry.timestamp);\n\n\t\tcase \"branch_summary\":\n\t\t\treturn createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);\n\n\t\tcase \"compaction\":\n\t\t\treturn createCompactionSummaryMessage(entry.summary, entry.tokensBefore, entry.timestamp);\n\n\t\t// These don't contribute to conversation content\n\t\tcase \"thinking_level_change\":\n\t\tcase \"model_change\":\n\t\tcase \"custom\":\n\t\tcase \"label\":\n\t\tcase \"session_info\":\n\t\t\treturn undefined;\n\t}\n}\n\n/**\n * Prepare entries for summarization with token budget.\n *\n * Walks entries from NEWEST to OLDEST, adding messages until we hit the token budget.\n * This ensures we keep the most recent context when the branch is too long.\n *\n * Also collects file operations from:\n * - Tool calls in assistant messages\n * - Existing branch_summary entries' details (for cumulative tracking)\n *\n * @param entries - Entries in chronological order\n * @param tokenBudget - Maximum tokens to include (0 = no limit)\n */\nexport function prepareBranchEntries(entries: SessionEntry[], tokenBudget: number = 0): BranchPreparation {\n\tconst messages: AgentMessage[] = [];\n\tconst fileOps = createFileOps();\n\tlet totalTokens = 0;\n\n\t// First pass: collect file ops from ALL entries (even if they don't fit in token budget)\n\t// This ensures we capture cumulative file tracking from nested branch summaries\n\t// Only extract from pi-generated summaries (fromHook !== true), not extension-generated ones\n\tfor (const entry of entries) {\n\t\tif (entry.type === \"branch_summary\" && !entry.fromHook && entry.details) {\n\t\t\tconst details = entry.details as BranchSummaryDetails;\n\t\t\tif (Array.isArray(details.readFiles)) {\n\t\t\t\tfor (const f of details.readFiles) fileOps.read.add(f);\n\t\t\t}\n\t\t\tif (Array.isArray(details.modifiedFiles)) {\n\t\t\t\t// Modified files go into both edited and written for proper deduplication\n\t\t\t\tfor (const f of details.modifiedFiles) {\n\t\t\t\t\tfileOps.edited.add(f);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Second pass: walk from newest to oldest, adding messages until token budget\n\tfor (let i = entries.length - 1; i >= 0; i--) {\n\t\tconst entry = entries[i];\n\t\tconst message = getMessageFromEntry(entry);\n\t\tif (!message) continue;\n\n\t\t// Extract file ops from assistant messages (tool calls)\n\t\textractFileOpsFromMessage(message, fileOps);\n\n\t\tconst tokens = estimateTokens(message);\n\n\t\t// Check budget before adding\n\t\tif (tokenBudget > 0 && totalTokens + tokens > tokenBudget) {\n\t\t\t// If this is a summary entry, try to fit it anyway as it's important context\n\t\t\tif (entry.type === \"compaction\" || entry.type === \"branch_summary\") {\n\t\t\t\tif (totalTokens < tokenBudget * 0.9) {\n\t\t\t\t\tmessages.unshift(message);\n\t\t\t\t\ttotalTokens += tokens;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Stop - we've hit the budget\n\t\t\tbreak;\n\t\t}\n\n\t\tmessages.unshift(message);\n\t\ttotalTokens += tokens;\n\t}\n\n\treturn { messages, fileOps, totalTokens };\n}\n\n// ============================================================================\n// Summary Generation\n// ============================================================================\n\nconst BRANCH_SUMMARY_PREAMBLE = `The user explored a different conversation branch before returning here.\nSummary of that exploration:\n\n`;\n\nconst BRANCH_SUMMARY_PROMPT = `Create a structured summary of this conversation branch for context when returning later.\n\nUse this EXACT format:\n\n## Goal\n[What was the user trying to accomplish in this branch?]\n\n## Constraints & Preferences\n- [Any constraints, preferences, or requirements mentioned]\n- [Or \"(none)\" if none were mentioned]\n\n## Progress\n### Done\n- [x] [Completed tasks/changes]\n\n### In Progress\n- [ ] [Work that was started but not finished]\n\n### Blocked\n- [Issues preventing progress, if any]\n\n## Key Decisions\n- **[Decision]**: [Brief rationale]\n\n## Next Steps\n1. [What should happen next to continue this work]\n\nKeep each section concise. Preserve exact file paths, function names, and error messages.`;\n\n/**\n * Generate a summary of abandoned branch entries.\n *\n * @param entries - Session entries to summarize (chronological order)\n * @param options - Generation options\n */\nasync function completeBranchSummary(\n\tmodel: Model<any>,\n\tcontext: Context,\n\toptions: SimpleStreamOptions,\n\tstreamFn?: StreamFn,\n): Promise<AssistantMessage> {\n\tif (!streamFn) return completeSimple(model, context, options);\n\tconst stream = await streamFn(model, context, options);\n\treturn stream.result();\n}\n\nexport async function generateBranchSummary(\n\tentries: SessionEntry[],\n\toptions: GenerateBranchSummaryOptions,\n): Promise<BranchSummaryResult> {\n\tconst {\n\t\tmodel,\n\t\tapiKey,\n\t\theaders,\n\t\tsignal,\n\t\tcustomInstructions,\n\t\treplaceInstructions,\n\t\treserveTokens = 16384,\n\t\tstreamFn,\n\t} = options;\n\n\t// Token budget = context window minus reserved space for prompt + response\n\tconst contextWindow = model.contextWindow || 128000;\n\tconst tokenBudget = contextWindow - reserveTokens;\n\n\tconst { messages, fileOps } = prepareBranchEntries(entries, tokenBudget);\n\n\tif (messages.length === 0) {\n\t\treturn { summary: \"No content to summarize\" };\n\t}\n\n\t// Transform to LLM-compatible messages, then serialize to text\n\t// Serialization prevents the model from treating it as a conversation to continue\n\tconst llmMessages = convertToLlm(messages);\n\tconst conversationText = serializeConversation(llmMessages);\n\n\t// Build prompt\n\tlet instructions: string;\n\tif (replaceInstructions && customInstructions) {\n\t\tinstructions = customInstructions;\n\t} else if (customInstructions) {\n\t\tinstructions = `${BRANCH_SUMMARY_PROMPT}\\n\\nAdditional focus: ${customInstructions}`;\n\t} else {\n\t\tinstructions = BRANCH_SUMMARY_PROMPT;\n\t}\n\tconst promptText = `<conversation>\\n${conversationText}\\n</conversation>\\n\\n${instructions}`;\n\n\tconst summarizationMessages = [\n\t\t{\n\t\t\trole: \"user\" as const,\n\t\t\tcontent: [{ type: \"text\" as const, text: promptText }],\n\t\t\ttimestamp: Date.now(),\n\t\t},\n\t];\n\n\t// Call LLM for summarization. Retry transient provider/watchdog failures so branch summaries\n\t// use the same reliability doctrine as compaction instead of bypassing the host stream wrapper.\n\tlet response: AssistantMessage | undefined;\n\tfor (let attempt = 0; attempt < 3; attempt++) {\n\t\tresponse = await completeBranchSummary(\n\t\t\tmodel,\n\t\t\t{ systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, messages: summarizationMessages },\n\t\t\t{ apiKey, headers, signal, maxTokens: 2048 },\n\t\t\tstreamFn,\n\t\t);\n\t\tif (response.stopReason !== \"error\") break;\n\t\tconst classified = classifyFailure({ message: response.errorMessage ?? \"\", provider: response.provider });\n\t\tif (!classified.retryable || signal.aborted) break;\n\t}\n\tif (!response) return { error: \"Summarization failed\" };\n\n\t// Check if aborted or errored\n\tif (response.stopReason === \"aborted\") {\n\t\treturn { aborted: true };\n\t}\n\tif (response.stopReason === \"error\") {\n\t\treturn { error: response.errorMessage || \"Summarization failed\" };\n\t}\n\n\tlet summary = response.content\n\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t.map((c) => c.text)\n\t\t.join(\"\\n\");\n\n\t// Prepend preamble to provide context about the branch summary\n\tsummary = BRANCH_SUMMARY_PREAMBLE + summary;\n\n\t// Compute file lists and append to summary\n\tconst { readFiles, modifiedFiles } = computeFileLists(fileOps);\n\tsummary += formatFileOperations(readFiles, modifiedFiles);\n\n\treturn {\n\t\tsummary: summary || \"No summary generated\",\n\t\treadFiles,\n\t\tmodifiedFiles,\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"branch-summarization.d.ts","sourceRoot":"","sources":["../../src/compaction/branch-summarization.ts"],"names":[],"mappings":"AA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C;IACpB,qDAAqD;IACrD,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,wFAAwF;IACxF,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,gEAAgE;IAChE,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,2EAA2E;IAC3E,QAAQ,CAAC,EAAE,QAAQ,CAAC;CACpB;AAMD;;;;;;;;;;;GAWG;AACH,wBAAgB,8BAA8B,CAC7C,OAAO,EAAE,sBAAsB,EAC/B,SAAS,EAAE,MAAM,GAAG,IAAI,EACxB,QAAQ,EAAE,MAAM,GACd,oBAAoB,CAkCtB;AAoCD;;;;;;;;;;;;GAYG;AACH,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,YAAY,EAAE,EAAE,WAAW,GAAE,MAAU,GAAG,iBAAiB,CAsDxG;AAyDD,wBAAsB,qBAAqB,CAC1C,OAAO,EAAE,YAAY,EAAE,EACvB,OAAO,EAAE,4BAA4B,GACnC,OAAO,CAAC,mBAAmB,CAAC,CAuF9B","sourcesContent":["/**\n * Branch summarization for tree navigation.\n *\n * When navigating to a different point in the session tree, this generates\n * a summary of the branch being left so context isn't lost.\n */\n\nimport type { AssistantMessage, Context, Model, SimpleStreamOptions } from \"@caupulican/pi-ai\";\nimport { completeSimple } from \"@caupulican/pi-ai\";\nimport {\n\tconvertToLlm,\n\tcreateBranchSummaryMessage,\n\tcreateCompactionSummaryMessage,\n\tcreateCustomMessage,\n} from \"../messages.ts\";\nimport { classifyFailure } from \"../reliability/classifier.ts\";\nimport type { ReadonlySessionManager, SessionEntry } from \"../session/session-manager.ts\";\nimport type { AgentMessage, StreamFn } from \"../types.ts\";\nimport { estimateTokens } from \"./compaction.ts\";\nimport {\n\tcomputeFileLists,\n\tcreateFileOps,\n\textractFileOpsFromMessage,\n\ttype FileOperations,\n\tformatFileOperations,\n\tSUMMARIZATION_SYSTEM_PROMPT,\n\tserializeConversation,\n} from \"./utils.ts\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface BranchSummaryResult {\n\tsummary?: string;\n\treadFiles?: string[];\n\tmodifiedFiles?: string[];\n\taborted?: boolean;\n\terror?: string;\n}\n\n/** Details stored in BranchSummaryEntry.details for file tracking */\nexport interface BranchSummaryDetails {\n\treadFiles: string[];\n\tmodifiedFiles: string[];\n}\n\nexport type { FileOperations } from \"./utils.ts\";\n\nexport interface BranchPreparation {\n\t/** Messages extracted for summarization, in chronological order */\n\tmessages: AgentMessage[];\n\t/** File operations extracted from tool calls */\n\tfileOps: FileOperations;\n\t/** Total estimated tokens in messages */\n\ttotalTokens: number;\n}\n\nexport interface CollectEntriesResult {\n\t/** Entries to summarize, in chronological order */\n\tentries: SessionEntry[];\n\t/** Common ancestor between old and new position, if any */\n\tcommonAncestorId: string | null;\n}\n\nexport interface GenerateBranchSummaryOptions {\n\t/** Model to use for summarization */\n\tmodel: Model<any>;\n\t/** API key for the model */\n\tapiKey: string;\n\t/** Request headers for the model */\n\theaders?: Record<string, string>;\n\t/** Abort signal for cancellation */\n\tsignal: AbortSignal;\n\t/** Optional custom instructions for summarization */\n\tcustomInstructions?: string;\n\t/** If true, customInstructions replaces the default prompt instead of being appended */\n\treplaceInstructions?: boolean;\n\t/** Tokens reserved for prompt + LLM response (default 16384) */\n\treserveTokens?: number;\n\t/** Optional wrapped stream function (watchdog/retry-capable host path). */\n\tstreamFn?: StreamFn;\n}\n\n// ============================================================================\n// Entry Collection\n// ============================================================================\n\n/**\n * Collect entries that should be summarized when navigating from one position to another.\n *\n * Walks from oldLeafId back to the common ancestor with targetId, collecting entries\n * along the way. Does NOT stop at compaction boundaries - those are included and their\n * summaries become context.\n *\n * @param session - Session manager (read-only access)\n * @param oldLeafId - Current position (where we're navigating from)\n * @param targetId - Target position (where we're navigating to)\n * @returns Entries to summarize and the common ancestor\n */\nexport function collectEntriesForBranchSummary(\n\tsession: ReadonlySessionManager,\n\toldLeafId: string | null,\n\ttargetId: string,\n): CollectEntriesResult {\n\t// If no old position, nothing to summarize\n\tif (!oldLeafId) {\n\t\treturn { entries: [], commonAncestorId: null };\n\t}\n\n\t// Find common ancestor (deepest node that's on both paths)\n\tconst oldPath = new Set(session.getBranch(oldLeafId).map((e) => e.id));\n\tconst targetPath = session.getBranch(targetId);\n\n\t// targetPath is root-first, so iterate backwards to find deepest common ancestor\n\tlet commonAncestorId: string | null = null;\n\tfor (let i = targetPath.length - 1; i >= 0; i--) {\n\t\tif (oldPath.has(targetPath[i].id)) {\n\t\t\tcommonAncestorId = targetPath[i].id;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// Collect entries from old leaf back to common ancestor\n\tconst entries: SessionEntry[] = [];\n\tlet current: string | null = oldLeafId;\n\n\twhile (current && current !== commonAncestorId) {\n\t\tconst entry = session.getEntry(current);\n\t\tif (!entry) break;\n\t\tentries.push(entry);\n\t\tcurrent = entry.parentId;\n\t}\n\n\t// Reverse to get chronological order\n\tentries.reverse();\n\n\treturn { entries, commonAncestorId };\n}\n\n// ============================================================================\n// Entry to Message Conversion\n// ============================================================================\n\n/**\n * Extract AgentMessage from a session entry.\n * Similar to getMessageFromEntry in compaction.ts but also handles compaction entries.\n */\nfunction getMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tswitch (entry.type) {\n\t\tcase \"message\":\n\t\t\t// Skip tool results - context is in assistant's tool call\n\t\t\tif (entry.message.role === \"toolResult\") return undefined;\n\t\t\treturn entry.message;\n\n\t\tcase \"custom_message\":\n\t\t\treturn createCustomMessage(entry.customType, entry.content, entry.display, entry.details, entry.timestamp);\n\n\t\tcase \"branch_summary\":\n\t\t\treturn createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);\n\n\t\tcase \"compaction\":\n\t\t\treturn createCompactionSummaryMessage(entry.summary, entry.tokensBefore, entry.timestamp);\n\n\t\t// These don't contribute to conversation content\n\t\tcase \"thinking_level_change\":\n\t\tcase \"model_change\":\n\t\tcase \"custom\":\n\t\tcase \"label\":\n\t\tcase \"session_info\":\n\t\t\treturn undefined;\n\t}\n}\n\n/**\n * Prepare entries for summarization with token budget.\n *\n * Walks entries from NEWEST to OLDEST, adding messages until we hit the token budget.\n * This ensures we keep the most recent context when the branch is too long.\n *\n * Also collects file operations from:\n * - Tool calls in assistant messages\n * - Existing branch_summary entries' details (for cumulative tracking)\n *\n * @param entries - Entries in chronological order\n * @param tokenBudget - Maximum tokens to include (0 = no limit)\n */\nexport function prepareBranchEntries(entries: SessionEntry[], tokenBudget: number = 0): BranchPreparation {\n\tconst messages: AgentMessage[] = [];\n\tconst fileOps = createFileOps();\n\tlet totalTokens = 0;\n\n\t// First pass: collect file ops from ALL entries (even if they don't fit in token budget)\n\t// This ensures we capture cumulative file tracking from nested branch summaries\n\t// Only extract from pi-generated summaries (fromHook !== true), not extension-generated ones\n\tfor (const entry of entries) {\n\t\tif (entry.type === \"branch_summary\" && !entry.fromHook && entry.details) {\n\t\t\tconst details = entry.details as BranchSummaryDetails;\n\t\t\tif (Array.isArray(details.readFiles)) {\n\t\t\t\tfor (const f of details.readFiles) fileOps.read.add(f);\n\t\t\t}\n\t\t\tif (Array.isArray(details.modifiedFiles)) {\n\t\t\t\t// Modified files go into both edited and written for proper deduplication\n\t\t\t\tfor (const f of details.modifiedFiles) {\n\t\t\t\t\tfileOps.edited.add(f);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Second pass: walk from newest to oldest, adding messages until token budget.\n\t// Append in reverse chronology and reverse once so large branches stay linear.\n\tfor (let i = entries.length - 1; i >= 0; i--) {\n\t\tconst entry = entries[i];\n\t\tconst message = getMessageFromEntry(entry);\n\t\tif (!message) continue;\n\n\t\t// Extract file ops from assistant messages (tool calls)\n\t\textractFileOpsFromMessage(message, fileOps);\n\n\t\tconst tokens = estimateTokens(message);\n\n\t\t// Check budget before adding\n\t\tif (tokenBudget > 0 && totalTokens + tokens > tokenBudget) {\n\t\t\t// If this is a summary entry, try to fit it anyway as it's important context\n\t\t\tif (entry.type === \"compaction\" || entry.type === \"branch_summary\") {\n\t\t\t\tif (totalTokens < tokenBudget * 0.9) {\n\t\t\t\t\tmessages.push(message);\n\t\t\t\t\ttotalTokens += tokens;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Stop - we've hit the budget\n\t\t\tbreak;\n\t\t}\n\n\t\tmessages.push(message);\n\t\ttotalTokens += tokens;\n\t}\n\n\tmessages.reverse();\n\treturn { messages, fileOps, totalTokens };\n}\n\n// ============================================================================\n// Summary Generation\n// ============================================================================\n\nconst BRANCH_SUMMARY_PREAMBLE = `The user explored a different conversation branch before returning here.\nSummary of that exploration:\n\n`;\n\nconst BRANCH_SUMMARY_PROMPT = `Create a structured summary of this conversation branch for context when returning later.\n\nUse this EXACT format:\n\n## Goal\n[What was the user trying to accomplish in this branch?]\n\n## Constraints & Preferences\n- [Any constraints, preferences, or requirements mentioned]\n- [Or \"(none)\" if none were mentioned]\n\n## Progress\n### Done\n- [x] [Completed tasks/changes]\n\n### In Progress\n- [ ] [Work that was started but not finished]\n\n### Blocked\n- [Issues preventing progress, if any]\n\n## Key Decisions\n- **[Decision]**: [Brief rationale]\n\n## Next Steps\n1. [What should happen next to continue this work]\n\nKeep each section concise. Preserve exact file paths, function names, and error messages.`;\n\n/**\n * Generate a summary of abandoned branch entries.\n *\n * @param entries - Session entries to summarize (chronological order)\n * @param options - Generation options\n */\nasync function completeBranchSummary(\n\tmodel: Model<any>,\n\tcontext: Context,\n\toptions: SimpleStreamOptions,\n\tstreamFn?: StreamFn,\n): Promise<AssistantMessage> {\n\tif (!streamFn) return completeSimple(model, context, options);\n\tconst stream = await streamFn(model, context, options);\n\treturn stream.result();\n}\n\nexport async function generateBranchSummary(\n\tentries: SessionEntry[],\n\toptions: GenerateBranchSummaryOptions,\n): Promise<BranchSummaryResult> {\n\tconst {\n\t\tmodel,\n\t\tapiKey,\n\t\theaders,\n\t\tsignal,\n\t\tcustomInstructions,\n\t\treplaceInstructions,\n\t\treserveTokens = 16384,\n\t\tstreamFn,\n\t} = options;\n\n\t// Token budget = context window minus reserved space for prompt + response\n\tconst contextWindow = model.contextWindow || 128000;\n\tconst tokenBudget = contextWindow - reserveTokens;\n\n\tconst { messages, fileOps } = prepareBranchEntries(entries, tokenBudget);\n\n\tif (messages.length === 0) {\n\t\treturn { summary: \"No content to summarize\" };\n\t}\n\n\t// Transform to LLM-compatible messages, then serialize to text\n\t// Serialization prevents the model from treating it as a conversation to continue\n\tconst llmMessages = convertToLlm(messages);\n\tconst conversationText = serializeConversation(llmMessages);\n\n\t// Build prompt\n\tlet instructions: string;\n\tif (replaceInstructions && customInstructions) {\n\t\tinstructions = customInstructions;\n\t} else if (customInstructions) {\n\t\tinstructions = `${BRANCH_SUMMARY_PROMPT}\\n\\nAdditional focus: ${customInstructions}`;\n\t} else {\n\t\tinstructions = BRANCH_SUMMARY_PROMPT;\n\t}\n\tconst promptText = `<conversation>\\n${conversationText}\\n</conversation>\\n\\n${instructions}`;\n\n\tconst summarizationMessages = [\n\t\t{\n\t\t\trole: \"user\" as const,\n\t\t\tcontent: [{ type: \"text\" as const, text: promptText }],\n\t\t\ttimestamp: Date.now(),\n\t\t},\n\t];\n\n\t// Call LLM for summarization. Retry transient provider/watchdog failures so branch summaries\n\t// use the same reliability doctrine as compaction instead of bypassing the host stream wrapper.\n\tlet response: AssistantMessage | undefined;\n\tfor (let attempt = 0; attempt < 3; attempt++) {\n\t\tresponse = await completeBranchSummary(\n\t\t\tmodel,\n\t\t\t{ systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, messages: summarizationMessages },\n\t\t\t{ apiKey, headers, signal, maxTokens: 2048 },\n\t\t\tstreamFn,\n\t\t);\n\t\tif (response.stopReason !== \"error\") break;\n\t\tconst classified = classifyFailure({ message: response.errorMessage ?? \"\", provider: response.provider });\n\t\tif (!classified.retryable || signal.aborted) break;\n\t}\n\tif (!response) return { error: \"Summarization failed\" };\n\n\t// Check if aborted or errored\n\tif (response.stopReason === \"aborted\") {\n\t\treturn { aborted: true };\n\t}\n\tif (response.stopReason === \"error\") {\n\t\treturn { error: response.errorMessage || \"Summarization failed\" };\n\t}\n\n\tlet summary = response.content\n\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t.map((c) => c.text)\n\t\t.join(\"\\n\");\n\n\t// Prepend preamble to provide context about the branch summary\n\tsummary = BRANCH_SUMMARY_PREAMBLE + summary;\n\n\t// Compute file lists and append to summary\n\tconst { readFiles, modifiedFiles } = computeFileLists(fileOps);\n\tsummary += formatFileOperations(readFiles, modifiedFiles);\n\n\treturn {\n\t\tsummary: summary || \"No summary generated\",\n\t\treadFiles,\n\t\tmodifiedFiles,\n\t};\n}\n"]}
|
|
@@ -118,7 +118,8 @@ export function prepareBranchEntries(entries, tokenBudget = 0) {
|
|
|
118
118
|
}
|
|
119
119
|
}
|
|
120
120
|
}
|
|
121
|
-
// Second pass: walk from newest to oldest, adding messages until token budget
|
|
121
|
+
// Second pass: walk from newest to oldest, adding messages until token budget.
|
|
122
|
+
// Append in reverse chronology and reverse once so large branches stay linear.
|
|
122
123
|
for (let i = entries.length - 1; i >= 0; i--) {
|
|
123
124
|
const entry = entries[i];
|
|
124
125
|
const message = getMessageFromEntry(entry);
|
|
@@ -132,16 +133,17 @@ export function prepareBranchEntries(entries, tokenBudget = 0) {
|
|
|
132
133
|
// If this is a summary entry, try to fit it anyway as it's important context
|
|
133
134
|
if (entry.type === "compaction" || entry.type === "branch_summary") {
|
|
134
135
|
if (totalTokens < tokenBudget * 0.9) {
|
|
135
|
-
messages.
|
|
136
|
+
messages.push(message);
|
|
136
137
|
totalTokens += tokens;
|
|
137
138
|
}
|
|
138
139
|
}
|
|
139
140
|
// Stop - we've hit the budget
|
|
140
141
|
break;
|
|
141
142
|
}
|
|
142
|
-
messages.
|
|
143
|
+
messages.push(message);
|
|
143
144
|
totalTokens += tokens;
|
|
144
145
|
}
|
|
146
|
+
messages.reverse();
|
|
145
147
|
return { messages, fileOps, totalTokens };
|
|
146
148
|
}
|
|
147
149
|
// ============================================================================
|
|
@@ -1 +1 @@
|
|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SAC5B,MAAM,CAAC,CAAC,CAAC,EAAuC,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC;SACrE,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;SAClB,IAAI,CAAC,IAAI,CAAC,CAAC;IAEb,+DAA+D;IAC/D,OAAO,GAAG,uBAAuB,GAAG,OAAO,CAAC;IAE5C,2CAA2C;IAC3C,MAAM,EAAE,SAAS,EAAE,aAAa,EAAE,GAAG,gBAAgB,CAAC,OAAO,CAAC,CAAC;IAC/D,OAAO,IAAI,oBAAoB,CAAC,SAAS,EAAE,aAAa,CAAC,CAAC;IAE1D,OAAO;QACN,OAAO,EAAE,OAAO,IAAI,sBAAsB;QAC1C,SAAS;QACT,aAAa;KACb,CAAC;AAAA,CACF","sourcesContent":["/**\n * Branch summarization for tree navigation.\n *\n * When navigating to a different point in the session tree, this generates\n * a summary of the branch being left so context isn't lost.\n */\n\nimport type { AssistantMessage, Context, Model, SimpleStreamOptions } from \"@caupulican/pi-ai\";\nimport { completeSimple } from \"@caupulican/pi-ai\";\nimport {\n\tconvertToLlm,\n\tcreateBranchSummaryMessage,\n\tcreateCompactionSummaryMessage,\n\tcreateCustomMessage,\n} from \"../messages.ts\";\nimport { classifyFailure } from \"../reliability/classifier.ts\";\nimport type { ReadonlySessionManager, SessionEntry } from \"../session/session-manager.ts\";\nimport type { AgentMessage, StreamFn } from \"../types.ts\";\nimport { estimateTokens } from \"./compaction.ts\";\nimport {\n\tcomputeFileLists,\n\tcreateFileOps,\n\textractFileOpsFromMessage,\n\ttype FileOperations,\n\tformatFileOperations,\n\tSUMMARIZATION_SYSTEM_PROMPT,\n\tserializeConversation,\n} from \"./utils.ts\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface BranchSummaryResult {\n\tsummary?: string;\n\treadFiles?: string[];\n\tmodifiedFiles?: string[];\n\taborted?: boolean;\n\terror?: string;\n}\n\n/** Details stored in BranchSummaryEntry.details for file tracking */\nexport interface BranchSummaryDetails {\n\treadFiles: string[];\n\tmodifiedFiles: string[];\n}\n\nexport type { FileOperations } from \"./utils.ts\";\n\nexport interface BranchPreparation {\n\t/** Messages extracted for summarization, in chronological order */\n\tmessages: AgentMessage[];\n\t/** File operations extracted from tool calls */\n\tfileOps: FileOperations;\n\t/** Total estimated tokens in messages */\n\ttotalTokens: number;\n}\n\nexport interface CollectEntriesResult {\n\t/** Entries to summarize, in chronological order */\n\tentries: SessionEntry[];\n\t/** Common ancestor between old and new position, if any */\n\tcommonAncestorId: string | null;\n}\n\nexport interface GenerateBranchSummaryOptions {\n\t/** Model to use for summarization */\n\tmodel: Model<any>;\n\t/** API key for the model */\n\tapiKey: string;\n\t/** Request headers for the model */\n\theaders?: Record<string, string>;\n\t/** Abort signal for cancellation */\n\tsignal: AbortSignal;\n\t/** Optional custom instructions for summarization */\n\tcustomInstructions?: string;\n\t/** If true, customInstructions replaces the default prompt instead of being appended */\n\treplaceInstructions?: boolean;\n\t/** Tokens reserved for prompt + LLM response (default 16384) */\n\treserveTokens?: number;\n\t/** Optional wrapped stream function (watchdog/retry-capable host path). */\n\tstreamFn?: StreamFn;\n}\n\n// ============================================================================\n// Entry Collection\n// ============================================================================\n\n/**\n * Collect entries that should be summarized when navigating from one position to another.\n *\n * Walks from oldLeafId back to the common ancestor with targetId, collecting entries\n * along the way. Does NOT stop at compaction boundaries - those are included and their\n * summaries become context.\n *\n * @param session - Session manager (read-only access)\n * @param oldLeafId - Current position (where we're navigating from)\n * @param targetId - Target position (where we're navigating to)\n * @returns Entries to summarize and the common ancestor\n */\nexport function collectEntriesForBranchSummary(\n\tsession: ReadonlySessionManager,\n\toldLeafId: string | null,\n\ttargetId: string,\n): CollectEntriesResult {\n\t// If no old position, nothing to summarize\n\tif (!oldLeafId) {\n\t\treturn { entries: [], commonAncestorId: null };\n\t}\n\n\t// Find common ancestor (deepest node that's on both paths)\n\tconst oldPath = new Set(session.getBranch(oldLeafId).map((e) => e.id));\n\tconst targetPath = session.getBranch(targetId);\n\n\t// targetPath is root-first, so iterate backwards to find deepest common ancestor\n\tlet commonAncestorId: string | null = null;\n\tfor (let i = targetPath.length - 1; i >= 0; i--) {\n\t\tif (oldPath.has(targetPath[i].id)) {\n\t\t\tcommonAncestorId = targetPath[i].id;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// Collect entries from old leaf back to common ancestor\n\tconst entries: SessionEntry[] = [];\n\tlet current: string | null = oldLeafId;\n\n\twhile (current && current !== commonAncestorId) {\n\t\tconst entry = session.getEntry(current);\n\t\tif (!entry) break;\n\t\tentries.push(entry);\n\t\tcurrent = entry.parentId;\n\t}\n\n\t// Reverse to get chronological order\n\tentries.reverse();\n\n\treturn { entries, commonAncestorId };\n}\n\n// ============================================================================\n// Entry to Message Conversion\n// ============================================================================\n\n/**\n * Extract AgentMessage from a session entry.\n * Similar to getMessageFromEntry in compaction.ts but also handles compaction entries.\n */\nfunction getMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tswitch (entry.type) {\n\t\tcase \"message\":\n\t\t\t// Skip tool results - context is in assistant's tool call\n\t\t\tif (entry.message.role === \"toolResult\") return undefined;\n\t\t\treturn entry.message;\n\n\t\tcase \"custom_message\":\n\t\t\treturn createCustomMessage(entry.customType, entry.content, entry.display, entry.details, entry.timestamp);\n\n\t\tcase \"branch_summary\":\n\t\t\treturn createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);\n\n\t\tcase \"compaction\":\n\t\t\treturn createCompactionSummaryMessage(entry.summary, entry.tokensBefore, entry.timestamp);\n\n\t\t// These don't contribute to conversation content\n\t\tcase \"thinking_level_change\":\n\t\tcase \"model_change\":\n\t\tcase \"custom\":\n\t\tcase \"label\":\n\t\tcase \"session_info\":\n\t\t\treturn undefined;\n\t}\n}\n\n/**\n * Prepare entries for summarization with token budget.\n *\n * Walks entries from NEWEST to OLDEST, adding messages until we hit the token budget.\n * This ensures we keep the most recent context when the branch is too long.\n *\n * Also collects file operations from:\n * - Tool calls in assistant messages\n * - Existing branch_summary entries' details (for cumulative tracking)\n *\n * @param entries - Entries in chronological order\n * @param tokenBudget - Maximum tokens to include (0 = no limit)\n */\nexport function prepareBranchEntries(entries: SessionEntry[], tokenBudget: number = 0): BranchPreparation {\n\tconst messages: AgentMessage[] = [];\n\tconst fileOps = createFileOps();\n\tlet totalTokens = 0;\n\n\t// First pass: collect file ops from ALL entries (even if they don't fit in token budget)\n\t// This ensures we capture cumulative file tracking from nested branch summaries\n\t// Only extract from pi-generated summaries (fromHook !== true), not extension-generated ones\n\tfor (const entry of entries) {\n\t\tif (entry.type === \"branch_summary\" && !entry.fromHook && entry.details) {\n\t\t\tconst details = entry.details as BranchSummaryDetails;\n\t\t\tif (Array.isArray(details.readFiles)) {\n\t\t\t\tfor (const f of details.readFiles) fileOps.read.add(f);\n\t\t\t}\n\t\t\tif (Array.isArray(details.modifiedFiles)) {\n\t\t\t\t// Modified files go into both edited and written for proper deduplication\n\t\t\t\tfor (const f of details.modifiedFiles) {\n\t\t\t\t\tfileOps.edited.add(f);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Second pass: walk from newest to oldest, adding messages until token budget\n\tfor (let i = entries.length - 1; i >= 0; i--) {\n\t\tconst entry = entries[i];\n\t\tconst message = getMessageFromEntry(entry);\n\t\tif (!message) continue;\n\n\t\t// Extract file ops from assistant messages (tool calls)\n\t\textractFileOpsFromMessage(message, fileOps);\n\n\t\tconst tokens = estimateTokens(message);\n\n\t\t// Check budget before adding\n\t\tif (tokenBudget > 0 && totalTokens + tokens > tokenBudget) {\n\t\t\t// If this is a summary entry, try to fit it anyway as it's important context\n\t\t\tif (entry.type === \"compaction\" || entry.type === \"branch_summary\") {\n\t\t\t\tif (totalTokens < tokenBudget * 0.9) {\n\t\t\t\t\tmessages.unshift(message);\n\t\t\t\t\ttotalTokens += tokens;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Stop - we've hit the budget\n\t\t\tbreak;\n\t\t}\n\n\t\tmessages.unshift(message);\n\t\ttotalTokens += tokens;\n\t}\n\n\treturn { messages, fileOps, totalTokens };\n}\n\n// ============================================================================\n// Summary Generation\n// ============================================================================\n\nconst BRANCH_SUMMARY_PREAMBLE = `The user explored a different conversation branch before returning here.\nSummary of that exploration:\n\n`;\n\nconst BRANCH_SUMMARY_PROMPT = `Create a structured summary of this conversation branch for context when returning later.\n\nUse this EXACT format:\n\n## Goal\n[What was the user trying to accomplish in this branch?]\n\n## Constraints & Preferences\n- [Any constraints, preferences, or requirements mentioned]\n- [Or \"(none)\" if none were mentioned]\n\n## Progress\n### Done\n- [x] [Completed tasks/changes]\n\n### In Progress\n- [ ] [Work that was started but not finished]\n\n### Blocked\n- [Issues preventing progress, if any]\n\n## Key Decisions\n- **[Decision]**: [Brief rationale]\n\n## Next Steps\n1. [What should happen next to continue this work]\n\nKeep each section concise. Preserve exact file paths, function names, and error messages.`;\n\n/**\n * Generate a summary of abandoned branch entries.\n *\n * @param entries - Session entries to summarize (chronological order)\n * @param options - Generation options\n */\nasync function completeBranchSummary(\n\tmodel: Model<any>,\n\tcontext: Context,\n\toptions: SimpleStreamOptions,\n\tstreamFn?: StreamFn,\n): Promise<AssistantMessage> {\n\tif (!streamFn) return completeSimple(model, context, options);\n\tconst stream = await streamFn(model, context, options);\n\treturn stream.result();\n}\n\nexport async function generateBranchSummary(\n\tentries: SessionEntry[],\n\toptions: GenerateBranchSummaryOptions,\n): Promise<BranchSummaryResult> {\n\tconst {\n\t\tmodel,\n\t\tapiKey,\n\t\theaders,\n\t\tsignal,\n\t\tcustomInstructions,\n\t\treplaceInstructions,\n\t\treserveTokens = 16384,\n\t\tstreamFn,\n\t} = options;\n\n\t// Token budget = context window minus reserved space for prompt + response\n\tconst contextWindow = model.contextWindow || 128000;\n\tconst tokenBudget = contextWindow - reserveTokens;\n\n\tconst { messages, fileOps } = prepareBranchEntries(entries, tokenBudget);\n\n\tif (messages.length === 0) {\n\t\treturn { summary: \"No content to summarize\" };\n\t}\n\n\t// Transform to LLM-compatible messages, then serialize to text\n\t// Serialization prevents the model from treating it as a conversation to continue\n\tconst llmMessages = convertToLlm(messages);\n\tconst conversationText = serializeConversation(llmMessages);\n\n\t// Build prompt\n\tlet instructions: string;\n\tif (replaceInstructions && customInstructions) {\n\t\tinstructions = customInstructions;\n\t} else if (customInstructions) {\n\t\tinstructions = `${BRANCH_SUMMARY_PROMPT}\\n\\nAdditional focus: ${customInstructions}`;\n\t} else {\n\t\tinstructions = BRANCH_SUMMARY_PROMPT;\n\t}\n\tconst promptText = `<conversation>\\n${conversationText}\\n</conversation>\\n\\n${instructions}`;\n\n\tconst summarizationMessages = [\n\t\t{\n\t\t\trole: \"user\" as const,\n\t\t\tcontent: [{ type: \"text\" as const, text: promptText }],\n\t\t\ttimestamp: Date.now(),\n\t\t},\n\t];\n\n\t// Call LLM for summarization. Retry transient provider/watchdog failures so branch summaries\n\t// use the same reliability doctrine as compaction instead of bypassing the host stream wrapper.\n\tlet response: AssistantMessage | undefined;\n\tfor (let attempt = 0; attempt < 3; attempt++) {\n\t\tresponse = await completeBranchSummary(\n\t\t\tmodel,\n\t\t\t{ systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, messages: summarizationMessages },\n\t\t\t{ apiKey, headers, signal, maxTokens: 2048 },\n\t\t\tstreamFn,\n\t\t);\n\t\tif (response.stopReason !== \"error\") break;\n\t\tconst classified = classifyFailure({ message: response.errorMessage ?? \"\", provider: response.provider });\n\t\tif (!classified.retryable || signal.aborted) break;\n\t}\n\tif (!response) return { error: \"Summarization failed\" };\n\n\t// Check if aborted or errored\n\tif (response.stopReason === \"aborted\") {\n\t\treturn { aborted: true };\n\t}\n\tif (response.stopReason === \"error\") {\n\t\treturn { error: response.errorMessage || \"Summarization failed\" };\n\t}\n\n\tlet summary = response.content\n\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t.map((c) => c.text)\n\t\t.join(\"\\n\");\n\n\t// Prepend preamble to provide context about the branch summary\n\tsummary = BRANCH_SUMMARY_PREAMBLE + summary;\n\n\t// Compute file lists and append to summary\n\tconst { readFiles, modifiedFiles } = computeFileLists(fileOps);\n\tsummary += formatFileOperations(readFiles, modifiedFiles);\n\n\treturn {\n\t\tsummary: summary || \"No summary generated\",\n\t\treadFiles,\n\t\tmodifiedFiles,\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"branch-summarization.js","sourceRoot":"","sources":["../../src/compaction/branch-summarization.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,EACN,YAAY,EACZ,0BAA0B,EAC1B,8BAA8B,EAC9B,mBAAmB,GACnB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,eAAe,EAAE,MAAM,8BAA8B,CAAC;AAG/D,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EACN,gBAAgB,EAChB,aAAa,EACb,yBAAyB,EAEzB,oBAAoB,EACpB,2BAA2B,EAC3B,qBAAqB,GACrB,MAAM,YAAY,CAAC;AAyDpB,+EAA+E;AAC/E,mBAAmB;AACnB,+EAA+E;AAE/E;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,8BAA8B,CAC7C,OAA+B,EAC/B,SAAwB,EACxB,QAAgB,EACO;IACvB,2CAA2C;IAC3C,IAAI,CAAC,SAAS,EAAE,CAAC;QAChB,OAAO,EAAE,OAAO,EAAE,EAAE,EAAE,gBAAgB,EAAE,IAAI,EAAE,CAAC;IAChD,CAAC;IAED,2DAA2D;IAC3D,MAAM,OAAO,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;IACvE,MAAM,UAAU,GAAG,OAAO,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;IAE/C,iFAA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AU,KAAK,SAAS,EAAE,CAAC;QACvC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC1B,CAAC;IACD,IAAI,QAAQ,CAAC,UAAU,KAAK,OAAO,EAAE,CAAC;QACrC,OAAO,EAAE,KAAK,EAAE,QAAQ,CAAC,YAAY,IAAI,sBAAsB,EAAE,CAAC;IACnE,CAAC;IAED,IAAI,OAAO,GAAG,QAAQ,CAAC,OAAO;SAC5B,MAAM,CAAC,CAAC,CAAC,EAAuC,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC;SACrE,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;SAClB,IAAI,CAAC,IAAI,CAAC,CAAC;IAEb,+DAA+D;IAC/D,OAAO,GAAG,uBAAuB,GAAG,OAAO,CAAC;IAE5C,2CAA2C;IAC3C,MAAM,EAAE,SAAS,EAAE,aAAa,EAAE,GAAG,gBAAgB,CAAC,OAAO,CAAC,CAAC;IAC/D,OAAO,IAAI,oBAAoB,CAAC,SAAS,EAAE,aAAa,CAAC,CAAC;IAE1D,OAAO;QACN,OAAO,EAAE,OAAO,IAAI,sBAAsB;QAC1C,SAAS;QACT,aAAa;KACb,CAAC;AAAA,CACF","sourcesContent":["/**\n * Branch summarization for tree navigation.\n *\n * When navigating to a different point in the session tree, this generates\n * a summary of the branch being left so context isn't lost.\n */\n\nimport type { AssistantMessage, Context, Model, SimpleStreamOptions } from \"@caupulican/pi-ai\";\nimport { completeSimple } from \"@caupulican/pi-ai\";\nimport {\n\tconvertToLlm,\n\tcreateBranchSummaryMessage,\n\tcreateCompactionSummaryMessage,\n\tcreateCustomMessage,\n} from \"../messages.ts\";\nimport { classifyFailure } from \"../reliability/classifier.ts\";\nimport type { ReadonlySessionManager, SessionEntry } from \"../session/session-manager.ts\";\nimport type { AgentMessage, StreamFn } from \"../types.ts\";\nimport { estimateTokens } from \"./compaction.ts\";\nimport {\n\tcomputeFileLists,\n\tcreateFileOps,\n\textractFileOpsFromMessage,\n\ttype FileOperations,\n\tformatFileOperations,\n\tSUMMARIZATION_SYSTEM_PROMPT,\n\tserializeConversation,\n} from \"./utils.ts\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface BranchSummaryResult {\n\tsummary?: string;\n\treadFiles?: string[];\n\tmodifiedFiles?: string[];\n\taborted?: boolean;\n\terror?: string;\n}\n\n/** Details stored in BranchSummaryEntry.details for file tracking */\nexport interface BranchSummaryDetails {\n\treadFiles: string[];\n\tmodifiedFiles: string[];\n}\n\nexport type { FileOperations } from \"./utils.ts\";\n\nexport interface BranchPreparation {\n\t/** Messages extracted for summarization, in chronological order */\n\tmessages: AgentMessage[];\n\t/** File operations extracted from tool calls */\n\tfileOps: FileOperations;\n\t/** Total estimated tokens in messages */\n\ttotalTokens: number;\n}\n\nexport interface CollectEntriesResult {\n\t/** Entries to summarize, in chronological order */\n\tentries: SessionEntry[];\n\t/** Common ancestor between old and new position, if any */\n\tcommonAncestorId: string | null;\n}\n\nexport interface GenerateBranchSummaryOptions {\n\t/** Model to use for summarization */\n\tmodel: Model<any>;\n\t/** API key for the model */\n\tapiKey: string;\n\t/** Request headers for the model */\n\theaders?: Record<string, string>;\n\t/** Abort signal for cancellation */\n\tsignal: AbortSignal;\n\t/** Optional custom instructions for summarization */\n\tcustomInstructions?: string;\n\t/** If true, customInstructions replaces the default prompt instead of being appended */\n\treplaceInstructions?: boolean;\n\t/** Tokens reserved for prompt + LLM response (default 16384) */\n\treserveTokens?: number;\n\t/** Optional wrapped stream function (watchdog/retry-capable host path). */\n\tstreamFn?: StreamFn;\n}\n\n// ============================================================================\n// Entry Collection\n// ============================================================================\n\n/**\n * Collect entries that should be summarized when navigating from one position to another.\n *\n * Walks from oldLeafId back to the common ancestor with targetId, collecting entries\n * along the way. Does NOT stop at compaction boundaries - those are included and their\n * summaries become context.\n *\n * @param session - Session manager (read-only access)\n * @param oldLeafId - Current position (where we're navigating from)\n * @param targetId - Target position (where we're navigating to)\n * @returns Entries to summarize and the common ancestor\n */\nexport function collectEntriesForBranchSummary(\n\tsession: ReadonlySessionManager,\n\toldLeafId: string | null,\n\ttargetId: string,\n): CollectEntriesResult {\n\t// If no old position, nothing to summarize\n\tif (!oldLeafId) {\n\t\treturn { entries: [], commonAncestorId: null };\n\t}\n\n\t// Find common ancestor (deepest node that's on both paths)\n\tconst oldPath = new Set(session.getBranch(oldLeafId).map((e) => e.id));\n\tconst targetPath = session.getBranch(targetId);\n\n\t// targetPath is root-first, so iterate backwards to find deepest common ancestor\n\tlet commonAncestorId: string | null = null;\n\tfor (let i = targetPath.length - 1; i >= 0; i--) {\n\t\tif (oldPath.has(targetPath[i].id)) {\n\t\t\tcommonAncestorId = targetPath[i].id;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// Collect entries from old leaf back to common ancestor\n\tconst entries: SessionEntry[] = [];\n\tlet current: string | null = oldLeafId;\n\n\twhile (current && current !== commonAncestorId) {\n\t\tconst entry = session.getEntry(current);\n\t\tif (!entry) break;\n\t\tentries.push(entry);\n\t\tcurrent = entry.parentId;\n\t}\n\n\t// Reverse to get chronological order\n\tentries.reverse();\n\n\treturn { entries, commonAncestorId };\n}\n\n// ============================================================================\n// Entry to Message Conversion\n// ============================================================================\n\n/**\n * Extract AgentMessage from a session entry.\n * Similar to getMessageFromEntry in compaction.ts but also handles compaction entries.\n */\nfunction getMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tswitch (entry.type) {\n\t\tcase \"message\":\n\t\t\t// Skip tool results - context is in assistant's tool call\n\t\t\tif (entry.message.role === \"toolResult\") return undefined;\n\t\t\treturn entry.message;\n\n\t\tcase \"custom_message\":\n\t\t\treturn createCustomMessage(entry.customType, entry.content, entry.display, entry.details, entry.timestamp);\n\n\t\tcase \"branch_summary\":\n\t\t\treturn createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);\n\n\t\tcase \"compaction\":\n\t\t\treturn createCompactionSummaryMessage(entry.summary, entry.tokensBefore, entry.timestamp);\n\n\t\t// These don't contribute to conversation content\n\t\tcase \"thinking_level_change\":\n\t\tcase \"model_change\":\n\t\tcase \"custom\":\n\t\tcase \"label\":\n\t\tcase \"session_info\":\n\t\t\treturn undefined;\n\t}\n}\n\n/**\n * Prepare entries for summarization with token budget.\n *\n * Walks entries from NEWEST to OLDEST, adding messages until we hit the token budget.\n * This ensures we keep the most recent context when the branch is too long.\n *\n * Also collects file operations from:\n * - Tool calls in assistant messages\n * - Existing branch_summary entries' details (for cumulative tracking)\n *\n * @param entries - Entries in chronological order\n * @param tokenBudget - Maximum tokens to include (0 = no limit)\n */\nexport function prepareBranchEntries(entries: SessionEntry[], tokenBudget: number = 0): BranchPreparation {\n\tconst messages: AgentMessage[] = [];\n\tconst fileOps = createFileOps();\n\tlet totalTokens = 0;\n\n\t// First pass: collect file ops from ALL entries (even if they don't fit in token budget)\n\t// This ensures we capture cumulative file tracking from nested branch summaries\n\t// Only extract from pi-generated summaries (fromHook !== true), not extension-generated ones\n\tfor (const entry of entries) {\n\t\tif (entry.type === \"branch_summary\" && !entry.fromHook && entry.details) {\n\t\t\tconst details = entry.details as BranchSummaryDetails;\n\t\t\tif (Array.isArray(details.readFiles)) {\n\t\t\t\tfor (const f of details.readFiles) fileOps.read.add(f);\n\t\t\t}\n\t\t\tif (Array.isArray(details.modifiedFiles)) {\n\t\t\t\t// Modified files go into both edited and written for proper deduplication\n\t\t\t\tfor (const f of details.modifiedFiles) {\n\t\t\t\t\tfileOps.edited.add(f);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Second pass: walk from newest to oldest, adding messages until token budget.\n\t// Append in reverse chronology and reverse once so large branches stay linear.\n\tfor (let i = entries.length - 1; i >= 0; i--) {\n\t\tconst entry = entries[i];\n\t\tconst message = getMessageFromEntry(entry);\n\t\tif (!message) continue;\n\n\t\t// Extract file ops from assistant messages (tool calls)\n\t\textractFileOpsFromMessage(message, fileOps);\n\n\t\tconst tokens = estimateTokens(message);\n\n\t\t// Check budget before adding\n\t\tif (tokenBudget > 0 && totalTokens + tokens > tokenBudget) {\n\t\t\t// If this is a summary entry, try to fit it anyway as it's important context\n\t\t\tif (entry.type === \"compaction\" || entry.type === \"branch_summary\") {\n\t\t\t\tif (totalTokens < tokenBudget * 0.9) {\n\t\t\t\t\tmessages.push(message);\n\t\t\t\t\ttotalTokens += tokens;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Stop - we've hit the budget\n\t\t\tbreak;\n\t\t}\n\n\t\tmessages.push(message);\n\t\ttotalTokens += tokens;\n\t}\n\n\tmessages.reverse();\n\treturn { messages, fileOps, totalTokens };\n}\n\n// ============================================================================\n// Summary Generation\n// ============================================================================\n\nconst BRANCH_SUMMARY_PREAMBLE = `The user explored a different conversation branch before returning here.\nSummary of that exploration:\n\n`;\n\nconst BRANCH_SUMMARY_PROMPT = `Create a structured summary of this conversation branch for context when returning later.\n\nUse this EXACT format:\n\n## Goal\n[What was the user trying to accomplish in this branch?]\n\n## Constraints & Preferences\n- [Any constraints, preferences, or requirements mentioned]\n- [Or \"(none)\" if none were mentioned]\n\n## Progress\n### Done\n- [x] [Completed tasks/changes]\n\n### In Progress\n- [ ] [Work that was started but not finished]\n\n### Blocked\n- [Issues preventing progress, if any]\n\n## Key Decisions\n- **[Decision]**: [Brief rationale]\n\n## Next Steps\n1. [What should happen next to continue this work]\n\nKeep each section concise. Preserve exact file paths, function names, and error messages.`;\n\n/**\n * Generate a summary of abandoned branch entries.\n *\n * @param entries - Session entries to summarize (chronological order)\n * @param options - Generation options\n */\nasync function completeBranchSummary(\n\tmodel: Model<any>,\n\tcontext: Context,\n\toptions: SimpleStreamOptions,\n\tstreamFn?: StreamFn,\n): Promise<AssistantMessage> {\n\tif (!streamFn) return completeSimple(model, context, options);\n\tconst stream = await streamFn(model, context, options);\n\treturn stream.result();\n}\n\nexport async function generateBranchSummary(\n\tentries: SessionEntry[],\n\toptions: GenerateBranchSummaryOptions,\n): Promise<BranchSummaryResult> {\n\tconst {\n\t\tmodel,\n\t\tapiKey,\n\t\theaders,\n\t\tsignal,\n\t\tcustomInstructions,\n\t\treplaceInstructions,\n\t\treserveTokens = 16384,\n\t\tstreamFn,\n\t} = options;\n\n\t// Token budget = context window minus reserved space for prompt + response\n\tconst contextWindow = model.contextWindow || 128000;\n\tconst tokenBudget = contextWindow - reserveTokens;\n\n\tconst { messages, fileOps } = prepareBranchEntries(entries, tokenBudget);\n\n\tif (messages.length === 0) {\n\t\treturn { summary: \"No content to summarize\" };\n\t}\n\n\t// Transform to LLM-compatible messages, then serialize to text\n\t// Serialization prevents the model from treating it as a conversation to continue\n\tconst llmMessages = convertToLlm(messages);\n\tconst conversationText = serializeConversation(llmMessages);\n\n\t// Build prompt\n\tlet instructions: string;\n\tif (replaceInstructions && customInstructions) {\n\t\tinstructions = customInstructions;\n\t} else if (customInstructions) {\n\t\tinstructions = `${BRANCH_SUMMARY_PROMPT}\\n\\nAdditional focus: ${customInstructions}`;\n\t} else {\n\t\tinstructions = BRANCH_SUMMARY_PROMPT;\n\t}\n\tconst promptText = `<conversation>\\n${conversationText}\\n</conversation>\\n\\n${instructions}`;\n\n\tconst summarizationMessages = [\n\t\t{\n\t\t\trole: \"user\" as const,\n\t\t\tcontent: [{ type: \"text\" as const, text: promptText }],\n\t\t\ttimestamp: Date.now(),\n\t\t},\n\t];\n\n\t// Call LLM for summarization. Retry transient provider/watchdog failures so branch summaries\n\t// use the same reliability doctrine as compaction instead of bypassing the host stream wrapper.\n\tlet response: AssistantMessage | undefined;\n\tfor (let attempt = 0; attempt < 3; attempt++) {\n\t\tresponse = await completeBranchSummary(\n\t\t\tmodel,\n\t\t\t{ systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, messages: summarizationMessages },\n\t\t\t{ apiKey, headers, signal, maxTokens: 2048 },\n\t\t\tstreamFn,\n\t\t);\n\t\tif (response.stopReason !== \"error\") break;\n\t\tconst classified = classifyFailure({ message: response.errorMessage ?? \"\", provider: response.provider });\n\t\tif (!classified.retryable || signal.aborted) break;\n\t}\n\tif (!response) return { error: \"Summarization failed\" };\n\n\t// Check if aborted or errored\n\tif (response.stopReason === \"aborted\") {\n\t\treturn { aborted: true };\n\t}\n\tif (response.stopReason === \"error\") {\n\t\treturn { error: response.errorMessage || \"Summarization failed\" };\n\t}\n\n\tlet summary = response.content\n\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t.map((c) => c.text)\n\t\t.join(\"\\n\");\n\n\t// Prepend preamble to provide context about the branch summary\n\tsummary = BRANCH_SUMMARY_PREAMBLE + summary;\n\n\t// Compute file lists and append to summary\n\tconst { readFiles, modifiedFiles } = computeFileLists(fileOps);\n\tsummary += formatFileOperations(readFiles, modifiedFiles);\n\n\treturn {\n\t\tsummary: summary || \"No summary generated\",\n\t\treadFiles,\n\t\tmodifiedFiles,\n\t};\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"extraction.d.ts","sourceRoot":"","sources":["../../src/compaction/extraction.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAGlE,MAAM,WAAW,kBAAkB;IAClC,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,UAAU,GAAG,SAAS,GAAG,MAAM,CAAC;IACtC,IAAI,EAAE,MAAM,CAAC;CACb;AAED,MAAM,WAAW,mBAAmB;IACnC,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,6BAA6B;IAC7C,sGAAsG;IACtG,KAAK,EAAE,WAAW,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,eAAe;IAC/B,KAAK,EAAE,kBAAkB,EAAE,CAAC;IAC5B,UAAU,EAAE,kBAAkB,EAAE,CAAC;IACjC,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,UAAU,EAAE,mBAAmB,EAAE,CAAC;IAClC,YAAY,EAAE,MAAM,EAAE,CAAC;IACvB,aAAa,EAAE,MAAM,CAAC;IACtB,gBAAgB,EAAE,MAAM,CAAC;IACzB,+EAA+E;IAC/E,oBAAoB,CAAC,EAAE,6BAA6B,EAAE,CAAC;CACvD;AAiCD,2GAA2G;AAC3G,eAAO,MAAM,4BAA4B,OAAQ,CAAC;AAmRlD,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,YAAY,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,eAAe,CAsP3G;AAgBD,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,eAAe,GAAG,MAAM,CAsC/D","sourcesContent":["import type { SessionEntry } from \"../session/session-manager.ts\";\nimport type { AgentMessage } from \"../types.ts\";\n\nexport interface CompactionFileFact {\n\tpath: string;\n\tkind: \"modified\" | \"created\" | \"read\";\n\tnote: string;\n}\n\nexport interface CompactionErrorFact {\n\toperation: string;\n\terror: string;\n}\n\nexport interface CompactionDelegatedWorkerFact {\n\t/** Worker-authored text is evidence for the parent, never a verified decision or completion claim. */\n\ttrust: \"UNTRUSTED\";\n\ttask: string;\n\tsummary: string;\n}\n\nexport interface CompactionFacts {\n\tfiles: CompactionFileFact[];\n\tworkingSet: CompactionFileFact[];\n\tactions: string[];\n\terrorFacts: CompactionErrorFact[];\n\tprohibitions: string[];\n\tcancelledText: string;\n\tactiveTaskSource: string;\n\t/** Latest-first worker evidence retained only by deterministic checkpoints. */\n\tdelegatedWorkerFacts?: CompactionDelegatedWorkerFact[];\n}\n\ninterface ToolCallFact {\n\tid: string | undefined;\n\tname: string;\n\tpath: string | undefined;\n\tbaseKind: \"modified\" | \"created\" | \"read\" | null;\n\tfinalKind: \"modified\" | \"created\" | \"read\" | null;\n\tverb: string;\n\tresolved: boolean;\n\tfailed: boolean;\n}\n\nconst PROHIBITION_PATTERN = /\\b(do not|don't|never|stop (?:doing|using|changing)|no more)\\b/i;\n// Deliberately narrow: a bare \"stop\" (\"stop the server and rerun\") is everyday phrasing, not a\n// reversal of the prior work — matching it marked whole turns cancelled and made the\n// cancelled-work gate fight the recall gates (2026-07-06 incident).\nconst REVERSAL_PATTERN =\n\t/\\b(undo|revert|roll back|never mind|scrap that|forget (?:it|that)|stop (?:that|this|it|everything|working on))\\b/i;\n\n/** User messages longer than this are documents/pastes, not spoken prohibitions. */\nconst PROHIBITION_SOURCE_MAX_CHARS = 1_500;\n/** Upper bound on gate-demanded rules; most recent win (same bounding rationale as Done carry-over). */\nconst MAX_PROHIBITIONS = 8;\n/** Upper bound on gate-demanded actions; mirrors the prompt's \"15 most recent Done items\" rule. */\nconst MAX_ACTIONS = 15;\nconst MAX_WORKING_SET_FILES = 8;\nconst MAX_ERROR_FACTS = 5;\nconst ERROR_LINE_MAX_CHARS = 160;\nconst COMMAND_PREFIX_MAX_CHARS = 80;\nconst MAX_DELEGATED_WORKER_FACTS = 4;\nconst DELEGATED_WORKER_TASK_MAX_CHARS = 240;\nconst DELEGATED_WORKER_SUMMARY_MAX_CHARS = 600;\n/** Shared clamp for the active-task text because verification can only demand what the prompt receives. */\nexport const ACTIVE_TASK_SOURCE_MAX_CHARS = 4_000;\n\nconst FILE_KIND_PRIORITY: Record<NonNullable<ToolCallFact[\"finalKind\"]>, number> = {\n\tread: 1,\n\tcreated: 2,\n\tmodified: 3,\n};\n\nconst TOOL_KIND_BY_NAME: Record<string, \"modified\" | \"created\" | \"read\" | null> = {\n\tread: \"read\",\n\tgrep: \"read\",\n\tfind: \"read\",\n\twrite: \"modified\",\n\tedit: \"modified\",\n\tbash: null,\n};\n\nconst TOOL_VERB_BY_NAME: Record<string, string> = {\n\twrite: \"WRITE\",\n\tedit: \"EDIT\",\n\tbash: \"RUN\",\n\tread: \"READ\",\n\tgrep: \"READ\",\n\tfind: \"READ\",\n};\n\nfunction messageToText(message: AgentMessage): string {\n\tconst rawContent = (message as { content?: unknown }).content;\n\tif (typeof rawContent === \"string\") {\n\t\treturn rawContent;\n\t}\n\tif (!Array.isArray(rawContent)) {\n\t\treturn \"\";\n\t}\n\n\tconst parts: string[] = [];\n\tfor (const block of rawContent) {\n\t\tif (!block || typeof block !== \"object\") {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif ((block as { type?: unknown }).type === \"text\" && typeof (block as { text?: unknown }).text === \"string\") {\n\t\t\tparts.push((block as { text: string }).text);\n\t\t}\n\t}\n\treturn parts.join(\" \").trim();\n}\n\nfunction assistantToolCallTarget(name: string, rawArgs: unknown): string | undefined {\n\tif (!rawArgs || typeof rawArgs !== \"object\") {\n\t\treturn undefined;\n\t}\n\tconst args = rawArgs as Record<string, unknown>;\n\n\tif (\n\t\t(name === \"read\" || name === \"grep\" || name === \"find\" || name === \"write\" || name === \"edit\") &&\n\t\ttypeof args.path === \"string\" &&\n\t\targs.path.length > 0\n\t) {\n\t\treturn args.path;\n\t}\n\n\tif (name === \"bash\" && typeof args.command === \"string\" && args.command.length > 0) {\n\t\treturn args.command;\n\t}\n\n\treturn undefined;\n}\n\nfunction clampText(text: string, maxLen: number): string {\n\treturn text.length > maxLen ? text.slice(0, maxLen) : text;\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\nfunction normalizeDelegatedWorkerText(text: string, maxLen: number): string {\n\treturn clampText(text.replace(/\\s+/g, \" \").trim(), maxLen);\n}\n\nfunction extractDelegatedWorkerFact(entry: SessionEntry): CompactionDelegatedWorkerFact | undefined {\n\tif (entry.type !== \"custom\" || entry.customType !== \"worker_result\" || !isPlainRecord(entry.data)) {\n\t\treturn undefined;\n\t}\n\tif (entry.data.version !== 1 || !isPlainRecord(entry.data.result)) return undefined;\n\n\tconst result = entry.data.result;\n\tif (typeof result.requestId !== \"string\" || typeof result.summary !== \"string\") return undefined;\n\tif (typeof result.status !== \"string\" || ![\"completed\", \"blocked\", \"failed\", \"cancelled\"].includes(result.status)) {\n\t\treturn undefined;\n\t}\n\tif (!Array.isArray(result.changedFiles) || !result.changedFiles.every((file) => typeof file === \"string\")) {\n\t\treturn undefined;\n\t}\n\n\tconst request = entry.data.request;\n\tconst instructions =\n\t\tisPlainRecord(request) && typeof request.instructions === \"string\" ? request.instructions : undefined;\n\tconst task = normalizeDelegatedWorkerText(\n\t\tinstructions ?? `Worker request ${result.requestId}`,\n\t\tDELEGATED_WORKER_TASK_MAX_CHARS,\n\t);\n\tconst summary = normalizeDelegatedWorkerText(result.summary, DELEGATED_WORKER_SUMMARY_MAX_CHARS);\n\n\treturn {\n\t\ttrust: \"UNTRUSTED\",\n\t\ttask: task || \"(empty task)\",\n\t\tsummary: summary || \"(empty summary)\",\n\t};\n}\n\nfunction extractDelegatedWorkerFacts(\n\tentries: readonly SessionEntry[],\n\tstart: number,\n\tend: number,\n): CompactionDelegatedWorkerFact[] {\n\tconst facts: CompactionDelegatedWorkerFact[] = [];\n\tfor (let i = end - 1; i >= start && facts.length < MAX_DELEGATED_WORKER_FACTS; i--) {\n\t\tconst fact = extractDelegatedWorkerFact(entries[i]);\n\t\tif (fact) facts.push(fact);\n\t}\n\treturn facts;\n}\n\nfunction appearsCreated(message: AgentMessage): boolean {\n\tif (message.role !== \"toolResult\") {\n\t\treturn false;\n\t}\n\n\tconst text = messageToText(message).toLowerCase();\n\tif (/(\\bnew file\\b|\\bcreated\\b|\\bcreated file\\b)/.test(text)) {\n\t\treturn true;\n\t}\n\n\tconst details = (message as { details?: unknown }).details;\n\tif (!details || typeof details !== \"object\") {\n\t\treturn false;\n\t}\n\n\tif (typeof (details as { created?: unknown }).created === \"boolean\") {\n\t\treturn (details as { created: boolean }).created;\n\t}\n\tif (typeof (details as { isCreated?: unknown }).isCreated === \"boolean\") {\n\t\treturn (details as { isCreated: boolean }).isCreated;\n\t}\n\tif (typeof (details as { isNewFile?: unknown }).isNewFile === \"boolean\") {\n\t\treturn (details as { isNewFile: boolean }).isNewFile;\n\t}\n\n\treturn false;\n}\n\nfunction splitSentenceLines(text: string): string[] {\n\treturn text\n\t\t.split(/(?<=[.!?])\\s+|\\n+/)\n\t\t.map((line) => line.trim().replace(/[.!?]+$/, \"\"))\n\t\t.filter(Boolean);\n}\n\nfunction getMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tswitch (entry.type) {\n\t\tcase \"message\":\n\t\t\treturn entry.message;\n\t\tcase \"custom_message\":\n\t\t\treturn {\n\t\t\t\trole: \"custom\",\n\t\t\t\tcustomType: entry.customType,\n\t\t\t\tcontent: entry.content,\n\t\t\t\tdetails: entry.details,\n\t\t\t\tdisplay: entry.display,\n\t\t\t\ttimestamp: new Date(entry.timestamp).getTime(),\n\t\t\t};\n\t\tcase \"branch_summary\":\n\t\t\treturn {\n\t\t\t\trole: \"branchSummary\",\n\t\t\t\tsummary: entry.summary,\n\t\t\t\tfromId: entry.fromId,\n\t\t\t\ttimestamp: new Date(entry.timestamp).getTime(),\n\t\t\t};\n\t\tcase \"compaction\":\n\t\t\treturn undefined;\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\nfunction isToolCallBlock(block: unknown): block is { type: \"toolCall\"; id?: string; name: string; arguments: unknown } {\n\tif (!block || typeof block !== \"object\") {\n\t\treturn false;\n\t}\n\tif ((block as { type?: unknown }).type !== \"toolCall\") {\n\t\treturn false;\n\t}\n\tif (typeof (block as { name?: unknown }).name !== \"string\") {\n\t\treturn false;\n\t}\n\tif (!(block as { arguments?: unknown }).arguments) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nfunction toolCallVerb(name: string): string {\n\treturn TOOL_VERB_BY_NAME[name] ?? name.toUpperCase();\n}\n\nfunction isHarnessPlumbingTarget(target: string | undefined): boolean {\n\tif (!target) return false;\n\treturn (\n\t\ttarget.includes(\"/.pi/agent/context-gc/\") ||\n\t\ttarget.includes(\"~/.pi/agent/context-gc/\") ||\n\t\t/\\/tmp\\/pi-bash-[^\\s]+\\.log\\b/.test(target)\n\t);\n}\n\nfunction normalizeOperationTarget(toolName: string, path: string | undefined): string {\n\tif (!path) return \"(unknown)\";\n\tif (toolName !== \"bash\") return path;\n\treturn clampText(path.replace(/\\s+/g, \" \").trim(), COMMAND_PREFIX_MAX_CHARS);\n}\n\nfunction operationKey(toolName: string, path: string | undefined): string {\n\treturn `${toolName}:${normalizeOperationTarget(toolName, path)}`;\n}\n\nfunction operationLabel(toolName: string, path: string | undefined): string {\n\treturn `${toolCallVerb(toolName)} ${normalizeOperationTarget(toolName, path)}`;\n}\n\nfunction resultExitCode(message: AgentMessage): number | undefined {\n\tconst details = (message as { details?: unknown }).details;\n\tif (!details || typeof details !== \"object\") return undefined;\n\tconst raw = (details as { exitCode?: unknown }).exitCode;\n\tif (typeof raw === \"number\" && Number.isFinite(raw)) return raw;\n\tif (typeof raw === \"string\" && /^\\d+$/.test(raw)) return Number(raw);\n\treturn undefined;\n}\n\nfunction isOutcomeBearingTool(toolName: string | undefined): boolean {\n\treturn toolName === \"bash\";\n}\n\nfunction isOpenProblemTool(toolName: string | undefined): boolean {\n\treturn toolName === \"bash\" || toolName === \"edit\" || toolName === \"write\";\n}\n\nfunction failureSignalLine(text: string): string | undefined {\n\treturn text\n\t\t.split(/\\r?\\n/)\n\t\t.map((part) => part.trim())\n\t\t.find((line) => /exited with code [1-9]\\d*/i.test(line) || /^(error|fatal|✗|FAIL)\\b/i.test(line));\n}\n\nfunction firstErrorLine(text: string): string {\n\tconst line =\n\t\tfailureSignalLine(text) ??\n\t\ttext\n\t\t\t.split(/\\r?\\n/)\n\t\t\t.map((part) => part.trim())\n\t\t\t.find(Boolean);\n\treturn clampText(line ?? \"failed\", ERROR_LINE_MAX_CHARS);\n}\n\nfunction isFailureToolResult(message: AgentMessage, text: string): boolean {\n\tif (message.role !== \"toolResult\") return false;\n\tif ((message as { isError?: unknown }).isError === true) return true;\n\tconst exitCode = resultExitCode(message);\n\tif (exitCode !== undefined) return exitCode !== 0;\n\tconst toolName = (message as { toolName?: unknown }).toolName;\n\treturn typeof toolName === \"string\" && isOutcomeBearingTool(toolName) && failureSignalLine(text) !== undefined;\n}\n\nexport function extractCompactionFacts(entries: SessionEntry[], start: number, end: number): CompactionFacts {\n\tconst rangeStart = Math.max(0, start);\n\tconst rangeEnd = Math.min(entries.length, Math.max(rangeStart, end));\n\n\tif (rangeStart >= rangeEnd) {\n\t\treturn {\n\t\t\tfiles: [],\n\t\t\tworkingSet: [],\n\t\t\tactions: [],\n\t\t\terrorFacts: [],\n\t\t\tprohibitions: [],\n\t\t\tcancelledText: \"\",\n\t\t\tactiveTaskSource: \"\",\n\t\t\tdelegatedWorkerFacts: [],\n\t\t};\n\t}\n\tconst delegatedWorkerFacts = extractDelegatedWorkerFacts(entries, rangeStart, rangeEnd);\n\n\tconst filesByPath = new Map<string, CompactionFileFact & { lastTouch: number }>();\n\tconst filesNotes = new Map<string, string>();\n\tconst seenProhibitions = new Set<string>();\n\tconst actionFacts: ToolCallFact[] = [];\n\tconst pendingById = new Map<string, number[]>();\n\tconst pendingByOrder: number[] = [];\n\n\tconst actions: string[] = [];\n\tconst openErrors = new Map<string, CompactionErrorFact & { lastTouch: number }>();\n\tconst prohibitions: string[] = [];\n\tlet activeTaskSource = \"\";\n\tconst cancelledParts: string[] = [];\n\tconst sinceLastUser: string[] = [];\n\n\tfor (let i = rangeStart; i < rangeEnd; i++) {\n\t\tconst message = getMessageFromEntry(entries[i]);\n\t\tif (!message) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (message.role === \"user\") {\n\t\t\tconst userText = messageToText(message);\n\t\t\tif (REVERSAL_PATTERN.test(userText)) {\n\t\t\t\tcancelledParts.push(...sinceLastUser);\n\t\t\t}\n\t\t\tsinceLastUser.length = 0;\n\n\t\t\tif (userText) {\n\t\t\t\tactiveTaskSource = clampText(userText, ACTIVE_TASK_SOURCE_MAX_CHARS);\n\t\t\t\t// Mandatory Rules exist for SPOKEN durable prohibitions (\"do not touch X\"), not for\n\t\t\t\t// documents. A long pasted text (plan, instruction file) can contain dozens of\n\t\t\t\t// \"never/do not\" lines; harvesting them makes the verification gate demand the\n\t\t\t\t// checkpoint reproduce the document (2026-07-06 field incident: 13 fragment rules\n\t\t\t\t// extracted from one pasted instruction). Documents live on disk; skip them here.\n\t\t\t\tif (userText.length <= PROHIBITION_SOURCE_MAX_CHARS) {\n\t\t\t\t\tfor (const sentence of splitSentenceLines(userText)) {\n\t\t\t\t\t\tif (!PROHIBITION_PATTERN.test(sentence)) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst normalized = clampText(sentence, 160);\n\t\t\t\t\t\tconst dedupeKey = normalized.toLowerCase();\n\t\t\t\t\t\tif (!seenProhibitions.has(dedupeKey)) {\n\t\t\t\t\t\t\tseenProhibitions.add(dedupeKey);\n\t\t\t\t\t\t\tprohibitions.push(normalized);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (message.role === \"assistant\" || message.role === \"toolResult\") {\n\t\t\tconst messageText = messageToText(message);\n\t\t\tif (messageText) {\n\t\t\t\tsinceLastUser.push(messageText);\n\t\t\t}\n\t\t}\n\n\t\tif (message.role === \"assistant\" && Array.isArray(message.content)) {\n\t\t\tfor (const block of message.content) {\n\t\t\t\tif (!isToolCallBlock(block)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst name = block.name;\n\t\t\t\tconst verb = toolCallVerb(name);\n\t\t\t\tconst path = assistantToolCallTarget(name, block.arguments);\n\t\t\t\tconst baseKind = TOOL_KIND_BY_NAME[name] ?? null;\n\t\t\t\tconst fact: ToolCallFact = {\n\t\t\t\t\tid: block.id,\n\t\t\t\t\tname,\n\t\t\t\t\tpath,\n\t\t\t\t\tbaseKind,\n\t\t\t\t\tfinalKind: baseKind,\n\t\t\t\t\tverb,\n\t\t\t\t\tresolved: false,\n\t\t\t\t\tfailed: false,\n\t\t\t\t};\n\t\t\t\tactionFacts.push(fact);\n\t\t\t\tconst index = actionFacts.length - 1;\n\t\t\t\tpendingByOrder.push(index);\n\t\t\t\tif (fact.id) {\n\t\t\t\t\tconst bucket = pendingById.get(fact.id) ?? [];\n\t\t\t\t\tbucket.push(index);\n\t\t\t\t\tpendingById.set(fact.id, bucket);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (message.role === \"toolResult\") {\n\t\t\tconst toolCallId = (message as { toolCallId?: string }).toolCallId;\n\t\t\tconst toolName = (message as { toolName?: string }).toolName;\n\t\t\tlet matchedIndex: number | undefined;\n\n\t\t\tif (toolCallId) {\n\t\t\t\tconst bucket = pendingById.get(toolCallId);\n\t\t\t\tif (bucket && bucket.length > 0) {\n\t\t\t\t\tmatchedIndex = bucket.shift();\n\t\t\t\t\tif (bucket.length === 0) {\n\t\t\t\t\t\tpendingById.delete(toolCallId);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (matchedIndex === undefined && toolName) {\n\t\t\t\tfor (const index of pendingByOrder) {\n\t\t\t\t\tconst candidate = actionFacts[index];\n\t\t\t\t\tif (!candidate.resolved && candidate.name === toolName) {\n\t\t\t\t\t\tmatchedIndex = index;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (matchedIndex !== undefined) {\n\t\t\t\tconst fact = actionFacts[matchedIndex];\n\t\t\t\tconst resultText = messageToText(message);\n\t\t\t\tconst failed = isFailureToolResult(message, resultText);\n\t\t\t\tfact.resolved = true;\n\t\t\t\tfact.failed = failed;\n\t\t\t\tif (!failed && fact.baseKind === \"modified\" && appearsCreated(message)) {\n\t\t\t\t\tfact.finalKind = \"created\";\n\t\t\t\t}\n\n\t\t\t\tif (!failed && fact.path && fact.finalKind && !isHarnessPlumbingTarget(fact.path)) {\n\t\t\t\t\tconst existing = filesByPath.get(fact.path);\n\t\t\t\t\tconst nextKind = fact.finalKind;\n\t\t\t\t\tconst note = fact.verb;\n\t\t\t\t\tif (!existing || FILE_KIND_PRIORITY[nextKind] > FILE_KIND_PRIORITY[existing.kind]) {\n\t\t\t\t\t\tfilesByPath.set(fact.path, { path: fact.path, kind: nextKind, note, lastTouch: i });\n\t\t\t\t\t} else if (existing.kind === nextKind) {\n\t\t\t\t\t\texisting.note = note;\n\t\t\t\t\t\texisting.lastTouch = i;\n\t\t\t\t\t} else {\n\t\t\t\t\t\texisting.lastTouch = i;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst key = operationKey(fact.name, fact.path);\n\t\t\t\tif (failed && isOpenProblemTool(fact.name)) {\n\t\t\t\t\topenErrors.set(key, {\n\t\t\t\t\t\toperation: operationLabel(fact.name, fact.path),\n\t\t\t\t\t\terror: firstErrorLine(resultText),\n\t\t\t\t\t\tlastTouch: i,\n\t\t\t\t\t});\n\t\t\t\t} else if (!failed) {\n\t\t\t\t\topenErrors.delete(key);\n\t\t\t\t}\n\n\t\t\t\tconst pendingPos = pendingByOrder.indexOf(matchedIndex);\n\t\t\t\tif (pendingPos >= 0) {\n\t\t\t\t\tpendingByOrder.splice(pendingPos, 1);\n\t\t\t\t}\n\t\t\t\tif (toolCallId) {\n\t\t\t\t\tconst bucket = pendingById.get(toolCallId);\n\t\t\t\t\tif (bucket) {\n\t\t\t\t\t\tconst pos = bucket.indexOf(matchedIndex);\n\t\t\t\t\t\tif (pos >= 0) {\n\t\t\t\t\t\t\tbucket.splice(pos, 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (bucket.length === 0) {\n\t\t\t\t\t\t\tpendingById.delete(toolCallId);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (const action of actionFacts) {\n\t\tif (isHarnessPlumbingTarget(action.path)) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (action.resolved && action.failed && action.name !== \"bash\") {\n\t\t\tcontinue;\n\t\t}\n\t\tif ((!action.resolved || !action.failed) && action.finalKind && action.path && !filesByPath.has(action.path)) {\n\t\t\tfilesByPath.set(action.path, {\n\t\t\t\tpath: action.path,\n\t\t\t\tkind: action.finalKind,\n\t\t\t\tnote: action.verb,\n\t\t\t\tlastTouch: actionFacts.indexOf(action),\n\t\t\t});\n\t\t}\n\n\t\tactions.push(`${action.verb} ${action.path ?? \"(unknown)\"}`);\n\t}\n\n\tfor (const file of filesByPath.values()) {\n\t\tif (!file.note && filesNotes.has(file.path)) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (file.note && filesNotes.get(file.path) === file.note) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (file.note) {\n\t\t\tfilesNotes.set(file.path, file.note);\n\t\t}\n\t}\n\n\tfor (const file of filesByPath.values()) {\n\t\tconst suffix = filesNotes.get(file.path);\n\t\tif (suffix) {\n\t\t\tfile.note = suffix;\n\t\t}\n\t}\n\n\tconst files = Array.from(filesByPath.values())\n\t\t.sort(\n\t\t\t(a, b) =>\n\t\t\t\tb.lastTouch - a.lastTouch ||\n\t\t\t\tFILE_KIND_PRIORITY[b.kind] - FILE_KIND_PRIORITY[a.kind] ||\n\t\t\t\ta.path.localeCompare(b.path),\n\t\t)\n\t\t.map(({ lastTouch: _lastTouch, ...file }) => file);\n\n\treturn {\n\t\tfiles,\n\t\tworkingSet: files.slice(0, MAX_WORKING_SET_FILES),\n\t\tactions: dedupeMostRecent(actions).slice(-MAX_ACTIONS),\n\t\terrorFacts: Array.from(openErrors.values())\n\t\t\t.sort((a, b) => a.lastTouch - b.lastTouch)\n\t\t\t.slice(-MAX_ERROR_FACTS)\n\t\t\t.map(({ lastTouch: _lastTouch, ...error }) => error),\n\t\tprohibitions: prohibitions.slice(-MAX_PROHIBITIONS),\n\t\tcancelledText: cancelledParts.join(\"\\n\"),\n\t\tactiveTaskSource,\n\t\tdelegatedWorkerFacts,\n\t};\n}\n\nfunction dedupeMostRecent(values: string[]): string[] {\n\tconst seen = new Set<string>();\n\tconst kept: string[] = [];\n\tfor (let i = values.length - 1; i >= 0; i--) {\n\t\tconst value = values[i];\n\t\tif (seen.has(value)) {\n\t\t\tcontinue;\n\t\t}\n\t\tseen.add(value);\n\t\tkept.push(value);\n\t}\n\treturn kept.reverse();\n}\n\nexport function renderFactsBlock(facts: CompactionFacts): string {\n\tconst lines: string[] = [\"verification demands:\"];\n\tlines.push(\"files-modified-recall (must appear in ## Files):\");\n\tfor (const file of facts.files.filter((file) => file.kind !== \"read\")) {\n\t\tlines.push(file.path);\n\t}\n\tlines.push(\"files-read-recall (must appear in ## Files, containment threshold applies):\");\n\tfor (const file of facts.files.filter((file) => file.kind === \"read\")) {\n\t\tlines.push(file.path);\n\t}\n\tlines.push(\"working-set-recall (must appear in ## Working Set):\");\n\tfor (const file of facts.workingSet) {\n\t\tlines.push(`${file.path} — ${file.note || file.kind}`);\n\t}\n\tlines.push(\"open-errors-recall (must appear in ## Open Problems):\");\n\tfor (const error of facts.errorFacts) {\n\t\tlines.push(`${error.operation}: ${error.error}`);\n\t}\n\tlines.push(\"actions-recall (must appear in ## Done):\");\n\tfor (const action of facts.actions) {\n\t\tlines.push(action);\n\t}\n\tlines.push(\"mandatory-rules-recall (must appear in ### Mandatory Rules):\");\n\tfor (const prohibition of facts.prohibitions) {\n\t\tlines.push(prohibition);\n\t}\n\t// The active-task gate demands near-verbatim recall of this text, but the conversation the\n\t// summarizer sees may be pre-digested or truncated — the facts block is the one channel\n\t// guaranteed to reach the prompt, so the gated text must ride in it (bounded).\n\tlines.push(\"active-task-containment (must appear in ## Active Task):\");\n\tif (facts.activeTaskSource) {\n\t\tlines.push(clampText(facts.activeTaskSource, ACTIVE_TASK_SOURCE_MAX_CHARS));\n\t}\n\tlines.push(\"cancelled-work-dropped (must NOT appear outside ### Mandatory Rules):\");\n\tif (facts.cancelledText) {\n\t\tlines.push(facts.cancelledText);\n\t}\n\treturn lines.join(\"\\n\");\n}\n"]}
|
|
1
|
+
{"version":3,"file":"extraction.d.ts","sourceRoot":"","sources":["../../src/compaction/extraction.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAGlE,MAAM,WAAW,kBAAkB;IAClC,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,UAAU,GAAG,SAAS,GAAG,MAAM,CAAC;IACtC,IAAI,EAAE,MAAM,CAAC;CACb;AAED,MAAM,WAAW,mBAAmB;IACnC,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,6BAA6B;IAC7C,sGAAsG;IACtG,KAAK,EAAE,WAAW,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,eAAe;IAC/B,KAAK,EAAE,kBAAkB,EAAE,CAAC;IAC5B,UAAU,EAAE,kBAAkB,EAAE,CAAC;IACjC,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,UAAU,EAAE,mBAAmB,EAAE,CAAC;IAClC,YAAY,EAAE,MAAM,EAAE,CAAC;IACvB,aAAa,EAAE,MAAM,CAAC;IACtB,gBAAgB,EAAE,MAAM,CAAC;IACzB,+EAA+E;IAC/E,oBAAoB,CAAC,EAAE,6BAA6B,EAAE,CAAC;CACvD;AAiCD,2GAA2G;AAC3G,eAAO,MAAM,4BAA4B,OAAQ,CAAC;AA2RlD,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,YAAY,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,eAAe,CAsP3G;AAgBD,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,eAAe,GAAG,MAAM,CAsC/D","sourcesContent":["import type { SessionEntry } from \"../session/session-manager.ts\";\nimport type { AgentMessage } from \"../types.ts\";\n\nexport interface CompactionFileFact {\n\tpath: string;\n\tkind: \"modified\" | \"created\" | \"read\";\n\tnote: string;\n}\n\nexport interface CompactionErrorFact {\n\toperation: string;\n\terror: string;\n}\n\nexport interface CompactionDelegatedWorkerFact {\n\t/** Worker-authored text is evidence for the parent, never a verified decision or completion claim. */\n\ttrust: \"UNTRUSTED\";\n\ttask: string;\n\tsummary: string;\n}\n\nexport interface CompactionFacts {\n\tfiles: CompactionFileFact[];\n\tworkingSet: CompactionFileFact[];\n\tactions: string[];\n\terrorFacts: CompactionErrorFact[];\n\tprohibitions: string[];\n\tcancelledText: string;\n\tactiveTaskSource: string;\n\t/** Latest-first worker evidence retained only by deterministic checkpoints. */\n\tdelegatedWorkerFacts?: CompactionDelegatedWorkerFact[];\n}\n\ninterface ToolCallFact {\n\tid: string | undefined;\n\tname: string;\n\tpath: string | undefined;\n\tbaseKind: \"modified\" | \"created\" | \"read\" | null;\n\tfinalKind: \"modified\" | \"created\" | \"read\" | null;\n\tverb: string;\n\tresolved: boolean;\n\tfailed: boolean;\n}\n\nconst PROHIBITION_PATTERN = /\\b(do not|don't|never|stop (?:doing|using|changing)|no more)\\b/i;\n// Deliberately narrow: a bare \"stop\" (\"stop the server and rerun\") is everyday phrasing, not a\n// reversal of the prior work — matching it marked whole turns cancelled and made the\n// cancelled-work gate fight the recall gates (2026-07-06 incident).\nconst REVERSAL_PATTERN =\n\t/\\b(undo|revert|roll back|never mind|scrap that|forget (?:it|that)|stop (?:that|this|it|everything|working on))\\b/i;\n\n/** User messages longer than this are documents/pastes, not spoken prohibitions. */\nconst PROHIBITION_SOURCE_MAX_CHARS = 1_500;\n/** Upper bound on gate-demanded rules; most recent win (same bounding rationale as Done carry-over). */\nconst MAX_PROHIBITIONS = 8;\n/** Upper bound on gate-demanded actions; mirrors the prompt's \"15 most recent Done items\" rule. */\nconst MAX_ACTIONS = 15;\nconst MAX_WORKING_SET_FILES = 8;\nconst MAX_ERROR_FACTS = 5;\nconst ERROR_LINE_MAX_CHARS = 160;\nconst COMMAND_PREFIX_MAX_CHARS = 80;\nconst MAX_DELEGATED_WORKER_FACTS = 4;\nconst DELEGATED_WORKER_TASK_MAX_CHARS = 240;\nconst DELEGATED_WORKER_SUMMARY_MAX_CHARS = 600;\n/** Shared clamp for the active-task text because verification can only demand what the prompt receives. */\nexport const ACTIVE_TASK_SOURCE_MAX_CHARS = 4_000;\n\nconst FILE_KIND_PRIORITY: Record<NonNullable<ToolCallFact[\"finalKind\"]>, number> = {\n\tread: 1,\n\tcreated: 2,\n\tmodified: 3,\n};\n\nconst TOOL_KIND_BY_NAME: Record<string, \"modified\" | \"created\" | \"read\" | null> = {\n\tread: \"read\",\n\tgrep: \"read\",\n\tfind: \"read\",\n\twrite: \"modified\",\n\tedit: \"modified\",\n\tbash: null,\n};\n\nconst TOOL_VERB_BY_NAME: Record<string, string> = {\n\twrite: \"WRITE\",\n\tedit: \"EDIT\",\n\tbash: \"RUN\",\n\tread: \"READ\",\n\tgrep: \"READ\",\n\tfind: \"READ\",\n};\n\nfunction messageToText(message: AgentMessage): string {\n\tconst rawContent = (message as { content?: unknown }).content;\n\tif (typeof rawContent === \"string\") {\n\t\treturn rawContent;\n\t}\n\tif (!Array.isArray(rawContent)) {\n\t\treturn \"\";\n\t}\n\n\tconst parts: string[] = [];\n\tfor (const block of rawContent) {\n\t\tif (!block || typeof block !== \"object\") {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif ((block as { type?: unknown }).type === \"text\" && typeof (block as { text?: unknown }).text === \"string\") {\n\t\t\tparts.push((block as { text: string }).text);\n\t\t}\n\t}\n\treturn (parts.length === 1 ? parts[0] : parts.join(\" \")).trim();\n}\n\nfunction assistantToolCallTarget(name: string, rawArgs: unknown): string | undefined {\n\tif (!rawArgs || typeof rawArgs !== \"object\") {\n\t\treturn undefined;\n\t}\n\tconst args = rawArgs as Record<string, unknown>;\n\n\tif (\n\t\t(name === \"read\" || name === \"grep\" || name === \"find\" || name === \"write\" || name === \"edit\") &&\n\t\ttypeof args.path === \"string\" &&\n\t\targs.path.length > 0\n\t) {\n\t\treturn args.path;\n\t}\n\n\tif (name === \"bash\" && typeof args.command === \"string\" && args.command.length > 0) {\n\t\treturn args.command;\n\t}\n\n\treturn undefined;\n}\n\nfunction clampText(text: string, maxLen: number): string {\n\treturn text.length > maxLen ? text.slice(0, maxLen) : text;\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\nfunction normalizeDelegatedWorkerText(text: string, maxLen: number): string {\n\tlet normalized = \"\";\n\tfor (const match of text.matchAll(/\\S+/g)) {\n\t\tconst separator = normalized.length > 0 ? \" \" : \"\";\n\t\tconst remaining = maxLen - normalized.length - separator.length;\n\t\tif (remaining <= 0) break;\n\t\tnormalized += `${separator}${match[0].slice(0, remaining)}`;\n\t\tif (match[0].length >= remaining) break;\n\t}\n\treturn normalized;\n}\n\nfunction extractDelegatedWorkerFact(entry: SessionEntry): CompactionDelegatedWorkerFact | undefined {\n\tif (entry.type !== \"custom\" || entry.customType !== \"worker_result\" || !isPlainRecord(entry.data)) {\n\t\treturn undefined;\n\t}\n\tif (entry.data.version !== 1 || !isPlainRecord(entry.data.result)) return undefined;\n\n\tconst result = entry.data.result;\n\tif (typeof result.requestId !== \"string\" || typeof result.summary !== \"string\") return undefined;\n\tif (typeof result.status !== \"string\" || ![\"completed\", \"blocked\", \"failed\", \"cancelled\"].includes(result.status)) {\n\t\treturn undefined;\n\t}\n\tif (!Array.isArray(result.changedFiles) || !result.changedFiles.every((file) => typeof file === \"string\")) {\n\t\treturn undefined;\n\t}\n\n\tconst request = entry.data.request;\n\tconst instructions =\n\t\tisPlainRecord(request) && typeof request.instructions === \"string\" ? request.instructions : undefined;\n\tconst task = normalizeDelegatedWorkerText(\n\t\tinstructions ?? `Worker request ${result.requestId}`,\n\t\tDELEGATED_WORKER_TASK_MAX_CHARS,\n\t);\n\tconst summary = normalizeDelegatedWorkerText(result.summary, DELEGATED_WORKER_SUMMARY_MAX_CHARS);\n\n\treturn {\n\t\ttrust: \"UNTRUSTED\",\n\t\ttask: task || \"(empty task)\",\n\t\tsummary: summary || \"(empty summary)\",\n\t};\n}\n\nfunction extractDelegatedWorkerFacts(\n\tentries: readonly SessionEntry[],\n\tstart: number,\n\tend: number,\n): CompactionDelegatedWorkerFact[] {\n\tconst facts: CompactionDelegatedWorkerFact[] = [];\n\tfor (let i = end - 1; i >= start && facts.length < MAX_DELEGATED_WORKER_FACTS; i--) {\n\t\tconst fact = extractDelegatedWorkerFact(entries[i]);\n\t\tif (fact) facts.push(fact);\n\t}\n\treturn facts;\n}\n\nfunction appearsCreated(message: AgentMessage): boolean {\n\tif (message.role !== \"toolResult\") {\n\t\treturn false;\n\t}\n\n\tconst text = messageToText(message).toLowerCase();\n\tif (/(\\bnew file\\b|\\bcreated\\b|\\bcreated file\\b)/.test(text)) {\n\t\treturn true;\n\t}\n\n\tconst details = (message as { details?: unknown }).details;\n\tif (!details || typeof details !== \"object\") {\n\t\treturn false;\n\t}\n\n\tif (typeof (details as { created?: unknown }).created === \"boolean\") {\n\t\treturn (details as { created: boolean }).created;\n\t}\n\tif (typeof (details as { isCreated?: unknown }).isCreated === \"boolean\") {\n\t\treturn (details as { isCreated: boolean }).isCreated;\n\t}\n\tif (typeof (details as { isNewFile?: unknown }).isNewFile === \"boolean\") {\n\t\treturn (details as { isNewFile: boolean }).isNewFile;\n\t}\n\n\treturn false;\n}\n\nfunction splitSentenceLines(text: string): string[] {\n\treturn text\n\t\t.split(/(?<=[.!?])\\s+|\\n+/)\n\t\t.map((line) => line.trim().replace(/[.!?]+$/, \"\"))\n\t\t.filter(Boolean);\n}\n\nfunction getMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tswitch (entry.type) {\n\t\tcase \"message\":\n\t\t\treturn entry.message;\n\t\tcase \"custom_message\":\n\t\t\treturn {\n\t\t\t\trole: \"custom\",\n\t\t\t\tcustomType: entry.customType,\n\t\t\t\tcontent: entry.content,\n\t\t\t\tdetails: entry.details,\n\t\t\t\tdisplay: entry.display,\n\t\t\t\ttimestamp: new Date(entry.timestamp).getTime(),\n\t\t\t};\n\t\tcase \"branch_summary\":\n\t\t\treturn {\n\t\t\t\trole: \"branchSummary\",\n\t\t\t\tsummary: entry.summary,\n\t\t\t\tfromId: entry.fromId,\n\t\t\t\ttimestamp: new Date(entry.timestamp).getTime(),\n\t\t\t};\n\t\tcase \"compaction\":\n\t\t\treturn undefined;\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\nfunction isToolCallBlock(block: unknown): block is { type: \"toolCall\"; id?: string; name: string; arguments: unknown } {\n\tif (!block || typeof block !== \"object\") {\n\t\treturn false;\n\t}\n\tif ((block as { type?: unknown }).type !== \"toolCall\") {\n\t\treturn false;\n\t}\n\tif (typeof (block as { name?: unknown }).name !== \"string\") {\n\t\treturn false;\n\t}\n\tif (!(block as { arguments?: unknown }).arguments) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nfunction toolCallVerb(name: string): string {\n\treturn TOOL_VERB_BY_NAME[name] ?? name.toUpperCase();\n}\n\nfunction isHarnessPlumbingTarget(target: string | undefined): boolean {\n\tif (!target) return false;\n\treturn (\n\t\ttarget.includes(\"/.pi/agent/context-gc/\") ||\n\t\ttarget.includes(\"~/.pi/agent/context-gc/\") ||\n\t\t/\\/tmp\\/pi-bash-[^\\s]+\\.log\\b/.test(target)\n\t);\n}\n\nfunction normalizeOperationTarget(toolName: string, path: string | undefined): string {\n\tif (!path) return \"(unknown)\";\n\tif (toolName !== \"bash\") return path;\n\treturn clampText(path.replace(/\\s+/g, \" \").trim(), COMMAND_PREFIX_MAX_CHARS);\n}\n\nfunction operationKey(toolName: string, path: string | undefined): string {\n\treturn `${toolName}:${normalizeOperationTarget(toolName, path)}`;\n}\n\nfunction operationLabel(toolName: string, path: string | undefined): string {\n\treturn `${toolCallVerb(toolName)} ${normalizeOperationTarget(toolName, path)}`;\n}\n\nfunction resultExitCode(message: AgentMessage): number | undefined {\n\tconst details = (message as { details?: unknown }).details;\n\tif (!details || typeof details !== \"object\") return undefined;\n\tconst raw = (details as { exitCode?: unknown }).exitCode;\n\tif (typeof raw === \"number\" && Number.isFinite(raw)) return raw;\n\tif (typeof raw === \"string\" && /^\\d+$/.test(raw)) return Number(raw);\n\treturn undefined;\n}\n\nfunction isOutcomeBearingTool(toolName: string | undefined): boolean {\n\treturn toolName === \"bash\";\n}\n\nfunction isOpenProblemTool(toolName: string | undefined): boolean {\n\treturn toolName === \"bash\" || toolName === \"edit\" || toolName === \"write\";\n}\n\nfunction failureSignalLine(text: string): string | undefined {\n\treturn text\n\t\t.split(/\\r?\\n/)\n\t\t.map((part) => part.trim())\n\t\t.find((line) => /exited with code [1-9]\\d*/i.test(line) || /^(error|fatal|✗|FAIL)\\b/i.test(line));\n}\n\nfunction firstErrorLine(text: string): string {\n\tconst line =\n\t\tfailureSignalLine(text) ??\n\t\ttext\n\t\t\t.split(/\\r?\\n/)\n\t\t\t.map((part) => part.trim())\n\t\t\t.find(Boolean);\n\treturn clampText(line ?? \"failed\", ERROR_LINE_MAX_CHARS);\n}\n\nfunction isFailureToolResult(message: AgentMessage, text: string): boolean {\n\tif (message.role !== \"toolResult\") return false;\n\tif ((message as { isError?: unknown }).isError === true) return true;\n\tconst exitCode = resultExitCode(message);\n\tif (exitCode !== undefined) return exitCode !== 0;\n\tconst toolName = (message as { toolName?: unknown }).toolName;\n\treturn typeof toolName === \"string\" && isOutcomeBearingTool(toolName) && failureSignalLine(text) !== undefined;\n}\n\nexport function extractCompactionFacts(entries: SessionEntry[], start: number, end: number): CompactionFacts {\n\tconst rangeStart = Math.max(0, start);\n\tconst rangeEnd = Math.min(entries.length, Math.max(rangeStart, end));\n\n\tif (rangeStart >= rangeEnd) {\n\t\treturn {\n\t\t\tfiles: [],\n\t\t\tworkingSet: [],\n\t\t\tactions: [],\n\t\t\terrorFacts: [],\n\t\t\tprohibitions: [],\n\t\t\tcancelledText: \"\",\n\t\t\tactiveTaskSource: \"\",\n\t\t\tdelegatedWorkerFacts: [],\n\t\t};\n\t}\n\tconst delegatedWorkerFacts = extractDelegatedWorkerFacts(entries, rangeStart, rangeEnd);\n\n\tconst filesByPath = new Map<string, CompactionFileFact & { lastTouch: number }>();\n\tconst filesNotes = new Map<string, string>();\n\tconst seenProhibitions = new Set<string>();\n\tconst actionFacts: ToolCallFact[] = [];\n\tconst pendingById = new Map<string, number[]>();\n\tconst pendingByOrder: number[] = [];\n\n\tconst actions: string[] = [];\n\tconst openErrors = new Map<string, CompactionErrorFact & { lastTouch: number }>();\n\tconst prohibitions: string[] = [];\n\tlet activeTaskSource = \"\";\n\tconst cancelledParts: string[] = [];\n\tconst sinceLastUser: string[] = [];\n\n\tfor (let i = rangeStart; i < rangeEnd; i++) {\n\t\tconst message = getMessageFromEntry(entries[i]);\n\t\tif (!message) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (message.role === \"user\") {\n\t\t\tconst userText = messageToText(message);\n\t\t\tif (REVERSAL_PATTERN.test(userText)) {\n\t\t\t\tcancelledParts.push(...sinceLastUser);\n\t\t\t}\n\t\t\tsinceLastUser.length = 0;\n\n\t\t\tif (userText) {\n\t\t\t\tactiveTaskSource = clampText(userText, ACTIVE_TASK_SOURCE_MAX_CHARS);\n\t\t\t\t// Mandatory Rules exist for SPOKEN durable prohibitions (\"do not touch X\"), not for\n\t\t\t\t// documents. A long pasted text (plan, instruction file) can contain dozens of\n\t\t\t\t// \"never/do not\" lines; harvesting them makes the verification gate demand the\n\t\t\t\t// checkpoint reproduce the document (2026-07-06 field incident: 13 fragment rules\n\t\t\t\t// extracted from one pasted instruction). Documents live on disk; skip them here.\n\t\t\t\tif (userText.length <= PROHIBITION_SOURCE_MAX_CHARS) {\n\t\t\t\t\tfor (const sentence of splitSentenceLines(userText)) {\n\t\t\t\t\t\tif (!PROHIBITION_PATTERN.test(sentence)) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst normalized = clampText(sentence, 160);\n\t\t\t\t\t\tconst dedupeKey = normalized.toLowerCase();\n\t\t\t\t\t\tif (!seenProhibitions.has(dedupeKey)) {\n\t\t\t\t\t\t\tseenProhibitions.add(dedupeKey);\n\t\t\t\t\t\t\tprohibitions.push(normalized);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (message.role === \"assistant\" || message.role === \"toolResult\") {\n\t\t\tconst messageText = messageToText(message);\n\t\t\tif (messageText) {\n\t\t\t\tsinceLastUser.push(messageText);\n\t\t\t}\n\t\t}\n\n\t\tif (message.role === \"assistant\" && Array.isArray(message.content)) {\n\t\t\tfor (const block of message.content) {\n\t\t\t\tif (!isToolCallBlock(block)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst name = block.name;\n\t\t\t\tconst verb = toolCallVerb(name);\n\t\t\t\tconst path = assistantToolCallTarget(name, block.arguments);\n\t\t\t\tconst baseKind = TOOL_KIND_BY_NAME[name] ?? null;\n\t\t\t\tconst fact: ToolCallFact = {\n\t\t\t\t\tid: block.id,\n\t\t\t\t\tname,\n\t\t\t\t\tpath,\n\t\t\t\t\tbaseKind,\n\t\t\t\t\tfinalKind: baseKind,\n\t\t\t\t\tverb,\n\t\t\t\t\tresolved: false,\n\t\t\t\t\tfailed: false,\n\t\t\t\t};\n\t\t\t\tactionFacts.push(fact);\n\t\t\t\tconst index = actionFacts.length - 1;\n\t\t\t\tpendingByOrder.push(index);\n\t\t\t\tif (fact.id) {\n\t\t\t\t\tconst bucket = pendingById.get(fact.id) ?? [];\n\t\t\t\t\tbucket.push(index);\n\t\t\t\t\tpendingById.set(fact.id, bucket);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (message.role === \"toolResult\") {\n\t\t\tconst toolCallId = (message as { toolCallId?: string }).toolCallId;\n\t\t\tconst toolName = (message as { toolName?: string }).toolName;\n\t\t\tlet matchedIndex: number | undefined;\n\n\t\t\tif (toolCallId) {\n\t\t\t\tconst bucket = pendingById.get(toolCallId);\n\t\t\t\tif (bucket && bucket.length > 0) {\n\t\t\t\t\tmatchedIndex = bucket.shift();\n\t\t\t\t\tif (bucket.length === 0) {\n\t\t\t\t\t\tpendingById.delete(toolCallId);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (matchedIndex === undefined && toolName) {\n\t\t\t\tfor (const index of pendingByOrder) {\n\t\t\t\t\tconst candidate = actionFacts[index];\n\t\t\t\t\tif (!candidate.resolved && candidate.name === toolName) {\n\t\t\t\t\t\tmatchedIndex = index;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (matchedIndex !== undefined) {\n\t\t\t\tconst fact = actionFacts[matchedIndex];\n\t\t\t\tconst resultText = messageToText(message);\n\t\t\t\tconst failed = isFailureToolResult(message, resultText);\n\t\t\t\tfact.resolved = true;\n\t\t\t\tfact.failed = failed;\n\t\t\t\tif (!failed && fact.baseKind === \"modified\" && appearsCreated(message)) {\n\t\t\t\t\tfact.finalKind = \"created\";\n\t\t\t\t}\n\n\t\t\t\tif (!failed && fact.path && fact.finalKind && !isHarnessPlumbingTarget(fact.path)) {\n\t\t\t\t\tconst existing = filesByPath.get(fact.path);\n\t\t\t\t\tconst nextKind = fact.finalKind;\n\t\t\t\t\tconst note = fact.verb;\n\t\t\t\t\tif (!existing || FILE_KIND_PRIORITY[nextKind] > FILE_KIND_PRIORITY[existing.kind]) {\n\t\t\t\t\t\tfilesByPath.set(fact.path, { path: fact.path, kind: nextKind, note, lastTouch: i });\n\t\t\t\t\t} else if (existing.kind === nextKind) {\n\t\t\t\t\t\texisting.note = note;\n\t\t\t\t\t\texisting.lastTouch = i;\n\t\t\t\t\t} else {\n\t\t\t\t\t\texisting.lastTouch = i;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst key = operationKey(fact.name, fact.path);\n\t\t\t\tif (failed && isOpenProblemTool(fact.name)) {\n\t\t\t\t\topenErrors.set(key, {\n\t\t\t\t\t\toperation: operationLabel(fact.name, fact.path),\n\t\t\t\t\t\terror: firstErrorLine(resultText),\n\t\t\t\t\t\tlastTouch: i,\n\t\t\t\t\t});\n\t\t\t\t} else if (!failed) {\n\t\t\t\t\topenErrors.delete(key);\n\t\t\t\t}\n\n\t\t\t\tconst pendingPos = pendingByOrder.indexOf(matchedIndex);\n\t\t\t\tif (pendingPos >= 0) {\n\t\t\t\t\tpendingByOrder.splice(pendingPos, 1);\n\t\t\t\t}\n\t\t\t\tif (toolCallId) {\n\t\t\t\t\tconst bucket = pendingById.get(toolCallId);\n\t\t\t\t\tif (bucket) {\n\t\t\t\t\t\tconst pos = bucket.indexOf(matchedIndex);\n\t\t\t\t\t\tif (pos >= 0) {\n\t\t\t\t\t\t\tbucket.splice(pos, 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (bucket.length === 0) {\n\t\t\t\t\t\t\tpendingById.delete(toolCallId);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (const action of actionFacts) {\n\t\tif (isHarnessPlumbingTarget(action.path)) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (action.resolved && action.failed && action.name !== \"bash\") {\n\t\t\tcontinue;\n\t\t}\n\t\tif ((!action.resolved || !action.failed) && action.finalKind && action.path && !filesByPath.has(action.path)) {\n\t\t\tfilesByPath.set(action.path, {\n\t\t\t\tpath: action.path,\n\t\t\t\tkind: action.finalKind,\n\t\t\t\tnote: action.verb,\n\t\t\t\tlastTouch: actionFacts.indexOf(action),\n\t\t\t});\n\t\t}\n\n\t\tactions.push(`${action.verb} ${action.path ?? \"(unknown)\"}`);\n\t}\n\n\tfor (const file of filesByPath.values()) {\n\t\tif (!file.note && filesNotes.has(file.path)) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (file.note && filesNotes.get(file.path) === file.note) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (file.note) {\n\t\t\tfilesNotes.set(file.path, file.note);\n\t\t}\n\t}\n\n\tfor (const file of filesByPath.values()) {\n\t\tconst suffix = filesNotes.get(file.path);\n\t\tif (suffix) {\n\t\t\tfile.note = suffix;\n\t\t}\n\t}\n\n\tconst files = Array.from(filesByPath.values())\n\t\t.sort(\n\t\t\t(a, b) =>\n\t\t\t\tb.lastTouch - a.lastTouch ||\n\t\t\t\tFILE_KIND_PRIORITY[b.kind] - FILE_KIND_PRIORITY[a.kind] ||\n\t\t\t\ta.path.localeCompare(b.path),\n\t\t)\n\t\t.map(({ lastTouch: _lastTouch, ...file }) => file);\n\n\treturn {\n\t\tfiles,\n\t\tworkingSet: files.slice(0, MAX_WORKING_SET_FILES),\n\t\tactions: dedupeMostRecent(actions).slice(-MAX_ACTIONS),\n\t\terrorFacts: Array.from(openErrors.values())\n\t\t\t.sort((a, b) => a.lastTouch - b.lastTouch)\n\t\t\t.slice(-MAX_ERROR_FACTS)\n\t\t\t.map(({ lastTouch: _lastTouch, ...error }) => error),\n\t\tprohibitions: prohibitions.slice(-MAX_PROHIBITIONS),\n\t\tcancelledText: cancelledParts.join(\"\\n\"),\n\t\tactiveTaskSource,\n\t\tdelegatedWorkerFacts,\n\t};\n}\n\nfunction dedupeMostRecent(values: string[]): string[] {\n\tconst seen = new Set<string>();\n\tconst kept: string[] = [];\n\tfor (let i = values.length - 1; i >= 0; i--) {\n\t\tconst value = values[i];\n\t\tif (seen.has(value)) {\n\t\t\tcontinue;\n\t\t}\n\t\tseen.add(value);\n\t\tkept.push(value);\n\t}\n\treturn kept.reverse();\n}\n\nexport function renderFactsBlock(facts: CompactionFacts): string {\n\tconst lines: string[] = [\"verification demands:\"];\n\tlines.push(\"files-modified-recall (must appear in ## Files):\");\n\tfor (const file of facts.files.filter((file) => file.kind !== \"read\")) {\n\t\tlines.push(file.path);\n\t}\n\tlines.push(\"files-read-recall (must appear in ## Files, containment threshold applies):\");\n\tfor (const file of facts.files.filter((file) => file.kind === \"read\")) {\n\t\tlines.push(file.path);\n\t}\n\tlines.push(\"working-set-recall (must appear in ## Working Set):\");\n\tfor (const file of facts.workingSet) {\n\t\tlines.push(`${file.path} — ${file.note || file.kind}`);\n\t}\n\tlines.push(\"open-errors-recall (must appear in ## Open Problems):\");\n\tfor (const error of facts.errorFacts) {\n\t\tlines.push(`${error.operation}: ${error.error}`);\n\t}\n\tlines.push(\"actions-recall (must appear in ## Done):\");\n\tfor (const action of facts.actions) {\n\t\tlines.push(action);\n\t}\n\tlines.push(\"mandatory-rules-recall (must appear in ### Mandatory Rules):\");\n\tfor (const prohibition of facts.prohibitions) {\n\t\tlines.push(prohibition);\n\t}\n\t// The active-task gate demands near-verbatim recall of this text, but the conversation the\n\t// summarizer sees may be pre-digested or truncated — the facts block is the one channel\n\t// guaranteed to reach the prompt, so the gated text must ride in it (bounded).\n\tlines.push(\"active-task-containment (must appear in ## Active Task):\");\n\tif (facts.activeTaskSource) {\n\t\tlines.push(clampText(facts.activeTaskSource, ACTIVE_TASK_SOURCE_MAX_CHARS));\n\t}\n\tlines.push(\"cancelled-work-dropped (must NOT appear outside ### Mandatory Rules):\");\n\tif (facts.cancelledText) {\n\t\tlines.push(facts.cancelledText);\n\t}\n\treturn lines.join(\"\\n\");\n}\n"]}
|
|
@@ -56,7 +56,7 @@ function messageToText(message) {
|
|
|
56
56
|
parts.push(block.text);
|
|
57
57
|
}
|
|
58
58
|
}
|
|
59
|
-
return parts.join(" ").trim();
|
|
59
|
+
return (parts.length === 1 ? parts[0] : parts.join(" ")).trim();
|
|
60
60
|
}
|
|
61
61
|
function assistantToolCallTarget(name, rawArgs) {
|
|
62
62
|
if (!rawArgs || typeof rawArgs !== "object") {
|
|
@@ -83,7 +83,17 @@ function isPlainRecord(value) {
|
|
|
83
83
|
return prototype === Object.prototype || prototype === null;
|
|
84
84
|
}
|
|
85
85
|
function normalizeDelegatedWorkerText(text, maxLen) {
|
|
86
|
-
|
|
86
|
+
let normalized = "";
|
|
87
|
+
for (const match of text.matchAll(/\S+/g)) {
|
|
88
|
+
const separator = normalized.length > 0 ? " " : "";
|
|
89
|
+
const remaining = maxLen - normalized.length - separator.length;
|
|
90
|
+
if (remaining <= 0)
|
|
91
|
+
break;
|
|
92
|
+
normalized += `${separator}${match[0].slice(0, remaining)}`;
|
|
93
|
+
if (match[0].length >= remaining)
|
|
94
|
+
break;
|
|
95
|
+
}
|
|
96
|
+
return normalized;
|
|
87
97
|
}
|
|
88
98
|
function extractDelegatedWorkerFact(entry) {
|
|
89
99
|
if (entry.type !== "custom" || entry.customType !== "worker_result" || !isPlainRecord(entry.data)) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"extraction.js","sourceRoot":"","sources":["../../src/compaction/extraction.ts"],"names":[],"mappings":"AA4CA,MAAM,mBAAmB,GAAG,iEAAiE,CAAC;AAC9F,+FAA+F;AAC/F,uFAAqF;AACrF,oEAAoE;AACpE,MAAM,gBAAgB,GACrB,mHAAmH,CAAC;AAErH,oFAAoF;AACpF,MAAM,4BAA4B,GAAG,KAAK,CAAC;AAC3C,wGAAwG;AACxG,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAC3B,mGAAmG;AACnG,MAAM,WAAW,GAAG,EAAE,CAAC;AACvB,MAAM,qBAAqB,GAAG,CAAC,CAAC;AAChC,MAAM,eAAe,GAAG,CAAC,CAAC;AAC1B,MAAM,oBAAoB,GAAG,GAAG,CAAC;AACjC,MAAM,wBAAwB,GAAG,EAAE,CAAC;AACpC,MAAM,0BAA0B,GAAG,CAAC,CAAC;AACrC,MAAM,+BAA+B,GAAG,GAAG,CAAC;AAC5C,MAAM,kCAAkC,GAAG,GAAG,CAAC;AAC/C,2GAA2G;AAC3G,MAAM,CAAC,MAAM,4BAA4B,GAAG,KAAK,CAAC;AAElD,MAAM,kBAAkB,GAA2D;IAClF,IAAI,EAAE,CAAC;IACP,OAAO,EAAE,CAAC;IACV,QAAQ,EAAE,CAAC;CACX,CAAC;AAEF,MAAM,iBA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,EAAE,CAAC,CAAC;IAClD,CAAC;IACD,KAAK,CAAC,IAAI,CAAC,0CAA0C,CAAC,CAAC;IACvD,KAAK,MAAM,MAAM,IAAI,KAAK,CAAC,OAAO,EAAE,CAAC;QACpC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACpB,CAAC;IACD,KAAK,CAAC,IAAI,CAAC,8DAA8D,CAAC,CAAC;IAC3E,KAAK,MAAM,WAAW,IAAI,KAAK,CAAC,YAAY,EAAE,CAAC;QAC9C,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;IACzB,CAAC;IACD,2FAA2F;IAC3F,0FAAwF;IACxF,+EAA+E;IAC/E,KAAK,CAAC,IAAI,CAAC,0DAA0D,CAAC,CAAC;IACvE,IAAI,KAAK,CAAC,gBAAgB,EAAE,CAAC;QAC5B,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,gBAAgB,EAAE,4BAA4B,CAAC,CAAC,CAAC;IAC7E,CAAC;IACD,KAAK,CAAC,IAAI,CAAC,uEAAuE,CAAC,CAAC;IACpF,IAAI,KAAK,CAAC,aAAa,EAAE,CAAC;QACzB,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,aAAa,CAAC,CAAC;IACjC,CAAC;IACD,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAAA,CACxB","sourcesContent":["import type { SessionEntry } from \"../session/session-manager.ts\";\nimport type { AgentMessage } from \"../types.ts\";\n\nexport interface CompactionFileFact {\n\tpath: string;\n\tkind: \"modified\" | \"created\" | \"read\";\n\tnote: string;\n}\n\nexport interface CompactionErrorFact {\n\toperation: string;\n\terror: string;\n}\n\nexport interface CompactionDelegatedWorkerFact {\n\t/** Worker-authored text is evidence for the parent, never a verified decision or completion claim. */\n\ttrust: \"UNTRUSTED\";\n\ttask: string;\n\tsummary: string;\n}\n\nexport interface CompactionFacts {\n\tfiles: CompactionFileFact[];\n\tworkingSet: CompactionFileFact[];\n\tactions: string[];\n\terrorFacts: CompactionErrorFact[];\n\tprohibitions: string[];\n\tcancelledText: string;\n\tactiveTaskSource: string;\n\t/** Latest-first worker evidence retained only by deterministic checkpoints. */\n\tdelegatedWorkerFacts?: CompactionDelegatedWorkerFact[];\n}\n\ninterface ToolCallFact {\n\tid: string | undefined;\n\tname: string;\n\tpath: string | undefined;\n\tbaseKind: \"modified\" | \"created\" | \"read\" | null;\n\tfinalKind: \"modified\" | \"created\" | \"read\" | null;\n\tverb: string;\n\tresolved: boolean;\n\tfailed: boolean;\n}\n\nconst PROHIBITION_PATTERN = /\\b(do not|don't|never|stop (?:doing|using|changing)|no more)\\b/i;\n// Deliberately narrow: a bare \"stop\" (\"stop the server and rerun\") is everyday phrasing, not a\n// reversal of the prior work — matching it marked whole turns cancelled and made the\n// cancelled-work gate fight the recall gates (2026-07-06 incident).\nconst REVERSAL_PATTERN =\n\t/\\b(undo|revert|roll back|never mind|scrap that|forget (?:it|that)|stop (?:that|this|it|everything|working on))\\b/i;\n\n/** User messages longer than this are documents/pastes, not spoken prohibitions. */\nconst PROHIBITION_SOURCE_MAX_CHARS = 1_500;\n/** Upper bound on gate-demanded rules; most recent win (same bounding rationale as Done carry-over). */\nconst MAX_PROHIBITIONS = 8;\n/** Upper bound on gate-demanded actions; mirrors the prompt's \"15 most recent Done items\" rule. */\nconst MAX_ACTIONS = 15;\nconst MAX_WORKING_SET_FILES = 8;\nconst MAX_ERROR_FACTS = 5;\nconst ERROR_LINE_MAX_CHARS = 160;\nconst COMMAND_PREFIX_MAX_CHARS = 80;\nconst MAX_DELEGATED_WORKER_FACTS = 4;\nconst DELEGATED_WORKER_TASK_MAX_CHARS = 240;\nconst DELEGATED_WORKER_SUMMARY_MAX_CHARS = 600;\n/** Shared clamp for the active-task text because verification can only demand what the prompt receives. */\nexport const ACTIVE_TASK_SOURCE_MAX_CHARS = 4_000;\n\nconst FILE_KIND_PRIORITY: Record<NonNullable<ToolCallFact[\"finalKind\"]>, number> = {\n\tread: 1,\n\tcreated: 2,\n\tmodified: 3,\n};\n\nconst TOOL_KIND_BY_NAME: Record<string, \"modified\" | \"created\" | \"read\" | null> = {\n\tread: \"read\",\n\tgrep: \"read\",\n\tfind: \"read\",\n\twrite: \"modified\",\n\tedit: \"modified\",\n\tbash: null,\n};\n\nconst TOOL_VERB_BY_NAME: Record<string, string> = {\n\twrite: \"WRITE\",\n\tedit: \"EDIT\",\n\tbash: \"RUN\",\n\tread: \"READ\",\n\tgrep: \"READ\",\n\tfind: \"READ\",\n};\n\nfunction messageToText(message: AgentMessage): string {\n\tconst rawContent = (message as { content?: unknown }).content;\n\tif (typeof rawContent === \"string\") {\n\t\treturn rawContent;\n\t}\n\tif (!Array.isArray(rawContent)) {\n\t\treturn \"\";\n\t}\n\n\tconst parts: string[] = [];\n\tfor (const block of rawContent) {\n\t\tif (!block || typeof block !== \"object\") {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif ((block as { type?: unknown }).type === \"text\" && typeof (block as { text?: unknown }).text === \"string\") {\n\t\t\tparts.push((block as { text: string }).text);\n\t\t}\n\t}\n\treturn parts.join(\" \").trim();\n}\n\nfunction assistantToolCallTarget(name: string, rawArgs: unknown): string | undefined {\n\tif (!rawArgs || typeof rawArgs !== \"object\") {\n\t\treturn undefined;\n\t}\n\tconst args = rawArgs as Record<string, unknown>;\n\n\tif (\n\t\t(name === \"read\" || name === \"grep\" || name === \"find\" || name === \"write\" || name === \"edit\") &&\n\t\ttypeof args.path === \"string\" &&\n\t\targs.path.length > 0\n\t) {\n\t\treturn args.path;\n\t}\n\n\tif (name === \"bash\" && typeof args.command === \"string\" && args.command.length > 0) {\n\t\treturn args.command;\n\t}\n\n\treturn undefined;\n}\n\nfunction clampText(text: string, maxLen: number): string {\n\treturn text.length > maxLen ? text.slice(0, maxLen) : text;\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\nfunction normalizeDelegatedWorkerText(text: string, maxLen: number): string {\n\treturn clampText(text.replace(/\\s+/g, \" \").trim(), maxLen);\n}\n\nfunction extractDelegatedWorkerFact(entry: SessionEntry): CompactionDelegatedWorkerFact | undefined {\n\tif (entry.type !== \"custom\" || entry.customType !== \"worker_result\" || !isPlainRecord(entry.data)) {\n\t\treturn undefined;\n\t}\n\tif (entry.data.version !== 1 || !isPlainRecord(entry.data.result)) return undefined;\n\n\tconst result = entry.data.result;\n\tif (typeof result.requestId !== \"string\" || typeof result.summary !== \"string\") return undefined;\n\tif (typeof result.status !== \"string\" || ![\"completed\", \"blocked\", \"failed\", \"cancelled\"].includes(result.status)) {\n\t\treturn undefined;\n\t}\n\tif (!Array.isArray(result.changedFiles) || !result.changedFiles.every((file) => typeof file === \"string\")) {\n\t\treturn undefined;\n\t}\n\n\tconst request = entry.data.request;\n\tconst instructions =\n\t\tisPlainRecord(request) && typeof request.instructions === \"string\" ? request.instructions : undefined;\n\tconst task = normalizeDelegatedWorkerText(\n\t\tinstructions ?? `Worker request ${result.requestId}`,\n\t\tDELEGATED_WORKER_TASK_MAX_CHARS,\n\t);\n\tconst summary = normalizeDelegatedWorkerText(result.summary, DELEGATED_WORKER_SUMMARY_MAX_CHARS);\n\n\treturn {\n\t\ttrust: \"UNTRUSTED\",\n\t\ttask: task || \"(empty task)\",\n\t\tsummary: summary || \"(empty summary)\",\n\t};\n}\n\nfunction extractDelegatedWorkerFacts(\n\tentries: readonly SessionEntry[],\n\tstart: number,\n\tend: number,\n): CompactionDelegatedWorkerFact[] {\n\tconst facts: CompactionDelegatedWorkerFact[] = [];\n\tfor (let i = end - 1; i >= start && facts.length < MAX_DELEGATED_WORKER_FACTS; i--) {\n\t\tconst fact = extractDelegatedWorkerFact(entries[i]);\n\t\tif (fact) facts.push(fact);\n\t}\n\treturn facts;\n}\n\nfunction appearsCreated(message: AgentMessage): boolean {\n\tif (message.role !== \"toolResult\") {\n\t\treturn false;\n\t}\n\n\tconst text = messageToText(message).toLowerCase();\n\tif (/(\\bnew file\\b|\\bcreated\\b|\\bcreated file\\b)/.test(text)) {\n\t\treturn true;\n\t}\n\n\tconst details = (message as { details?: unknown }).details;\n\tif (!details || typeof details !== \"object\") {\n\t\treturn false;\n\t}\n\n\tif (typeof (details as { created?: unknown }).created === \"boolean\") {\n\t\treturn (details as { created: boolean }).created;\n\t}\n\tif (typeof (details as { isCreated?: unknown }).isCreated === \"boolean\") {\n\t\treturn (details as { isCreated: boolean }).isCreated;\n\t}\n\tif (typeof (details as { isNewFile?: unknown }).isNewFile === \"boolean\") {\n\t\treturn (details as { isNewFile: boolean }).isNewFile;\n\t}\n\n\treturn false;\n}\n\nfunction splitSentenceLines(text: string): string[] {\n\treturn text\n\t\t.split(/(?<=[.!?])\\s+|\\n+/)\n\t\t.map((line) => line.trim().replace(/[.!?]+$/, \"\"))\n\t\t.filter(Boolean);\n}\n\nfunction getMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tswitch (entry.type) {\n\t\tcase \"message\":\n\t\t\treturn entry.message;\n\t\tcase \"custom_message\":\n\t\t\treturn {\n\t\t\t\trole: \"custom\",\n\t\t\t\tcustomType: entry.customType,\n\t\t\t\tcontent: entry.content,\n\t\t\t\tdetails: entry.details,\n\t\t\t\tdisplay: entry.display,\n\t\t\t\ttimestamp: new Date(entry.timestamp).getTime(),\n\t\t\t};\n\t\tcase \"branch_summary\":\n\t\t\treturn {\n\t\t\t\trole: \"branchSummary\",\n\t\t\t\tsummary: entry.summary,\n\t\t\t\tfromId: entry.fromId,\n\t\t\t\ttimestamp: new Date(entry.timestamp).getTime(),\n\t\t\t};\n\t\tcase \"compaction\":\n\t\t\treturn undefined;\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\nfunction isToolCallBlock(block: unknown): block is { type: \"toolCall\"; id?: string; name: string; arguments: unknown } {\n\tif (!block || typeof block !== \"object\") {\n\t\treturn false;\n\t}\n\tif ((block as { type?: unknown }).type !== \"toolCall\") {\n\t\treturn false;\n\t}\n\tif (typeof (block as { name?: unknown }).name !== \"string\") {\n\t\treturn false;\n\t}\n\tif (!(block as { arguments?: unknown }).arguments) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nfunction toolCallVerb(name: string): string {\n\treturn TOOL_VERB_BY_NAME[name] ?? name.toUpperCase();\n}\n\nfunction isHarnessPlumbingTarget(target: string | undefined): boolean {\n\tif (!target) return false;\n\treturn (\n\t\ttarget.includes(\"/.pi/agent/context-gc/\") ||\n\t\ttarget.includes(\"~/.pi/agent/context-gc/\") ||\n\t\t/\\/tmp\\/pi-bash-[^\\s]+\\.log\\b/.test(target)\n\t);\n}\n\nfunction normalizeOperationTarget(toolName: string, path: string | undefined): string {\n\tif (!path) return \"(unknown)\";\n\tif (toolName !== \"bash\") return path;\n\treturn clampText(path.replace(/\\s+/g, \" \").trim(), COMMAND_PREFIX_MAX_CHARS);\n}\n\nfunction operationKey(toolName: string, path: string | undefined): string {\n\treturn `${toolName}:${normalizeOperationTarget(toolName, path)}`;\n}\n\nfunction operationLabel(toolName: string, path: string | undefined): string {\n\treturn `${toolCallVerb(toolName)} ${normalizeOperationTarget(toolName, path)}`;\n}\n\nfunction resultExitCode(message: AgentMessage): number | undefined {\n\tconst details = (message as { details?: unknown }).details;\n\tif (!details || typeof details !== \"object\") return undefined;\n\tconst raw = (details as { exitCode?: unknown }).exitCode;\n\tif (typeof raw === \"number\" && Number.isFinite(raw)) return raw;\n\tif (typeof raw === \"string\" && /^\\d+$/.test(raw)) return Number(raw);\n\treturn undefined;\n}\n\nfunction isOutcomeBearingTool(toolName: string | undefined): boolean {\n\treturn toolName === \"bash\";\n}\n\nfunction isOpenProblemTool(toolName: string | undefined): boolean {\n\treturn toolName === \"bash\" || toolName === \"edit\" || toolName === \"write\";\n}\n\nfunction failureSignalLine(text: string): string | undefined {\n\treturn text\n\t\t.split(/\\r?\\n/)\n\t\t.map((part) => part.trim())\n\t\t.find((line) => /exited with code [1-9]\\d*/i.test(line) || /^(error|fatal|✗|FAIL)\\b/i.test(line));\n}\n\nfunction firstErrorLine(text: string): string {\n\tconst line =\n\t\tfailureSignalLine(text) ??\n\t\ttext\n\t\t\t.split(/\\r?\\n/)\n\t\t\t.map((part) => part.trim())\n\t\t\t.find(Boolean);\n\treturn clampText(line ?? \"failed\", ERROR_LINE_MAX_CHARS);\n}\n\nfunction isFailureToolResult(message: AgentMessage, text: string): boolean {\n\tif (message.role !== \"toolResult\") return false;\n\tif ((message as { isError?: unknown }).isError === true) return true;\n\tconst exitCode = resultExitCode(message);\n\tif (exitCode !== undefined) return exitCode !== 0;\n\tconst toolName = (message as { toolName?: unknown }).toolName;\n\treturn typeof toolName === \"string\" && isOutcomeBearingTool(toolName) && failureSignalLine(text) !== undefined;\n}\n\nexport function extractCompactionFacts(entries: SessionEntry[], start: number, end: number): CompactionFacts {\n\tconst rangeStart = Math.max(0, start);\n\tconst rangeEnd = Math.min(entries.length, Math.max(rangeStart, end));\n\n\tif (rangeStart >= rangeEnd) {\n\t\treturn {\n\t\t\tfiles: [],\n\t\t\tworkingSet: [],\n\t\t\tactions: [],\n\t\t\terrorFacts: [],\n\t\t\tprohibitions: [],\n\t\t\tcancelledText: \"\",\n\t\t\tactiveTaskSource: \"\",\n\t\t\tdelegatedWorkerFacts: [],\n\t\t};\n\t}\n\tconst delegatedWorkerFacts = extractDelegatedWorkerFacts(entries, rangeStart, rangeEnd);\n\n\tconst filesByPath = new Map<string, CompactionFileFact & { lastTouch: number }>();\n\tconst filesNotes = new Map<string, string>();\n\tconst seenProhibitions = new Set<string>();\n\tconst actionFacts: ToolCallFact[] = [];\n\tconst pendingById = new Map<string, number[]>();\n\tconst pendingByOrder: number[] = [];\n\n\tconst actions: string[] = [];\n\tconst openErrors = new Map<string, CompactionErrorFact & { lastTouch: number }>();\n\tconst prohibitions: string[] = [];\n\tlet activeTaskSource = \"\";\n\tconst cancelledParts: string[] = [];\n\tconst sinceLastUser: string[] = [];\n\n\tfor (let i = rangeStart; i < rangeEnd; i++) {\n\t\tconst message = getMessageFromEntry(entries[i]);\n\t\tif (!message) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (message.role === \"user\") {\n\t\t\tconst userText = messageToText(message);\n\t\t\tif (REVERSAL_PATTERN.test(userText)) {\n\t\t\t\tcancelledParts.push(...sinceLastUser);\n\t\t\t}\n\t\t\tsinceLastUser.length = 0;\n\n\t\t\tif (userText) {\n\t\t\t\tactiveTaskSource = clampText(userText, ACTIVE_TASK_SOURCE_MAX_CHARS);\n\t\t\t\t// Mandatory Rules exist for SPOKEN durable prohibitions (\"do not touch X\"), not for\n\t\t\t\t// documents. A long pasted text (plan, instruction file) can contain dozens of\n\t\t\t\t// \"never/do not\" lines; harvesting them makes the verification gate demand the\n\t\t\t\t// checkpoint reproduce the document (2026-07-06 field incident: 13 fragment rules\n\t\t\t\t// extracted from one pasted instruction). Documents live on disk; skip them here.\n\t\t\t\tif (userText.length <= PROHIBITION_SOURCE_MAX_CHARS) {\n\t\t\t\t\tfor (const sentence of splitSentenceLines(userText)) {\n\t\t\t\t\t\tif (!PROHIBITION_PATTERN.test(sentence)) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst normalized = clampText(sentence, 160);\n\t\t\t\t\t\tconst dedupeKey = normalized.toLowerCase();\n\t\t\t\t\t\tif (!seenProhibitions.has(dedupeKey)) {\n\t\t\t\t\t\t\tseenProhibitions.add(dedupeKey);\n\t\t\t\t\t\t\tprohibitions.push(normalized);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (message.role === \"assistant\" || message.role === \"toolResult\") {\n\t\t\tconst messageText = messageToText(message);\n\t\t\tif (messageText) {\n\t\t\t\tsinceLastUser.push(messageText);\n\t\t\t}\n\t\t}\n\n\t\tif (message.role === \"assistant\" && Array.isArray(message.content)) {\n\t\t\tfor (const block of message.content) {\n\t\t\t\tif (!isToolCallBlock(block)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst name = block.name;\n\t\t\t\tconst verb = toolCallVerb(name);\n\t\t\t\tconst path = assistantToolCallTarget(name, block.arguments);\n\t\t\t\tconst baseKind = TOOL_KIND_BY_NAME[name] ?? null;\n\t\t\t\tconst fact: ToolCallFact = {\n\t\t\t\t\tid: block.id,\n\t\t\t\t\tname,\n\t\t\t\t\tpath,\n\t\t\t\t\tbaseKind,\n\t\t\t\t\tfinalKind: baseKind,\n\t\t\t\t\tverb,\n\t\t\t\t\tresolved: false,\n\t\t\t\t\tfailed: false,\n\t\t\t\t};\n\t\t\t\tactionFacts.push(fact);\n\t\t\t\tconst index = actionFacts.length - 1;\n\t\t\t\tpendingByOrder.push(index);\n\t\t\t\tif (fact.id) {\n\t\t\t\t\tconst bucket = pendingById.get(fact.id) ?? [];\n\t\t\t\t\tbucket.push(index);\n\t\t\t\t\tpendingById.set(fact.id, bucket);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (message.role === \"toolResult\") {\n\t\t\tconst toolCallId = (message as { toolCallId?: string }).toolCallId;\n\t\t\tconst toolName = (message as { toolName?: string }).toolName;\n\t\t\tlet matchedIndex: number | undefined;\n\n\t\t\tif (toolCallId) {\n\t\t\t\tconst bucket = pendingById.get(toolCallId);\n\t\t\t\tif (bucket && bucket.length > 0) {\n\t\t\t\t\tmatchedIndex = bucket.shift();\n\t\t\t\t\tif (bucket.length === 0) {\n\t\t\t\t\t\tpendingById.delete(toolCallId);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (matchedIndex === undefined && toolName) {\n\t\t\t\tfor (const index of pendingByOrder) {\n\t\t\t\t\tconst candidate = actionFacts[index];\n\t\t\t\t\tif (!candidate.resolved && candidate.name === toolName) {\n\t\t\t\t\t\tmatchedIndex = index;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (matchedIndex !== undefined) {\n\t\t\t\tconst fact = actionFacts[matchedIndex];\n\t\t\t\tconst resultText = messageToText(message);\n\t\t\t\tconst failed = isFailureToolResult(message, resultText);\n\t\t\t\tfact.resolved = true;\n\t\t\t\tfact.failed = failed;\n\t\t\t\tif (!failed && fact.baseKind === \"modified\" && appearsCreated(message)) {\n\t\t\t\t\tfact.finalKind = \"created\";\n\t\t\t\t}\n\n\t\t\t\tif (!failed && fact.path && fact.finalKind && !isHarnessPlumbingTarget(fact.path)) {\n\t\t\t\t\tconst existing = filesByPath.get(fact.path);\n\t\t\t\t\tconst nextKind = fact.finalKind;\n\t\t\t\t\tconst note = fact.verb;\n\t\t\t\t\tif (!existing || FILE_KIND_PRIORITY[nextKind] > FILE_KIND_PRIORITY[existing.kind]) {\n\t\t\t\t\t\tfilesByPath.set(fact.path, { path: fact.path, kind: nextKind, note, lastTouch: i });\n\t\t\t\t\t} else if (existing.kind === nextKind) {\n\t\t\t\t\t\texisting.note = note;\n\t\t\t\t\t\texisting.lastTouch = i;\n\t\t\t\t\t} else {\n\t\t\t\t\t\texisting.lastTouch = i;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst key = operationKey(fact.name, fact.path);\n\t\t\t\tif (failed && isOpenProblemTool(fact.name)) {\n\t\t\t\t\topenErrors.set(key, {\n\t\t\t\t\t\toperation: operationLabel(fact.name, fact.path),\n\t\t\t\t\t\terror: firstErrorLine(resultText),\n\t\t\t\t\t\tlastTouch: i,\n\t\t\t\t\t});\n\t\t\t\t} else if (!failed) {\n\t\t\t\t\topenErrors.delete(key);\n\t\t\t\t}\n\n\t\t\t\tconst pendingPos = pendingByOrder.indexOf(matchedIndex);\n\t\t\t\tif (pendingPos >= 0) {\n\t\t\t\t\tpendingByOrder.splice(pendingPos, 1);\n\t\t\t\t}\n\t\t\t\tif (toolCallId) {\n\t\t\t\t\tconst bucket = pendingById.get(toolCallId);\n\t\t\t\t\tif (bucket) {\n\t\t\t\t\t\tconst pos = bucket.indexOf(matchedIndex);\n\t\t\t\t\t\tif (pos >= 0) {\n\t\t\t\t\t\t\tbucket.splice(pos, 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (bucket.length === 0) {\n\t\t\t\t\t\t\tpendingById.delete(toolCallId);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (const action of actionFacts) {\n\t\tif (isHarnessPlumbingTarget(action.path)) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (action.resolved && action.failed && action.name !== \"bash\") {\n\t\t\tcontinue;\n\t\t}\n\t\tif ((!action.resolved || !action.failed) && action.finalKind && action.path && !filesByPath.has(action.path)) {\n\t\t\tfilesByPath.set(action.path, {\n\t\t\t\tpath: action.path,\n\t\t\t\tkind: action.finalKind,\n\t\t\t\tnote: action.verb,\n\t\t\t\tlastTouch: actionFacts.indexOf(action),\n\t\t\t});\n\t\t}\n\n\t\tactions.push(`${action.verb} ${action.path ?? \"(unknown)\"}`);\n\t}\n\n\tfor (const file of filesByPath.values()) {\n\t\tif (!file.note && filesNotes.has(file.path)) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (file.note && filesNotes.get(file.path) === file.note) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (file.note) {\n\t\t\tfilesNotes.set(file.path, file.note);\n\t\t}\n\t}\n\n\tfor (const file of filesByPath.values()) {\n\t\tconst suffix = filesNotes.get(file.path);\n\t\tif (suffix) {\n\t\t\tfile.note = suffix;\n\t\t}\n\t}\n\n\tconst files = Array.from(filesByPath.values())\n\t\t.sort(\n\t\t\t(a, b) =>\n\t\t\t\tb.lastTouch - a.lastTouch ||\n\t\t\t\tFILE_KIND_PRIORITY[b.kind] - FILE_KIND_PRIORITY[a.kind] ||\n\t\t\t\ta.path.localeCompare(b.path),\n\t\t)\n\t\t.map(({ lastTouch: _lastTouch, ...file }) => file);\n\n\treturn {\n\t\tfiles,\n\t\tworkingSet: files.slice(0, MAX_WORKING_SET_FILES),\n\t\tactions: dedupeMostRecent(actions).slice(-MAX_ACTIONS),\n\t\terrorFacts: Array.from(openErrors.values())\n\t\t\t.sort((a, b) => a.lastTouch - b.lastTouch)\n\t\t\t.slice(-MAX_ERROR_FACTS)\n\t\t\t.map(({ lastTouch: _lastTouch, ...error }) => error),\n\t\tprohibitions: prohibitions.slice(-MAX_PROHIBITIONS),\n\t\tcancelledText: cancelledParts.join(\"\\n\"),\n\t\tactiveTaskSource,\n\t\tdelegatedWorkerFacts,\n\t};\n}\n\nfunction dedupeMostRecent(values: string[]): string[] {\n\tconst seen = new Set<string>();\n\tconst kept: string[] = [];\n\tfor (let i = values.length - 1; i >= 0; i--) {\n\t\tconst value = values[i];\n\t\tif (seen.has(value)) {\n\t\t\tcontinue;\n\t\t}\n\t\tseen.add(value);\n\t\tkept.push(value);\n\t}\n\treturn kept.reverse();\n}\n\nexport function renderFactsBlock(facts: CompactionFacts): string {\n\tconst lines: string[] = [\"verification demands:\"];\n\tlines.push(\"files-modified-recall (must appear in ## Files):\");\n\tfor (const file of facts.files.filter((file) => file.kind !== \"read\")) {\n\t\tlines.push(file.path);\n\t}\n\tlines.push(\"files-read-recall (must appear in ## Files, containment threshold applies):\");\n\tfor (const file of facts.files.filter((file) => file.kind === \"read\")) {\n\t\tlines.push(file.path);\n\t}\n\tlines.push(\"working-set-recall (must appear in ## Working Set):\");\n\tfor (const file of facts.workingSet) {\n\t\tlines.push(`${file.path} — ${file.note || file.kind}`);\n\t}\n\tlines.push(\"open-errors-recall (must appear in ## Open Problems):\");\n\tfor (const error of facts.errorFacts) {\n\t\tlines.push(`${error.operation}: ${error.error}`);\n\t}\n\tlines.push(\"actions-recall (must appear in ## Done):\");\n\tfor (const action of facts.actions) {\n\t\tlines.push(action);\n\t}\n\tlines.push(\"mandatory-rules-recall (must appear in ### Mandatory Rules):\");\n\tfor (const prohibition of facts.prohibitions) {\n\t\tlines.push(prohibition);\n\t}\n\t// The active-task gate demands near-verbatim recall of this text, but the conversation the\n\t// summarizer sees may be pre-digested or truncated — the facts block is the one channel\n\t// guaranteed to reach the prompt, so the gated text must ride in it (bounded).\n\tlines.push(\"active-task-containment (must appear in ## Active Task):\");\n\tif (facts.activeTaskSource) {\n\t\tlines.push(clampText(facts.activeTaskSource, ACTIVE_TASK_SOURCE_MAX_CHARS));\n\t}\n\tlines.push(\"cancelled-work-dropped (must NOT appear outside ### Mandatory Rules):\");\n\tif (facts.cancelledText) {\n\t\tlines.push(facts.cancelledText);\n\t}\n\treturn lines.join(\"\\n\");\n}\n"]}
|
|
1
|
+
{"version":3,"file":"extraction.js","sourceRoot":"","sources":["../../src/compaction/extraction.ts"],"names":[],"mappings":"AA4CA,MAAM,mBAAmB,GAAG,iEAAiE,CAAC;AAC9F,+FAA+F;AAC/F,uFAAqF;AACrF,oEAAoE;AACpE,MAAM,gBAAgB,GACrB,mHAAmH,CAAC;AAErH,oFAAoF;AACpF,MAAM,4BAA4B,GAAG,KAAK,CAAC;AAC3C,wGAAwG;AACxG,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAC3B,mGAAmG;AACnG,MAAM,WAAW,GAAG,EAAE,CAAC;AACvB,MAAM,qBAAqB,GAAG,CAAC,CAAC;AAChC,MAAM,eAAe,GAAG,CAAC,CAAC;AAC1B,MAAM,oBAAoB,GAAG,GAAG,CAAC;AACjC,MAAM,wBAAwB,GAAG,EAAE,CAAC;AACpC,MAAM,0BAA0B,GAAG,CAAC,CAAC;AACrC,MAAM,+BAA+B,GAAG,GAAG,CAAC;AAC5C,MAAM,kCAAkC,GAAG,GAAG,CAAC;AAC/C,2GAA2G;AAC3G,MAAM,CAAC,MAAM,4BAA4B,GAAG,KAAK,CAAC;AAElD,MAAM,kBAAkB,GAA2D;IAClF,IAAI,EAAE,CAAC;IACP,OAAO,EAAE,CAAC;IACV,QAAQ,EAAE,CAAC;CACX,CAAC;AAEF,MAAM,iBAAiB,GAA2D;IACjF,IAAI,EAA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a,EAAE,CAAC;QACzB,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,aAAa,CAAC,CAAC;IACjC,CAAC;IACD,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAAA,CACxB","sourcesContent":["import type { SessionEntry } from \"../session/session-manager.ts\";\nimport type { AgentMessage } from \"../types.ts\";\n\nexport interface CompactionFileFact {\n\tpath: string;\n\tkind: \"modified\" | \"created\" | \"read\";\n\tnote: string;\n}\n\nexport interface CompactionErrorFact {\n\toperation: string;\n\terror: string;\n}\n\nexport interface CompactionDelegatedWorkerFact {\n\t/** Worker-authored text is evidence for the parent, never a verified decision or completion claim. */\n\ttrust: \"UNTRUSTED\";\n\ttask: string;\n\tsummary: string;\n}\n\nexport interface CompactionFacts {\n\tfiles: CompactionFileFact[];\n\tworkingSet: CompactionFileFact[];\n\tactions: string[];\n\terrorFacts: CompactionErrorFact[];\n\tprohibitions: string[];\n\tcancelledText: string;\n\tactiveTaskSource: string;\n\t/** Latest-first worker evidence retained only by deterministic checkpoints. */\n\tdelegatedWorkerFacts?: CompactionDelegatedWorkerFact[];\n}\n\ninterface ToolCallFact {\n\tid: string | undefined;\n\tname: string;\n\tpath: string | undefined;\n\tbaseKind: \"modified\" | \"created\" | \"read\" | null;\n\tfinalKind: \"modified\" | \"created\" | \"read\" | null;\n\tverb: string;\n\tresolved: boolean;\n\tfailed: boolean;\n}\n\nconst PROHIBITION_PATTERN = /\\b(do not|don't|never|stop (?:doing|using|changing)|no more)\\b/i;\n// Deliberately narrow: a bare \"stop\" (\"stop the server and rerun\") is everyday phrasing, not a\n// reversal of the prior work — matching it marked whole turns cancelled and made the\n// cancelled-work gate fight the recall gates (2026-07-06 incident).\nconst REVERSAL_PATTERN =\n\t/\\b(undo|revert|roll back|never mind|scrap that|forget (?:it|that)|stop (?:that|this|it|everything|working on))\\b/i;\n\n/** User messages longer than this are documents/pastes, not spoken prohibitions. */\nconst PROHIBITION_SOURCE_MAX_CHARS = 1_500;\n/** Upper bound on gate-demanded rules; most recent win (same bounding rationale as Done carry-over). */\nconst MAX_PROHIBITIONS = 8;\n/** Upper bound on gate-demanded actions; mirrors the prompt's \"15 most recent Done items\" rule. */\nconst MAX_ACTIONS = 15;\nconst MAX_WORKING_SET_FILES = 8;\nconst MAX_ERROR_FACTS = 5;\nconst ERROR_LINE_MAX_CHARS = 160;\nconst COMMAND_PREFIX_MAX_CHARS = 80;\nconst MAX_DELEGATED_WORKER_FACTS = 4;\nconst DELEGATED_WORKER_TASK_MAX_CHARS = 240;\nconst DELEGATED_WORKER_SUMMARY_MAX_CHARS = 600;\n/** Shared clamp for the active-task text because verification can only demand what the prompt receives. */\nexport const ACTIVE_TASK_SOURCE_MAX_CHARS = 4_000;\n\nconst FILE_KIND_PRIORITY: Record<NonNullable<ToolCallFact[\"finalKind\"]>, number> = {\n\tread: 1,\n\tcreated: 2,\n\tmodified: 3,\n};\n\nconst TOOL_KIND_BY_NAME: Record<string, \"modified\" | \"created\" | \"read\" | null> = {\n\tread: \"read\",\n\tgrep: \"read\",\n\tfind: \"read\",\n\twrite: \"modified\",\n\tedit: \"modified\",\n\tbash: null,\n};\n\nconst TOOL_VERB_BY_NAME: Record<string, string> = {\n\twrite: \"WRITE\",\n\tedit: \"EDIT\",\n\tbash: \"RUN\",\n\tread: \"READ\",\n\tgrep: \"READ\",\n\tfind: \"READ\",\n};\n\nfunction messageToText(message: AgentMessage): string {\n\tconst rawContent = (message as { content?: unknown }).content;\n\tif (typeof rawContent === \"string\") {\n\t\treturn rawContent;\n\t}\n\tif (!Array.isArray(rawContent)) {\n\t\treturn \"\";\n\t}\n\n\tconst parts: string[] = [];\n\tfor (const block of rawContent) {\n\t\tif (!block || typeof block !== \"object\") {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif ((block as { type?: unknown }).type === \"text\" && typeof (block as { text?: unknown }).text === \"string\") {\n\t\t\tparts.push((block as { text: string }).text);\n\t\t}\n\t}\n\treturn (parts.length === 1 ? parts[0] : parts.join(\" \")).trim();\n}\n\nfunction assistantToolCallTarget(name: string, rawArgs: unknown): string | undefined {\n\tif (!rawArgs || typeof rawArgs !== \"object\") {\n\t\treturn undefined;\n\t}\n\tconst args = rawArgs as Record<string, unknown>;\n\n\tif (\n\t\t(name === \"read\" || name === \"grep\" || name === \"find\" || name === \"write\" || name === \"edit\") &&\n\t\ttypeof args.path === \"string\" &&\n\t\targs.path.length > 0\n\t) {\n\t\treturn args.path;\n\t}\n\n\tif (name === \"bash\" && typeof args.command === \"string\" && args.command.length > 0) {\n\t\treturn args.command;\n\t}\n\n\treturn undefined;\n}\n\nfunction clampText(text: string, maxLen: number): string {\n\treturn text.length > maxLen ? text.slice(0, maxLen) : text;\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\nfunction normalizeDelegatedWorkerText(text: string, maxLen: number): string {\n\tlet normalized = \"\";\n\tfor (const match of text.matchAll(/\\S+/g)) {\n\t\tconst separator = normalized.length > 0 ? \" \" : \"\";\n\t\tconst remaining = maxLen - normalized.length - separator.length;\n\t\tif (remaining <= 0) break;\n\t\tnormalized += `${separator}${match[0].slice(0, remaining)}`;\n\t\tif (match[0].length >= remaining) break;\n\t}\n\treturn normalized;\n}\n\nfunction extractDelegatedWorkerFact(entry: SessionEntry): CompactionDelegatedWorkerFact | undefined {\n\tif (entry.type !== \"custom\" || entry.customType !== \"worker_result\" || !isPlainRecord(entry.data)) {\n\t\treturn undefined;\n\t}\n\tif (entry.data.version !== 1 || !isPlainRecord(entry.data.result)) return undefined;\n\n\tconst result = entry.data.result;\n\tif (typeof result.requestId !== \"string\" || typeof result.summary !== \"string\") return undefined;\n\tif (typeof result.status !== \"string\" || ![\"completed\", \"blocked\", \"failed\", \"cancelled\"].includes(result.status)) {\n\t\treturn undefined;\n\t}\n\tif (!Array.isArray(result.changedFiles) || !result.changedFiles.every((file) => typeof file === \"string\")) {\n\t\treturn undefined;\n\t}\n\n\tconst request = entry.data.request;\n\tconst instructions =\n\t\tisPlainRecord(request) && typeof request.instructions === \"string\" ? request.instructions : undefined;\n\tconst task = normalizeDelegatedWorkerText(\n\t\tinstructions ?? `Worker request ${result.requestId}`,\n\t\tDELEGATED_WORKER_TASK_MAX_CHARS,\n\t);\n\tconst summary = normalizeDelegatedWorkerText(result.summary, DELEGATED_WORKER_SUMMARY_MAX_CHARS);\n\n\treturn {\n\t\ttrust: \"UNTRUSTED\",\n\t\ttask: task || \"(empty task)\",\n\t\tsummary: summary || \"(empty summary)\",\n\t};\n}\n\nfunction extractDelegatedWorkerFacts(\n\tentries: readonly SessionEntry[],\n\tstart: number,\n\tend: number,\n): CompactionDelegatedWorkerFact[] {\n\tconst facts: CompactionDelegatedWorkerFact[] = [];\n\tfor (let i = end - 1; i >= start && facts.length < MAX_DELEGATED_WORKER_FACTS; i--) {\n\t\tconst fact = extractDelegatedWorkerFact(entries[i]);\n\t\tif (fact) facts.push(fact);\n\t}\n\treturn facts;\n}\n\nfunction appearsCreated(message: AgentMessage): boolean {\n\tif (message.role !== \"toolResult\") {\n\t\treturn false;\n\t}\n\n\tconst text = messageToText(message).toLowerCase();\n\tif (/(\\bnew file\\b|\\bcreated\\b|\\bcreated file\\b)/.test(text)) {\n\t\treturn true;\n\t}\n\n\tconst details = (message as { details?: unknown }).details;\n\tif (!details || typeof details !== \"object\") {\n\t\treturn false;\n\t}\n\n\tif (typeof (details as { created?: unknown }).created === \"boolean\") {\n\t\treturn (details as { created: boolean }).created;\n\t}\n\tif (typeof (details as { isCreated?: unknown }).isCreated === \"boolean\") {\n\t\treturn (details as { isCreated: boolean }).isCreated;\n\t}\n\tif (typeof (details as { isNewFile?: unknown }).isNewFile === \"boolean\") {\n\t\treturn (details as { isNewFile: boolean }).isNewFile;\n\t}\n\n\treturn false;\n}\n\nfunction splitSentenceLines(text: string): string[] {\n\treturn text\n\t\t.split(/(?<=[.!?])\\s+|\\n+/)\n\t\t.map((line) => line.trim().replace(/[.!?]+$/, \"\"))\n\t\t.filter(Boolean);\n}\n\nfunction getMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tswitch (entry.type) {\n\t\tcase \"message\":\n\t\t\treturn entry.message;\n\t\tcase \"custom_message\":\n\t\t\treturn {\n\t\t\t\trole: \"custom\",\n\t\t\t\tcustomType: entry.customType,\n\t\t\t\tcontent: entry.content,\n\t\t\t\tdetails: entry.details,\n\t\t\t\tdisplay: entry.display,\n\t\t\t\ttimestamp: new Date(entry.timestamp).getTime(),\n\t\t\t};\n\t\tcase \"branch_summary\":\n\t\t\treturn {\n\t\t\t\trole: \"branchSummary\",\n\t\t\t\tsummary: entry.summary,\n\t\t\t\tfromId: entry.fromId,\n\t\t\t\ttimestamp: new Date(entry.timestamp).getTime(),\n\t\t\t};\n\t\tcase \"compaction\":\n\t\t\treturn undefined;\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n}\n\nfunction isToolCallBlock(block: unknown): block is { type: \"toolCall\"; id?: string; name: string; arguments: unknown } {\n\tif (!block || typeof block !== \"object\") {\n\t\treturn false;\n\t}\n\tif ((block as { type?: unknown }).type !== \"toolCall\") {\n\t\treturn false;\n\t}\n\tif (typeof (block as { name?: unknown }).name !== \"string\") {\n\t\treturn false;\n\t}\n\tif (!(block as { arguments?: unknown }).arguments) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nfunction toolCallVerb(name: string): string {\n\treturn TOOL_VERB_BY_NAME[name] ?? name.toUpperCase();\n}\n\nfunction isHarnessPlumbingTarget(target: string | undefined): boolean {\n\tif (!target) return false;\n\treturn (\n\t\ttarget.includes(\"/.pi/agent/context-gc/\") ||\n\t\ttarget.includes(\"~/.pi/agent/context-gc/\") ||\n\t\t/\\/tmp\\/pi-bash-[^\\s]+\\.log\\b/.test(target)\n\t);\n}\n\nfunction normalizeOperationTarget(toolName: string, path: string | undefined): string {\n\tif (!path) return \"(unknown)\";\n\tif (toolName !== \"bash\") return path;\n\treturn clampText(path.replace(/\\s+/g, \" \").trim(), COMMAND_PREFIX_MAX_CHARS);\n}\n\nfunction operationKey(toolName: string, path: string | undefined): string {\n\treturn `${toolName}:${normalizeOperationTarget(toolName, path)}`;\n}\n\nfunction operationLabel(toolName: string, path: string | undefined): string {\n\treturn `${toolCallVerb(toolName)} ${normalizeOperationTarget(toolName, path)}`;\n}\n\nfunction resultExitCode(message: AgentMessage): number | undefined {\n\tconst details = (message as { details?: unknown }).details;\n\tif (!details || typeof details !== \"object\") return undefined;\n\tconst raw = (details as { exitCode?: unknown }).exitCode;\n\tif (typeof raw === \"number\" && Number.isFinite(raw)) return raw;\n\tif (typeof raw === \"string\" && /^\\d+$/.test(raw)) return Number(raw);\n\treturn undefined;\n}\n\nfunction isOutcomeBearingTool(toolName: string | undefined): boolean {\n\treturn toolName === \"bash\";\n}\n\nfunction isOpenProblemTool(toolName: string | undefined): boolean {\n\treturn toolName === \"bash\" || toolName === \"edit\" || toolName === \"write\";\n}\n\nfunction failureSignalLine(text: string): string | undefined {\n\treturn text\n\t\t.split(/\\r?\\n/)\n\t\t.map((part) => part.trim())\n\t\t.find((line) => /exited with code [1-9]\\d*/i.test(line) || /^(error|fatal|✗|FAIL)\\b/i.test(line));\n}\n\nfunction firstErrorLine(text: string): string {\n\tconst line =\n\t\tfailureSignalLine(text) ??\n\t\ttext\n\t\t\t.split(/\\r?\\n/)\n\t\t\t.map((part) => part.trim())\n\t\t\t.find(Boolean);\n\treturn clampText(line ?? \"failed\", ERROR_LINE_MAX_CHARS);\n}\n\nfunction isFailureToolResult(message: AgentMessage, text: string): boolean {\n\tif (message.role !== \"toolResult\") return false;\n\tif ((message as { isError?: unknown }).isError === true) return true;\n\tconst exitCode = resultExitCode(message);\n\tif (exitCode !== undefined) return exitCode !== 0;\n\tconst toolName = (message as { toolName?: unknown }).toolName;\n\treturn typeof toolName === \"string\" && isOutcomeBearingTool(toolName) && failureSignalLine(text) !== undefined;\n}\n\nexport function extractCompactionFacts(entries: SessionEntry[], start: number, end: number): CompactionFacts {\n\tconst rangeStart = Math.max(0, start);\n\tconst rangeEnd = Math.min(entries.length, Math.max(rangeStart, end));\n\n\tif (rangeStart >= rangeEnd) {\n\t\treturn {\n\t\t\tfiles: [],\n\t\t\tworkingSet: [],\n\t\t\tactions: [],\n\t\t\terrorFacts: [],\n\t\t\tprohibitions: [],\n\t\t\tcancelledText: \"\",\n\t\t\tactiveTaskSource: \"\",\n\t\t\tdelegatedWorkerFacts: [],\n\t\t};\n\t}\n\tconst delegatedWorkerFacts = extractDelegatedWorkerFacts(entries, rangeStart, rangeEnd);\n\n\tconst filesByPath = new Map<string, CompactionFileFact & { lastTouch: number }>();\n\tconst filesNotes = new Map<string, string>();\n\tconst seenProhibitions = new Set<string>();\n\tconst actionFacts: ToolCallFact[] = [];\n\tconst pendingById = new Map<string, number[]>();\n\tconst pendingByOrder: number[] = [];\n\n\tconst actions: string[] = [];\n\tconst openErrors = new Map<string, CompactionErrorFact & { lastTouch: number }>();\n\tconst prohibitions: string[] = [];\n\tlet activeTaskSource = \"\";\n\tconst cancelledParts: string[] = [];\n\tconst sinceLastUser: string[] = [];\n\n\tfor (let i = rangeStart; i < rangeEnd; i++) {\n\t\tconst message = getMessageFromEntry(entries[i]);\n\t\tif (!message) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (message.role === \"user\") {\n\t\t\tconst userText = messageToText(message);\n\t\t\tif (REVERSAL_PATTERN.test(userText)) {\n\t\t\t\tcancelledParts.push(...sinceLastUser);\n\t\t\t}\n\t\t\tsinceLastUser.length = 0;\n\n\t\t\tif (userText) {\n\t\t\t\tactiveTaskSource = clampText(userText, ACTIVE_TASK_SOURCE_MAX_CHARS);\n\t\t\t\t// Mandatory Rules exist for SPOKEN durable prohibitions (\"do not touch X\"), not for\n\t\t\t\t// documents. A long pasted text (plan, instruction file) can contain dozens of\n\t\t\t\t// \"never/do not\" lines; harvesting them makes the verification gate demand the\n\t\t\t\t// checkpoint reproduce the document (2026-07-06 field incident: 13 fragment rules\n\t\t\t\t// extracted from one pasted instruction). Documents live on disk; skip them here.\n\t\t\t\tif (userText.length <= PROHIBITION_SOURCE_MAX_CHARS) {\n\t\t\t\t\tfor (const sentence of splitSentenceLines(userText)) {\n\t\t\t\t\t\tif (!PROHIBITION_PATTERN.test(sentence)) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst normalized = clampText(sentence, 160);\n\t\t\t\t\t\tconst dedupeKey = normalized.toLowerCase();\n\t\t\t\t\t\tif (!seenProhibitions.has(dedupeKey)) {\n\t\t\t\t\t\t\tseenProhibitions.add(dedupeKey);\n\t\t\t\t\t\t\tprohibitions.push(normalized);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (message.role === \"assistant\" || message.role === \"toolResult\") {\n\t\t\tconst messageText = messageToText(message);\n\t\t\tif (messageText) {\n\t\t\t\tsinceLastUser.push(messageText);\n\t\t\t}\n\t\t}\n\n\t\tif (message.role === \"assistant\" && Array.isArray(message.content)) {\n\t\t\tfor (const block of message.content) {\n\t\t\t\tif (!isToolCallBlock(block)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst name = block.name;\n\t\t\t\tconst verb = toolCallVerb(name);\n\t\t\t\tconst path = assistantToolCallTarget(name, block.arguments);\n\t\t\t\tconst baseKind = TOOL_KIND_BY_NAME[name] ?? null;\n\t\t\t\tconst fact: ToolCallFact = {\n\t\t\t\t\tid: block.id,\n\t\t\t\t\tname,\n\t\t\t\t\tpath,\n\t\t\t\t\tbaseKind,\n\t\t\t\t\tfinalKind: baseKind,\n\t\t\t\t\tverb,\n\t\t\t\t\tresolved: false,\n\t\t\t\t\tfailed: false,\n\t\t\t\t};\n\t\t\t\tactionFacts.push(fact);\n\t\t\t\tconst index = actionFacts.length - 1;\n\t\t\t\tpendingByOrder.push(index);\n\t\t\t\tif (fact.id) {\n\t\t\t\t\tconst bucket = pendingById.get(fact.id) ?? [];\n\t\t\t\t\tbucket.push(index);\n\t\t\t\t\tpendingById.set(fact.id, bucket);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (message.role === \"toolResult\") {\n\t\t\tconst toolCallId = (message as { toolCallId?: string }).toolCallId;\n\t\t\tconst toolName = (message as { toolName?: string }).toolName;\n\t\t\tlet matchedIndex: number | undefined;\n\n\t\t\tif (toolCallId) {\n\t\t\t\tconst bucket = pendingById.get(toolCallId);\n\t\t\t\tif (bucket && bucket.length > 0) {\n\t\t\t\t\tmatchedIndex = bucket.shift();\n\t\t\t\t\tif (bucket.length === 0) {\n\t\t\t\t\t\tpendingById.delete(toolCallId);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (matchedIndex === undefined && toolName) {\n\t\t\t\tfor (const index of pendingByOrder) {\n\t\t\t\t\tconst candidate = actionFacts[index];\n\t\t\t\t\tif (!candidate.resolved && candidate.name === toolName) {\n\t\t\t\t\t\tmatchedIndex = index;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (matchedIndex !== undefined) {\n\t\t\t\tconst fact = actionFacts[matchedIndex];\n\t\t\t\tconst resultText = messageToText(message);\n\t\t\t\tconst failed = isFailureToolResult(message, resultText);\n\t\t\t\tfact.resolved = true;\n\t\t\t\tfact.failed = failed;\n\t\t\t\tif (!failed && fact.baseKind === \"modified\" && appearsCreated(message)) {\n\t\t\t\t\tfact.finalKind = \"created\";\n\t\t\t\t}\n\n\t\t\t\tif (!failed && fact.path && fact.finalKind && !isHarnessPlumbingTarget(fact.path)) {\n\t\t\t\t\tconst existing = filesByPath.get(fact.path);\n\t\t\t\t\tconst nextKind = fact.finalKind;\n\t\t\t\t\tconst note = fact.verb;\n\t\t\t\t\tif (!existing || FILE_KIND_PRIORITY[nextKind] > FILE_KIND_PRIORITY[existing.kind]) {\n\t\t\t\t\t\tfilesByPath.set(fact.path, { path: fact.path, kind: nextKind, note, lastTouch: i });\n\t\t\t\t\t} else if (existing.kind === nextKind) {\n\t\t\t\t\t\texisting.note = note;\n\t\t\t\t\t\texisting.lastTouch = i;\n\t\t\t\t\t} else {\n\t\t\t\t\t\texisting.lastTouch = i;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst key = operationKey(fact.name, fact.path);\n\t\t\t\tif (failed && isOpenProblemTool(fact.name)) {\n\t\t\t\t\topenErrors.set(key, {\n\t\t\t\t\t\toperation: operationLabel(fact.name, fact.path),\n\t\t\t\t\t\terror: firstErrorLine(resultText),\n\t\t\t\t\t\tlastTouch: i,\n\t\t\t\t\t});\n\t\t\t\t} else if (!failed) {\n\t\t\t\t\topenErrors.delete(key);\n\t\t\t\t}\n\n\t\t\t\tconst pendingPos = pendingByOrder.indexOf(matchedIndex);\n\t\t\t\tif (pendingPos >= 0) {\n\t\t\t\t\tpendingByOrder.splice(pendingPos, 1);\n\t\t\t\t}\n\t\t\t\tif (toolCallId) {\n\t\t\t\t\tconst bucket = pendingById.get(toolCallId);\n\t\t\t\t\tif (bucket) {\n\t\t\t\t\t\tconst pos = bucket.indexOf(matchedIndex);\n\t\t\t\t\t\tif (pos >= 0) {\n\t\t\t\t\t\t\tbucket.splice(pos, 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (bucket.length === 0) {\n\t\t\t\t\t\t\tpendingById.delete(toolCallId);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (const action of actionFacts) {\n\t\tif (isHarnessPlumbingTarget(action.path)) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (action.resolved && action.failed && action.name !== \"bash\") {\n\t\t\tcontinue;\n\t\t}\n\t\tif ((!action.resolved || !action.failed) && action.finalKind && action.path && !filesByPath.has(action.path)) {\n\t\t\tfilesByPath.set(action.path, {\n\t\t\t\tpath: action.path,\n\t\t\t\tkind: action.finalKind,\n\t\t\t\tnote: action.verb,\n\t\t\t\tlastTouch: actionFacts.indexOf(action),\n\t\t\t});\n\t\t}\n\n\t\tactions.push(`${action.verb} ${action.path ?? \"(unknown)\"}`);\n\t}\n\n\tfor (const file of filesByPath.values()) {\n\t\tif (!file.note && filesNotes.has(file.path)) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (file.note && filesNotes.get(file.path) === file.note) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (file.note) {\n\t\t\tfilesNotes.set(file.path, file.note);\n\t\t}\n\t}\n\n\tfor (const file of filesByPath.values()) {\n\t\tconst suffix = filesNotes.get(file.path);\n\t\tif (suffix) {\n\t\t\tfile.note = suffix;\n\t\t}\n\t}\n\n\tconst files = Array.from(filesByPath.values())\n\t\t.sort(\n\t\t\t(a, b) =>\n\t\t\t\tb.lastTouch - a.lastTouch ||\n\t\t\t\tFILE_KIND_PRIORITY[b.kind] - FILE_KIND_PRIORITY[a.kind] ||\n\t\t\t\ta.path.localeCompare(b.path),\n\t\t)\n\t\t.map(({ lastTouch: _lastTouch, ...file }) => file);\n\n\treturn {\n\t\tfiles,\n\t\tworkingSet: files.slice(0, MAX_WORKING_SET_FILES),\n\t\tactions: dedupeMostRecent(actions).slice(-MAX_ACTIONS),\n\t\terrorFacts: Array.from(openErrors.values())\n\t\t\t.sort((a, b) => a.lastTouch - b.lastTouch)\n\t\t\t.slice(-MAX_ERROR_FACTS)\n\t\t\t.map(({ lastTouch: _lastTouch, ...error }) => error),\n\t\tprohibitions: prohibitions.slice(-MAX_PROHIBITIONS),\n\t\tcancelledText: cancelledParts.join(\"\\n\"),\n\t\tactiveTaskSource,\n\t\tdelegatedWorkerFacts,\n\t};\n}\n\nfunction dedupeMostRecent(values: string[]): string[] {\n\tconst seen = new Set<string>();\n\tconst kept: string[] = [];\n\tfor (let i = values.length - 1; i >= 0; i--) {\n\t\tconst value = values[i];\n\t\tif (seen.has(value)) {\n\t\t\tcontinue;\n\t\t}\n\t\tseen.add(value);\n\t\tkept.push(value);\n\t}\n\treturn kept.reverse();\n}\n\nexport function renderFactsBlock(facts: CompactionFacts): string {\n\tconst lines: string[] = [\"verification demands:\"];\n\tlines.push(\"files-modified-recall (must appear in ## Files):\");\n\tfor (const file of facts.files.filter((file) => file.kind !== \"read\")) {\n\t\tlines.push(file.path);\n\t}\n\tlines.push(\"files-read-recall (must appear in ## Files, containment threshold applies):\");\n\tfor (const file of facts.files.filter((file) => file.kind === \"read\")) {\n\t\tlines.push(file.path);\n\t}\n\tlines.push(\"working-set-recall (must appear in ## Working Set):\");\n\tfor (const file of facts.workingSet) {\n\t\tlines.push(`${file.path} — ${file.note || file.kind}`);\n\t}\n\tlines.push(\"open-errors-recall (must appear in ## Open Problems):\");\n\tfor (const error of facts.errorFacts) {\n\t\tlines.push(`${error.operation}: ${error.error}`);\n\t}\n\tlines.push(\"actions-recall (must appear in ## Done):\");\n\tfor (const action of facts.actions) {\n\t\tlines.push(action);\n\t}\n\tlines.push(\"mandatory-rules-recall (must appear in ### Mandatory Rules):\");\n\tfor (const prohibition of facts.prohibitions) {\n\t\tlines.push(prohibition);\n\t}\n\t// The active-task gate demands near-verbatim recall of this text, but the conversation the\n\t// summarizer sees may be pre-digested or truncated — the facts block is the one channel\n\t// guaranteed to reach the prompt, so the gated text must ride in it (bounded).\n\tlines.push(\"active-task-containment (must appear in ## Active Task):\");\n\tif (facts.activeTaskSource) {\n\t\tlines.push(clampText(facts.activeTaskSource, ACTIVE_TASK_SOURCE_MAX_CHARS));\n\t}\n\tlines.push(\"cancelled-work-dropped (must NOT appear outside ### Mandatory Rules):\");\n\tif (facts.cancelledText) {\n\t\tlines.push(facts.cancelledText);\n\t}\n\treturn lines.join(\"\\n\");\n}\n"]}
|