@caupulican/pi-agent-core 0.81.2 → 0.81.3
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/compaction.d.ts +11 -2
- package/dist/compaction/compaction.d.ts.map +1 -1
- package/dist/compaction/compaction.js +258 -106
- package/dist/compaction/compaction.js.map +1 -1
- package/dist/compaction/extraction.d.ts +15 -0
- package/dist/compaction/extraction.d.ts.map +1 -0
- package/dist/compaction/extraction.js +342 -0
- package/dist/compaction/extraction.js.map +1 -0
- package/dist/compaction/index.d.ts +4 -0
- package/dist/compaction/index.d.ts.map +1 -1
- package/dist/compaction/index.js +4 -0
- package/dist/compaction/index.js.map +1 -1
- package/dist/compaction/loop.d.ts +52 -0
- package/dist/compaction/loop.d.ts.map +1 -0
- package/dist/compaction/loop.js +154 -0
- package/dist/compaction/loop.js.map +1 -0
- package/dist/compaction/token-budget.d.ts +12 -0
- package/dist/compaction/token-budget.d.ts.map +1 -0
- package/dist/compaction/token-budget.js +52 -0
- package/dist/compaction/token-budget.js.map +1 -0
- package/dist/compaction/utils.d.ts +1 -1
- package/dist/compaction/utils.d.ts.map +1 -1
- package/dist/compaction/utils.js +45 -2
- package/dist/compaction/utils.js.map +1 -1
- package/dist/compaction/verification.d.ts +20 -0
- package/dist/compaction/verification.d.ts.map +1 -0
- package/dist/compaction/verification.js +169 -0
- package/dist/compaction/verification.js.map +1 -0
- package/dist/reliability/classifier.d.ts +2 -0
- package/dist/reliability/classifier.d.ts.map +1 -1
- package/dist/reliability/classifier.js +18 -1
- package/dist/reliability/classifier.js.map +1 -1
- package/dist/reliability/index.d.ts +1 -0
- package/dist/reliability/index.d.ts.map +1 -1
- package/dist/reliability/index.js +1 -0
- package/dist/reliability/index.js.map +1 -1
- package/dist/reliability/provider-signatures.d.ts +10 -0
- package/dist/reliability/provider-signatures.d.ts.map +1 -0
- package/dist/reliability/provider-signatures.js +11 -0
- package/dist/reliability/provider-signatures.js.map +1 -0
- package/dist/reliability/retry-controller.d.ts.map +1 -1
- package/dist/reliability/retry-controller.js +1 -0
- package/dist/reliability/retry-controller.js.map +1 -1
- package/package.json +2 -2
|
@@ -7,7 +7,9 @@
|
|
|
7
7
|
import { completeSimple } from "@caupulican/pi-ai";
|
|
8
8
|
import { convertToLlm, createBranchSummaryMessage, createCompactionSummaryMessage, createCustomMessage, } from "../messages.js";
|
|
9
9
|
import { buildSessionContext } from "../session/session-manager.js";
|
|
10
|
+
import { extractCompactionFacts, renderFactsBlock } from "./extraction.js";
|
|
10
11
|
import { computeFileLists, createFileOps, extractFileOpsFromMessage, formatFileOperations, SUMMARIZATION_SYSTEM_PROMPT, serializeConversation, } from "./utils.js";
|
|
12
|
+
import { buildRetryPrompt, verifySummary } from "./verification.js";
|
|
11
13
|
/**
|
|
12
14
|
* Extract file operations from messages and previous compaction entries.
|
|
13
15
|
*/
|
|
@@ -379,76 +381,35 @@ export function findCutPoint(entries, startIndex, endIndex, keepRecentTokens) {
|
|
|
379
381
|
// ============================================================================
|
|
380
382
|
// Summarization
|
|
381
383
|
// ============================================================================
|
|
382
|
-
const SUMMARIZATION_PROMPT = `
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
##
|
|
387
|
-
[What is the user trying to accomplish? Can be multiple items if the session covers different tasks.]
|
|
388
|
-
|
|
384
|
+
const SUMMARIZATION_PROMPT = `Checkpoint the conversation above. Format from your instructions, sections in this order:
|
|
385
|
+
## Active Task
|
|
386
|
+
### Mandatory Rules
|
|
387
|
+
## Files
|
|
388
|
+
## Done
|
|
389
389
|
## Constraints & Preferences
|
|
390
|
-
- [Any constraints, preferences, or requirements mentioned by user]
|
|
391
|
-
- [Or "(none)" if none were mentioned]
|
|
392
|
-
|
|
393
|
-
## Progress
|
|
394
|
-
### Done
|
|
395
|
-
- [x] [Completed tasks/changes]
|
|
396
|
-
|
|
397
|
-
### In Progress
|
|
398
|
-
- [ ] [Current work]
|
|
399
|
-
|
|
400
|
-
### Blocked
|
|
401
|
-
- [Issues preventing progress, if any]
|
|
402
|
-
|
|
403
390
|
## Key Decisions
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
## Next Steps
|
|
407
|
-
1. [Ordered list of what should happen next]
|
|
408
|
-
|
|
391
|
+
## Blocked / Open
|
|
409
392
|
## Critical Context
|
|
410
|
-
- [Any data, examples, or references needed to continue]
|
|
411
|
-
- [Or "(none)" if not applicable]
|
|
412
|
-
|
|
413
|
-
Keep each section concise. Preserve exact file paths, function names, and error messages.`;
|
|
414
|
-
const UPDATE_SUMMARIZATION_PROMPT = `The messages above are NEW conversation messages to incorporate into the existing summary provided in <previous-summary> tags.
|
|
415
393
|
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
- UPDATE "Next Steps" based on what was accomplished
|
|
421
|
-
- PRESERVE exact file paths, function names, and error messages
|
|
422
|
-
- If something is no longer relevant, you may remove it
|
|
394
|
+
Pre-extracted facts (verified by tooling — include ALL of them, merged with what you read):
|
|
395
|
+
<facts>
|
|
396
|
+
{FACTS_BLOCK}
|
|
397
|
+
</facts>
|
|
423
398
|
|
|
424
|
-
|
|
399
|
+
Budget: ~{BUDGET} tokens. Concrete beats complete.`;
|
|
400
|
+
const UPDATE_SUMMARIZATION_PROMPT = `Update the checkpoint in <previous-summary> with the NEW turns above. RULES:
|
|
401
|
+
- PRESERVE every existing ### Mandatory Rules bullet VERBATIM; append new ones.
|
|
402
|
+
- Continue the ## Done numbering; move finished work from Blocked/Open.
|
|
403
|
+
- Update ## Active Task to the newest unfulfilled user input; apply the cancellation rule.
|
|
404
|
+
- Keep ## Files current (add new, keep still-relevant, drop obsolete).
|
|
405
|
+
- Preserve exact paths, commands, errors.
|
|
425
406
|
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
- [Preserve existing, add new ones discovered]
|
|
431
|
-
|
|
432
|
-
## Progress
|
|
433
|
-
### Done
|
|
434
|
-
- [x] [Include previously done items AND newly completed items]
|
|
435
|
-
|
|
436
|
-
### In Progress
|
|
437
|
-
- [ ] [Current work - update based on progress]
|
|
438
|
-
|
|
439
|
-
### Blocked
|
|
440
|
-
- [Current blockers - remove if resolved]
|
|
441
|
-
|
|
442
|
-
## Key Decisions
|
|
443
|
-
- **[Decision]**: [Brief rationale] (preserve all previous, add new)
|
|
444
|
-
|
|
445
|
-
## Next Steps
|
|
446
|
-
1. [Update based on current state]
|
|
447
|
-
|
|
448
|
-
## Critical Context
|
|
449
|
-
- [Preserve important context, add new if needed]
|
|
407
|
+
Same section order. Pre-extracted facts:
|
|
408
|
+
<facts>
|
|
409
|
+
{FACTS_BLOCK}
|
|
410
|
+
</facts>
|
|
450
411
|
|
|
451
|
-
|
|
412
|
+
Budget: ~{BUDGET} tokens.`;
|
|
452
413
|
function createSummarizationOptions(model, maxTokens, apiKey, headers, signal, thinkingLevel) {
|
|
453
414
|
const options = { maxTokens, signal, apiKey, headers };
|
|
454
415
|
if (model.reasoning && thinkingLevel && thinkingLevel !== "off") {
|
|
@@ -467,50 +428,152 @@ async function completeSummarization(model, context, options, streamFn) {
|
|
|
467
428
|
* Generate a summary of the conversation using the LLM.
|
|
468
429
|
* If previousSummary is provided, uses the update prompt to merge.
|
|
469
430
|
*/
|
|
470
|
-
export async function generateSummary(currentMessages, model, reserveTokens, apiKey, headers, signal, customInstructions, previousSummary, thinkingLevel, streamFn, preDigest) {
|
|
471
|
-
const
|
|
472
|
-
|
|
473
|
-
let
|
|
431
|
+
export async function generateSummary(currentMessages, model, reserveTokens, apiKey, headers, signal, customInstructions, previousSummary, thinkingLevel, streamFn, preDigest, factsBlock = "files:\nactions:\nprohibitions:", chunked = false) {
|
|
432
|
+
const summaryBudget = getSummaryBudget(reserveTokens, model);
|
|
433
|
+
const maxTokens = summaryBudget;
|
|
434
|
+
let promptSuffix = fillPromptTemplate(previousSummary ? UPDATE_SUMMARIZATION_PROMPT : SUMMARIZATION_PROMPT, factsBlock, summaryBudget);
|
|
474
435
|
if (customInstructions) {
|
|
475
|
-
|
|
436
|
+
promptSuffix = `${promptSuffix}\n\nAdditional focus: ${customInstructions}`;
|
|
476
437
|
}
|
|
477
|
-
// Serialize conversation to text so model doesn't try to continue it
|
|
478
|
-
// Convert to LLM messages first (handles custom types like bashExecution, custom, etc.)
|
|
479
438
|
const llmMessages = convertToLlm(currentMessages);
|
|
480
439
|
let conversationText = serializeConversation(llmMessages);
|
|
481
|
-
// Brain-curation surface 3 (opt-in, injected by the session): pre-digest old chunks locally
|
|
482
|
-
// before the frontier summarization call. Best-effort — failure keeps the verbatim text.
|
|
483
440
|
if (preDigest) {
|
|
484
441
|
try {
|
|
485
442
|
conversationText = await preDigest(conversationText, signal);
|
|
486
443
|
}
|
|
487
444
|
catch {
|
|
488
|
-
// verbatim
|
|
445
|
+
// Keep the verbatim conversation when an optional pre-digest fails.
|
|
489
446
|
}
|
|
490
447
|
}
|
|
491
|
-
|
|
448
|
+
const inputBound = getSummarizerInputBound(model, maxTokens);
|
|
449
|
+
const initialPromptText = buildSummarizationPrompt(conversationText, previousSummary, promptSuffix);
|
|
450
|
+
if (estimateStringTokens(initialPromptText) > inputBound) {
|
|
451
|
+
if (!chunked) {
|
|
452
|
+
throw new Error("input-overflow: summarization request exceeds summarizer window");
|
|
453
|
+
}
|
|
454
|
+
conversationText = await summarizeChunks(conversationText, model, maxTokens, apiKey, headers, signal, thinkingLevel, streamFn, inputBound);
|
|
455
|
+
}
|
|
456
|
+
const promptText = buildSummarizationPrompt(conversationText, previousSummary, promptSuffix);
|
|
457
|
+
const response = await completeSummarization(model, {
|
|
458
|
+
systemPrompt: SUMMARIZATION_SYSTEM_PROMPT,
|
|
459
|
+
messages: [
|
|
460
|
+
{
|
|
461
|
+
role: "user",
|
|
462
|
+
content: [{ type: "text", text: promptText }],
|
|
463
|
+
timestamp: Date.now(),
|
|
464
|
+
},
|
|
465
|
+
],
|
|
466
|
+
}, createSummarizationOptions(model, maxTokens, apiKey, headers, signal, thinkingLevel), streamFn);
|
|
467
|
+
if (response.stopReason === "error") {
|
|
468
|
+
throw new Error(`Summarization failed: ${response.errorMessage || "Unknown error"}`);
|
|
469
|
+
}
|
|
470
|
+
return truncateSummaryToBudget(extractTextContent(response), summaryBudget);
|
|
471
|
+
}
|
|
472
|
+
function fillPromptTemplate(template, factsBlock, budget) {
|
|
473
|
+
return template.replaceAll("{FACTS_BLOCK}", factsBlock).replaceAll("{BUDGET}", String(budget));
|
|
474
|
+
}
|
|
475
|
+
function getSummaryBudget(reserveTokens, model) {
|
|
476
|
+
const modelMaxTokens = model.maxTokens > 0 ? model.maxTokens : Number.POSITIVE_INFINITY;
|
|
477
|
+
return Math.max(1, Math.min(1_500, Math.floor(0.8 * reserveTokens), modelMaxTokens));
|
|
478
|
+
}
|
|
479
|
+
function getSummarizerInputBound(model, maxTokens) {
|
|
480
|
+
const contextWindow = model.contextWindow > 0 ? model.contextWindow : Number.POSITIVE_INFINITY;
|
|
481
|
+
return contextWindow === Number.POSITIVE_INFINITY ? contextWindow : Math.max(1, contextWindow - maxTokens - 2_000);
|
|
482
|
+
}
|
|
483
|
+
function buildSummarizationPrompt(conversationText, previousSummary, promptSuffix) {
|
|
492
484
|
let promptText = `<conversation>\n${conversationText}\n</conversation>\n\n`;
|
|
493
485
|
if (previousSummary) {
|
|
494
486
|
promptText += `<previous-summary>\n${previousSummary}\n</previous-summary>\n\n`;
|
|
495
487
|
}
|
|
496
|
-
promptText
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
const
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
488
|
+
return promptText + promptSuffix;
|
|
489
|
+
}
|
|
490
|
+
async function summarizeChunks(conversationText, model, maxTokens, apiKey, headers, signal, thinkingLevel, streamFn, inputBound) {
|
|
491
|
+
const maxChunkTokens = Math.max(1, inputBound);
|
|
492
|
+
const maxChunkChars = Math.max(1, maxChunkTokens * 4);
|
|
493
|
+
const chunks = splitText(conversationText, maxChunkChars);
|
|
494
|
+
const retainedChunks = chunks.slice(-4);
|
|
495
|
+
const omittedChunks = chunks.length - retainedChunks.length;
|
|
496
|
+
const summaries = [];
|
|
497
|
+
for (let i = 0; i < retainedChunks.length; i++) {
|
|
498
|
+
const promptText = `<conversation-chunk index="${i + 1}" total="${retainedChunks.length}">\n${retainedChunks[i]}\n</conversation-chunk>\n\nSummarize this chunk for a later checkpoint merge. Preserve exact file paths, commands, errors, user prohibitions, and active work. Output concise notes only.`;
|
|
499
|
+
const response = await completeSummarization(model, {
|
|
500
|
+
systemPrompt: SUMMARIZATION_SYSTEM_PROMPT,
|
|
501
|
+
messages: [
|
|
502
|
+
{
|
|
503
|
+
role: "user",
|
|
504
|
+
content: [{ type: "text", text: promptText }],
|
|
505
|
+
timestamp: Date.now(),
|
|
506
|
+
},
|
|
507
|
+
],
|
|
508
|
+
}, createSummarizationOptions(model, maxTokens, apiKey, headers, signal, thinkingLevel), streamFn);
|
|
509
|
+
if (response.stopReason === "error") {
|
|
510
|
+
throw new Error(`Summarization failed: ${response.errorMessage || "Unknown error"}`);
|
|
511
|
+
}
|
|
512
|
+
summaries.push(extractTextContent(response));
|
|
508
513
|
}
|
|
509
|
-
const
|
|
510
|
-
|
|
511
|
-
|
|
514
|
+
const omittedNote = omittedChunks > 0
|
|
515
|
+
? `## Critical Context\n${omittedChunks} older oversized chunks omitted; deterministic facts supplied separately.\n\n`
|
|
516
|
+
: "";
|
|
517
|
+
return `${omittedNote}${summaries.join("\n\n")}`;
|
|
518
|
+
}
|
|
519
|
+
function splitText(text, maxChars) {
|
|
520
|
+
const chunks = [];
|
|
521
|
+
for (let start = 0; start < text.length; start += maxChars) {
|
|
522
|
+
chunks.push(text.slice(start, start + maxChars));
|
|
523
|
+
}
|
|
524
|
+
return chunks.length > 0 ? chunks : [""];
|
|
525
|
+
}
|
|
526
|
+
function extractTextContent(message) {
|
|
527
|
+
return message.content
|
|
528
|
+
.filter((content) => content.type === "text")
|
|
529
|
+
.map((content) => content.text)
|
|
512
530
|
.join("\n");
|
|
513
|
-
|
|
531
|
+
}
|
|
532
|
+
function truncateSummaryToBudget(summary, budget) {
|
|
533
|
+
const maxTokens = Math.floor(budget * 1.3);
|
|
534
|
+
if (estimateStringTokens(summary) <= maxTokens) {
|
|
535
|
+
return summary;
|
|
536
|
+
}
|
|
537
|
+
let current = summary;
|
|
538
|
+
for (const heading of [
|
|
539
|
+
"Critical Context",
|
|
540
|
+
"Blocked / Open",
|
|
541
|
+
"Key Decisions",
|
|
542
|
+
"Constraints & Preferences",
|
|
543
|
+
"Done",
|
|
544
|
+
"Files",
|
|
545
|
+
]) {
|
|
546
|
+
const next = removeSummarySection(current, heading);
|
|
547
|
+
if (next === current) {
|
|
548
|
+
continue;
|
|
549
|
+
}
|
|
550
|
+
current = next;
|
|
551
|
+
if (estimateStringTokens(current) <= maxTokens) {
|
|
552
|
+
return current;
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
return current;
|
|
556
|
+
}
|
|
557
|
+
function removeSummarySection(summary, heading) {
|
|
558
|
+
const lines = summary.split(/\r?\n/);
|
|
559
|
+
const kept = [];
|
|
560
|
+
let skipping = false;
|
|
561
|
+
for (const line of lines) {
|
|
562
|
+
const match = /^(?:##|###)\s+(.+?)\s*$/.exec(line);
|
|
563
|
+
if (match) {
|
|
564
|
+
skipping = match[1].trim().toLowerCase() === heading.toLowerCase();
|
|
565
|
+
if (skipping) {
|
|
566
|
+
continue;
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
if (!skipping) {
|
|
570
|
+
kept.push(line);
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
return kept.join("\n").trim();
|
|
574
|
+
}
|
|
575
|
+
function estimateStringTokens(text) {
|
|
576
|
+
return Math.ceil(text.length / 4);
|
|
514
577
|
}
|
|
515
578
|
export function prepareCompaction(pathEntries, settings) {
|
|
516
579
|
if (pathEntries.length > 0 && pathEntries[pathEntries.length - 1].type === "compaction") {
|
|
@@ -565,6 +628,7 @@ export function prepareCompaction(pathEntries, settings) {
|
|
|
565
628
|
extractFileOpsFromMessage(msg, fileOps);
|
|
566
629
|
}
|
|
567
630
|
}
|
|
631
|
+
const facts = extractCompactionFacts(pathEntries, boundaryStart, historyEnd);
|
|
568
632
|
return {
|
|
569
633
|
firstKeptEntryId,
|
|
570
634
|
messagesToSummarize,
|
|
@@ -573,6 +637,7 @@ export function prepareCompaction(pathEntries, settings) {
|
|
|
573
637
|
tokensBefore,
|
|
574
638
|
previousSummary,
|
|
575
639
|
fileOps,
|
|
640
|
+
facts,
|
|
576
641
|
settings,
|
|
577
642
|
};
|
|
578
643
|
}
|
|
@@ -600,24 +665,54 @@ Be concise. Focus on what's needed to understand the kept suffix.`;
|
|
|
600
665
|
* @param preparation - Pre-calculated preparation from prepareCompaction()
|
|
601
666
|
* @param customInstructions - Optional custom focus for the summary
|
|
602
667
|
*/
|
|
603
|
-
export async function compact(preparation, model, apiKey, headers, customInstructions, signal, thinkingLevel, streamFn, preDigest) {
|
|
604
|
-
const { firstKeptEntryId, messagesToSummarize, turnPrefixMessages, isSplitTurn, tokensBefore, previousSummary, fileOps, settings, } = preparation;
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
668
|
+
export async function compact(preparation, model, apiKey, headers, customInstructions, signal, thinkingLevel, streamFn, preDigest, executionOptions) {
|
|
669
|
+
const { firstKeptEntryId, messagesToSummarize, turnPrefixMessages, isSplitTurn, tokensBefore, previousSummary, fileOps, settings, facts: factsFromPreparation, } = preparation;
|
|
670
|
+
const facts = factsFromPreparation ?? {
|
|
671
|
+
files: [],
|
|
672
|
+
actions: [],
|
|
673
|
+
prohibitions: [],
|
|
674
|
+
cancelledText: "",
|
|
675
|
+
activeTaskSource: "",
|
|
676
|
+
};
|
|
677
|
+
const factsBlock = renderFactsBlock(facts);
|
|
678
|
+
let verification;
|
|
679
|
+
let summary = "";
|
|
680
|
+
if (isSplitTurn && messagesToSummarize.length > 0) {
|
|
681
|
+
let historySummary = "No prior history.";
|
|
682
|
+
let historyInstructions = customInstructions;
|
|
683
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
684
|
+
historySummary = await generateSummary(messagesToSummarize, model, settings.reserveTokens, apiKey, headers, signal, historyInstructions, previousSummary, thinkingLevel, streamFn, preDigest, factsBlock, executionOptions?.chunked ?? false);
|
|
685
|
+
verification = verifySummary(historySummary, facts);
|
|
686
|
+
if (verification.ok) {
|
|
687
|
+
break;
|
|
688
|
+
}
|
|
689
|
+
if (attempt >= 1) {
|
|
690
|
+
if (executionOptions?.allowVerificationFailure) {
|
|
691
|
+
break;
|
|
692
|
+
}
|
|
693
|
+
throw new Error(`gate-failed: ${formatVerificationFailures(verification)}`);
|
|
694
|
+
}
|
|
695
|
+
historyInstructions = buildRetryPrompt(verification, historySummary);
|
|
696
|
+
}
|
|
697
|
+
const turnPrefixSummary = await generateTurnPrefixSummary(turnPrefixMessages, model, settings.reserveTokens, apiKey, headers, signal, thinkingLevel, streamFn);
|
|
698
|
+
summary = `${historySummary}\n\n---\n\n**Turn Context (split turn):**\n\n${turnPrefixSummary}`;
|
|
617
699
|
}
|
|
618
700
|
else {
|
|
619
|
-
|
|
620
|
-
|
|
701
|
+
let customSummaryInstructions = customInstructions;
|
|
702
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
703
|
+
summary = await generateSummary(messagesToSummarize, model, settings.reserveTokens, apiKey, headers, signal, customSummaryInstructions, previousSummary, thinkingLevel, streamFn, preDigest, factsBlock, executionOptions?.chunked ?? false);
|
|
704
|
+
verification = verifySummary(summary, facts);
|
|
705
|
+
if (verification.ok) {
|
|
706
|
+
break;
|
|
707
|
+
}
|
|
708
|
+
if (attempt >= 1) {
|
|
709
|
+
if (executionOptions?.allowVerificationFailure) {
|
|
710
|
+
break;
|
|
711
|
+
}
|
|
712
|
+
throw new Error(`gate-failed: ${formatVerificationFailures(verification)}`);
|
|
713
|
+
}
|
|
714
|
+
customSummaryInstructions = buildRetryPrompt(verification, summary);
|
|
715
|
+
}
|
|
621
716
|
}
|
|
622
717
|
// Compute file lists and append to summary
|
|
623
718
|
const { readFiles, modifiedFiles } = computeFileLists(fileOps);
|
|
@@ -625,6 +720,63 @@ export async function compact(preparation, model, apiKey, headers, customInstruc
|
|
|
625
720
|
if (!firstKeptEntryId) {
|
|
626
721
|
throw new Error("First kept entry has no UUID - session may need migration");
|
|
627
722
|
}
|
|
723
|
+
return {
|
|
724
|
+
summary,
|
|
725
|
+
firstKeptEntryId,
|
|
726
|
+
tokensBefore,
|
|
727
|
+
details: { readFiles, modifiedFiles },
|
|
728
|
+
verification,
|
|
729
|
+
};
|
|
730
|
+
}
|
|
731
|
+
function formatVerificationFailures(verification) {
|
|
732
|
+
return verification.failures.map((failure) => `${failure.check}: ${failure.detail}`).join(", ");
|
|
733
|
+
}
|
|
734
|
+
export function createDeterministicCompaction(preparation) {
|
|
735
|
+
const { firstKeptEntryId, tokensBefore, fileOps, facts } = preparation;
|
|
736
|
+
if (!firstKeptEntryId) {
|
|
737
|
+
throw new Error("First kept entry has no UUID - session may need migration");
|
|
738
|
+
}
|
|
739
|
+
const { readFiles, modifiedFiles } = computeFileLists(fileOps);
|
|
740
|
+
const factsText = renderFactsBlock(facts ?? {
|
|
741
|
+
files: [],
|
|
742
|
+
actions: [],
|
|
743
|
+
prohibitions: [],
|
|
744
|
+
cancelledText: "",
|
|
745
|
+
activeTaskSource: "",
|
|
746
|
+
});
|
|
747
|
+
const fileLines = facts?.files.length
|
|
748
|
+
? facts.files.map((file) => `- ${file.path} — ${file.note || file.kind} (${file.kind})`)
|
|
749
|
+
: [`- read: ${readFiles.length}`, `- modified: ${modifiedFiles.length}`];
|
|
750
|
+
const mandatoryRuleLines = facts?.prohibitions.length ? facts.prohibitions.map((rule) => `- ${rule}`) : ["(none)"];
|
|
751
|
+
const doneLines = facts?.actions.length
|
|
752
|
+
? facts.actions.map((action, index) => `${index + 1}. ${action}`)
|
|
753
|
+
: ["1. CHECKPOINT deterministic fallback — repeated compaction retries exhausted"];
|
|
754
|
+
const summary = [
|
|
755
|
+
"## Active Task",
|
|
756
|
+
facts?.activeTaskSource ? `User: ${facts.activeTaskSource}` : "Continue from the deterministic compact snapshot.",
|
|
757
|
+
"",
|
|
758
|
+
"### Mandatory Rules",
|
|
759
|
+
...mandatoryRuleLines,
|
|
760
|
+
"",
|
|
761
|
+
"## Files",
|
|
762
|
+
...fileLines,
|
|
763
|
+
"",
|
|
764
|
+
"## Done",
|
|
765
|
+
...doneLines,
|
|
766
|
+
"",
|
|
767
|
+
"## Constraints & Preferences",
|
|
768
|
+
"Preserve exact file paths, commands, line numbers, and error strings.",
|
|
769
|
+
"",
|
|
770
|
+
"## Key Decisions",
|
|
771
|
+
"- Deterministic checkpoint used after repeated compaction retries.",
|
|
772
|
+
"",
|
|
773
|
+
"## Blocked / Open",
|
|
774
|
+
"(none)",
|
|
775
|
+
"",
|
|
776
|
+
"## Critical Context",
|
|
777
|
+
"- Deterministic facts-only checkpoint; no LLM summary was accepted.",
|
|
778
|
+
factsText,
|
|
779
|
+
].join("\n");
|
|
628
780
|
return {
|
|
629
781
|
summary,
|
|
630
782
|
firstKeptEntryId,
|