@caupulican/pi-agent-core 0.81.2 → 0.81.4

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.
Files changed (44) hide show
  1. package/dist/compaction/compaction.d.ts +21 -2
  2. package/dist/compaction/compaction.d.ts.map +1 -1
  3. package/dist/compaction/compaction.js +283 -106
  4. package/dist/compaction/compaction.js.map +1 -1
  5. package/dist/compaction/extraction.d.ts +15 -0
  6. package/dist/compaction/extraction.d.ts.map +1 -0
  7. package/dist/compaction/extraction.js +349 -0
  8. package/dist/compaction/extraction.js.map +1 -0
  9. package/dist/compaction/index.d.ts +4 -0
  10. package/dist/compaction/index.d.ts.map +1 -1
  11. package/dist/compaction/index.js +4 -0
  12. package/dist/compaction/index.js.map +1 -1
  13. package/dist/compaction/loop.d.ts +52 -0
  14. package/dist/compaction/loop.d.ts.map +1 -0
  15. package/dist/compaction/loop.js +157 -0
  16. package/dist/compaction/loop.js.map +1 -0
  17. package/dist/compaction/token-budget.d.ts +12 -0
  18. package/dist/compaction/token-budget.d.ts.map +1 -0
  19. package/dist/compaction/token-budget.js +52 -0
  20. package/dist/compaction/token-budget.js.map +1 -0
  21. package/dist/compaction/utils.d.ts +1 -1
  22. package/dist/compaction/utils.d.ts.map +1 -1
  23. package/dist/compaction/utils.js +45 -2
  24. package/dist/compaction/utils.js.map +1 -1
  25. package/dist/compaction/verification.d.ts +20 -0
  26. package/dist/compaction/verification.d.ts.map +1 -0
  27. package/dist/compaction/verification.js +169 -0
  28. package/dist/compaction/verification.js.map +1 -0
  29. package/dist/reliability/classifier.d.ts +2 -0
  30. package/dist/reliability/classifier.d.ts.map +1 -1
  31. package/dist/reliability/classifier.js +18 -1
  32. package/dist/reliability/classifier.js.map +1 -1
  33. package/dist/reliability/index.d.ts +1 -0
  34. package/dist/reliability/index.d.ts.map +1 -1
  35. package/dist/reliability/index.js +1 -0
  36. package/dist/reliability/index.js.map +1 -1
  37. package/dist/reliability/provider-signatures.d.ts +12 -0
  38. package/dist/reliability/provider-signatures.d.ts.map +1 -0
  39. package/dist/reliability/provider-signatures.js +34 -0
  40. package/dist/reliability/provider-signatures.js.map +1 -0
  41. package/dist/reliability/retry-controller.d.ts.map +1 -1
  42. package/dist/reliability/retry-controller.js +2 -1
  43. package/dist/reliability/retry-controller.js.map +1 -1
  44. 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 = `The messages above are a conversation to summarize. Create a structured context checkpoint summary that another LLM will use to continue the work.
383
-
384
- Use this EXACT format:
385
-
386
- ## Goal
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
- - **[Decision]**: [Brief rationale]
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
-
416
- Update the existing structured summary with new information. RULES:
417
- - PRESERVE all existing information from the previous summary
418
- - ADD new progress, decisions, and context from the new messages
419
- - UPDATE the Progress section: move items from "In Progress" to "Done" when completed
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
423
393
 
424
- Use this EXACT format:
394
+ Pre-extracted facts (verified by tooling — include ALL of them, merged with what you read):
395
+ <facts>
396
+ {FACTS_BLOCK}
397
+ </facts>
425
398
 
426
- ## Goal
427
- [Preserve existing goals, add new ones if the task expanded]
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.
428
406
 
429
- ## Constraints & Preferences
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)
407
+ Same section order. Pre-extracted facts:
408
+ <facts>
409
+ {FACTS_BLOCK}
410
+ </facts>
444
411
 
445
- ## Next Steps
446
- 1. [Update based on current state]
447
-
448
- ## Critical Context
449
- - [Preserve important context, add new if needed]
450
-
451
- Keep each section concise. Preserve exact file paths, function names, and error messages.`;
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,177 @@ 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 maxTokens = Math.min(Math.floor(0.8 * reserveTokens), model.maxTokens > 0 ? model.maxTokens : Number.POSITIVE_INFINITY);
472
- // Use update prompt if we have a previous summary, otherwise initial prompt
473
- let basePrompt = previousSummary ? UPDATE_SUMMARIZATION_PROMPT : SUMMARIZATION_PROMPT;
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, factsBlock);
433
+ const maxTokens = summaryBudget;
434
+ let promptSuffix = fillPromptTemplate(previousSummary ? UPDATE_SUMMARIZATION_PROMPT : SUMMARIZATION_PROMPT, factsBlock, summaryBudget);
474
435
  if (customInstructions) {
475
- basePrompt = `${basePrompt}\n\nAdditional focus: ${customInstructions}`;
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 fallback
445
+ // Keep the verbatim conversation when an optional pre-digest fails.
489
446
  }
490
447
  }
491
- // Build the prompt with conversation wrapped in tags
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
+ // A length-stopped checkpoint silently lost its tail sections — gating it as if complete
471
+ // guarantees a verification failure. Fail loudly so the compaction ladder escalates instead.
472
+ if (response.stopReason === "length") {
473
+ throw new Error("summary-length-stop: summarizer hit its output cap before completing the checkpoint");
474
+ }
475
+ return truncateSummaryToBudget(extractTextContent(response), summaryBudget);
476
+ }
477
+ function fillPromptTemplate(template, factsBlock, budget) {
478
+ return template.replaceAll("{FACTS_BLOCK}", factsBlock).replaceAll("{BUDGET}", String(budget));
479
+ }
480
+ const SUMMARY_BUDGET_BASE_TOKENS = 1_500;
481
+ /** Hard ceiling for the facts-scaled summary budget; also the worst case selection must assume. */
482
+ export const SUMMARY_BUDGET_MAX_TOKENS = 4_000;
483
+ /** Prompt-side margin beyond the raw conversation input (system prompt, tags, instructions). */
484
+ const SUMMARIZER_PROMPT_MARGIN_TOKENS = 2_000;
485
+ function getSummaryBudget(reserveTokens, model, factsBlock) {
486
+ const modelMaxTokens = model.maxTokens > 0 ? model.maxTokens : Number.POSITIVE_INFINITY;
487
+ // The verification gate demands the summary restate every extracted fact (modified files,
488
+ // actions, rules). A fixed budget makes large spans structurally fail: the model length-stops
489
+ // and the gated sections are the casualties. Scale the budget with the demand, bounded.
490
+ const factsTokens = factsBlock ? estimateStringTokens(factsBlock) : 0;
491
+ const demandBudget = Math.min(SUMMARY_BUDGET_MAX_TOKENS, Math.max(SUMMARY_BUDGET_BASE_TOKENS, factsTokens + 500));
492
+ return Math.max(1, Math.min(demandBudget, Math.floor(0.8 * reserveTokens), modelMaxTokens));
493
+ }
494
+ function getSummarizerInputBound(model, maxTokens) {
495
+ const contextWindow = model.contextWindow > 0 ? model.contextWindow : Number.POSITIVE_INFINITY;
496
+ return contextWindow === Number.POSITIVE_INFINITY
497
+ ? contextWindow
498
+ : Math.max(1, contextWindow - maxTokens - SUMMARIZER_PROMPT_MARGIN_TOKENS);
499
+ }
500
+ /**
501
+ * Whether a candidate summarizer can ingest a summarization input of the given size in ONE
502
+ * request (unchunked), using the same window arithmetic as {@link getSummarizerInputBound} with
503
+ * the worst-case (facts-scaled) summary budget. Hosts use this at SELECTION time: a model that
504
+ * fails this must not be handed the job — chunking cannot rescue recall-gated summarization, and
505
+ * local servers silently truncate over-window prompts instead of erroring.
506
+ */
507
+ export function summarizerCanIngest(model, estimatedInputTokens) {
508
+ const contextWindow = model.contextWindow > 0 ? model.contextWindow : Number.POSITIVE_INFINITY;
509
+ if (contextWindow === Number.POSITIVE_INFINITY)
510
+ return true;
511
+ return estimatedInputTokens <= contextWindow - SUMMARY_BUDGET_MAX_TOKENS - SUMMARIZER_PROMPT_MARGIN_TOKENS;
512
+ }
513
+ function buildSummarizationPrompt(conversationText, previousSummary, promptSuffix) {
492
514
  let promptText = `<conversation>\n${conversationText}\n</conversation>\n\n`;
493
515
  if (previousSummary) {
494
516
  promptText += `<previous-summary>\n${previousSummary}\n</previous-summary>\n\n`;
495
517
  }
496
- promptText += basePrompt;
497
- const summarizationMessages = [
498
- {
499
- role: "user",
500
- content: [{ type: "text", text: promptText }],
501
- timestamp: Date.now(),
502
- },
503
- ];
504
- const completionOptions = createSummarizationOptions(model, maxTokens, apiKey, headers, signal, thinkingLevel);
505
- const response = await completeSummarization(model, { systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, messages: summarizationMessages }, completionOptions, streamFn);
506
- if (response.stopReason === "error") {
507
- throw new Error(`Summarization failed: ${response.errorMessage || "Unknown error"}`);
518
+ return promptText + promptSuffix;
519
+ }
520
+ async function summarizeChunks(conversationText, model, maxTokens, apiKey, headers, signal, thinkingLevel, streamFn, inputBound) {
521
+ const maxChunkTokens = Math.max(1, inputBound);
522
+ const maxChunkChars = Math.max(1, maxChunkTokens * 4);
523
+ const chunks = splitText(conversationText, maxChunkChars);
524
+ const retainedChunks = chunks.slice(-4);
525
+ const omittedChunks = chunks.length - retainedChunks.length;
526
+ const summaries = [];
527
+ for (let i = 0; i < retainedChunks.length; i++) {
528
+ 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.`;
529
+ const response = await completeSummarization(model, {
530
+ systemPrompt: SUMMARIZATION_SYSTEM_PROMPT,
531
+ messages: [
532
+ {
533
+ role: "user",
534
+ content: [{ type: "text", text: promptText }],
535
+ timestamp: Date.now(),
536
+ },
537
+ ],
538
+ }, createSummarizationOptions(model, maxTokens, apiKey, headers, signal, thinkingLevel), streamFn);
539
+ if (response.stopReason === "error") {
540
+ throw new Error(`Summarization failed: ${response.errorMessage || "Unknown error"}`);
541
+ }
542
+ summaries.push(extractTextContent(response));
508
543
  }
509
- const textContent = response.content
510
- .filter((c) => c.type === "text")
511
- .map((c) => c.text)
544
+ const omittedNote = omittedChunks > 0
545
+ ? `## Critical Context\n${omittedChunks} older oversized chunks omitted; deterministic facts supplied separately.\n\n`
546
+ : "";
547
+ return `${omittedNote}${summaries.join("\n\n")}`;
548
+ }
549
+ function splitText(text, maxChars) {
550
+ const chunks = [];
551
+ for (let start = 0; start < text.length; start += maxChars) {
552
+ chunks.push(text.slice(start, start + maxChars));
553
+ }
554
+ return chunks.length > 0 ? chunks : [""];
555
+ }
556
+ function extractTextContent(message) {
557
+ return message.content
558
+ .filter((content) => content.type === "text")
559
+ .map((content) => content.text)
512
560
  .join("\n");
513
- return textContent;
561
+ }
562
+ function truncateSummaryToBudget(summary, budget) {
563
+ const maxTokens = Math.floor(budget * 1.3);
564
+ if (estimateStringTokens(summary) <= maxTokens) {
565
+ return summary;
566
+ }
567
+ let current = summary;
568
+ // Never drop "Files" or "Done" here: the verification gate checks exactly those sections
569
+ // (files-modified/read-recall, actions-overlap), so deleting them guarantees gate failure.
570
+ for (const heading of ["Critical Context", "Blocked / Open", "Key Decisions", "Constraints & Preferences"]) {
571
+ const next = removeSummarySection(current, heading);
572
+ if (next === current) {
573
+ continue;
574
+ }
575
+ current = next;
576
+ if (estimateStringTokens(current) <= maxTokens) {
577
+ return current;
578
+ }
579
+ }
580
+ return current;
581
+ }
582
+ function removeSummarySection(summary, heading) {
583
+ const lines = summary.split(/\r?\n/);
584
+ const kept = [];
585
+ let skipping = false;
586
+ for (const line of lines) {
587
+ const match = /^(?:##|###)\s+(.+?)\s*$/.exec(line);
588
+ if (match) {
589
+ skipping = match[1].trim().toLowerCase() === heading.toLowerCase();
590
+ if (skipping) {
591
+ continue;
592
+ }
593
+ }
594
+ if (!skipping) {
595
+ kept.push(line);
596
+ }
597
+ }
598
+ return kept.join("\n").trim();
599
+ }
600
+ function estimateStringTokens(text) {
601
+ return Math.ceil(text.length / 4);
514
602
  }
515
603
  export function prepareCompaction(pathEntries, settings) {
516
604
  if (pathEntries.length > 0 && pathEntries[pathEntries.length - 1].type === "compaction") {
@@ -565,6 +653,7 @@ export function prepareCompaction(pathEntries, settings) {
565
653
  extractFileOpsFromMessage(msg, fileOps);
566
654
  }
567
655
  }
656
+ const facts = extractCompactionFacts(pathEntries, boundaryStart, historyEnd);
568
657
  return {
569
658
  firstKeptEntryId,
570
659
  messagesToSummarize,
@@ -573,6 +662,7 @@ export function prepareCompaction(pathEntries, settings) {
573
662
  tokensBefore,
574
663
  previousSummary,
575
664
  fileOps,
665
+ facts,
576
666
  settings,
577
667
  };
578
668
  }
@@ -600,24 +690,54 @@ Be concise. Focus on what's needed to understand the kept suffix.`;
600
690
  * @param preparation - Pre-calculated preparation from prepareCompaction()
601
691
  * @param customInstructions - Optional custom focus for the summary
602
692
  */
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
- // Generate summaries (can be parallel if both needed) and merge into one
606
- let summary;
607
- if (isSplitTurn && turnPrefixMessages.length > 0) {
608
- // Generate both summaries in parallel
609
- const [historyResult, turnPrefixResult] = await Promise.all([
610
- messagesToSummarize.length > 0
611
- ? generateSummary(messagesToSummarize, model, settings.reserveTokens, apiKey, headers, signal, customInstructions, previousSummary, thinkingLevel, streamFn, preDigest)
612
- : Promise.resolve("No prior history."),
613
- generateTurnPrefixSummary(turnPrefixMessages, model, settings.reserveTokens, apiKey, headers, signal, thinkingLevel, streamFn),
614
- ]);
615
- // Merge into single summary
616
- summary = `${historyResult}\n\n---\n\n**Turn Context (split turn):**\n\n${turnPrefixResult}`;
693
+ export async function compact(preparation, model, apiKey, headers, customInstructions, signal, thinkingLevel, streamFn, preDigest, executionOptions) {
694
+ const { firstKeptEntryId, messagesToSummarize, turnPrefixMessages, isSplitTurn, tokensBefore, previousSummary, fileOps, settings, facts: factsFromPreparation, } = preparation;
695
+ const facts = factsFromPreparation ?? {
696
+ files: [],
697
+ actions: [],
698
+ prohibitions: [],
699
+ cancelledText: "",
700
+ activeTaskSource: "",
701
+ };
702
+ const factsBlock = renderFactsBlock(facts);
703
+ let verification;
704
+ let summary = "";
705
+ if (isSplitTurn && messagesToSummarize.length > 0) {
706
+ let historySummary = "No prior history.";
707
+ let historyInstructions = customInstructions;
708
+ for (let attempt = 0; attempt < 2; attempt++) {
709
+ historySummary = await generateSummary(messagesToSummarize, model, settings.reserveTokens, apiKey, headers, signal, historyInstructions, previousSummary, thinkingLevel, streamFn, preDigest, factsBlock, executionOptions?.chunked ?? false);
710
+ verification = verifySummary(historySummary, facts);
711
+ if (verification.ok) {
712
+ break;
713
+ }
714
+ if (attempt >= 1) {
715
+ if (executionOptions?.allowVerificationFailure) {
716
+ break;
717
+ }
718
+ throw new Error(`gate-failed: ${formatVerificationFailures(verification)}`);
719
+ }
720
+ historyInstructions = buildRetryPrompt(verification, historySummary);
721
+ }
722
+ const turnPrefixSummary = await generateTurnPrefixSummary(turnPrefixMessages, model, settings.reserveTokens, apiKey, headers, signal, thinkingLevel, streamFn);
723
+ summary = `${historySummary}\n\n---\n\n**Turn Context (split turn):**\n\n${turnPrefixSummary}`;
617
724
  }
618
725
  else {
619
- // Just generate history summary
620
- summary = await generateSummary(messagesToSummarize, model, settings.reserveTokens, apiKey, headers, signal, customInstructions, previousSummary, thinkingLevel, streamFn, preDigest);
726
+ let customSummaryInstructions = customInstructions;
727
+ for (let attempt = 0; attempt < 2; attempt++) {
728
+ summary = await generateSummary(messagesToSummarize, model, settings.reserveTokens, apiKey, headers, signal, customSummaryInstructions, previousSummary, thinkingLevel, streamFn, preDigest, factsBlock, executionOptions?.chunked ?? false);
729
+ verification = verifySummary(summary, facts);
730
+ if (verification.ok) {
731
+ break;
732
+ }
733
+ if (attempt >= 1) {
734
+ if (executionOptions?.allowVerificationFailure) {
735
+ break;
736
+ }
737
+ throw new Error(`gate-failed: ${formatVerificationFailures(verification)}`);
738
+ }
739
+ customSummaryInstructions = buildRetryPrompt(verification, summary);
740
+ }
621
741
  }
622
742
  // Compute file lists and append to summary
623
743
  const { readFiles, modifiedFiles } = computeFileLists(fileOps);
@@ -625,6 +745,63 @@ export async function compact(preparation, model, apiKey, headers, customInstruc
625
745
  if (!firstKeptEntryId) {
626
746
  throw new Error("First kept entry has no UUID - session may need migration");
627
747
  }
748
+ return {
749
+ summary,
750
+ firstKeptEntryId,
751
+ tokensBefore,
752
+ details: { readFiles, modifiedFiles },
753
+ verification,
754
+ };
755
+ }
756
+ function formatVerificationFailures(verification) {
757
+ return verification.failures.map((failure) => `${failure.check}: ${failure.detail}`).join(", ");
758
+ }
759
+ export function createDeterministicCompaction(preparation) {
760
+ const { firstKeptEntryId, tokensBefore, fileOps, facts } = preparation;
761
+ if (!firstKeptEntryId) {
762
+ throw new Error("First kept entry has no UUID - session may need migration");
763
+ }
764
+ const { readFiles, modifiedFiles } = computeFileLists(fileOps);
765
+ const factsText = renderFactsBlock(facts ?? {
766
+ files: [],
767
+ actions: [],
768
+ prohibitions: [],
769
+ cancelledText: "",
770
+ activeTaskSource: "",
771
+ });
772
+ const fileLines = facts?.files.length
773
+ ? facts.files.map((file) => `- ${file.path} — ${file.note || file.kind} (${file.kind})`)
774
+ : [`- read: ${readFiles.length}`, `- modified: ${modifiedFiles.length}`];
775
+ const mandatoryRuleLines = facts?.prohibitions.length ? facts.prohibitions.map((rule) => `- ${rule}`) : ["(none)"];
776
+ const doneLines = facts?.actions.length
777
+ ? facts.actions.map((action, index) => `${index + 1}. ${action}`)
778
+ : ["1. CHECKPOINT deterministic fallback — repeated compaction retries exhausted"];
779
+ const summary = [
780
+ "## Active Task",
781
+ facts?.activeTaskSource ? `User: ${facts.activeTaskSource}` : "Continue from the deterministic compact snapshot.",
782
+ "",
783
+ "### Mandatory Rules",
784
+ ...mandatoryRuleLines,
785
+ "",
786
+ "## Files",
787
+ ...fileLines,
788
+ "",
789
+ "## Done",
790
+ ...doneLines,
791
+ "",
792
+ "## Constraints & Preferences",
793
+ "Preserve exact file paths, commands, line numbers, and error strings.",
794
+ "",
795
+ "## Key Decisions",
796
+ "- Deterministic checkpoint used after repeated compaction retries.",
797
+ "",
798
+ "## Blocked / Open",
799
+ "(none)",
800
+ "",
801
+ "## Critical Context",
802
+ "- Deterministic facts-only checkpoint; no LLM summary was accepted.",
803
+ factsText,
804
+ ].join("\n");
628
805
  return {
629
806
  summary,
630
807
  firstKeptEntryId,