Repository navigation
feat: compact replay context and track task usage #57
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
carbongotfound
wants to merge
2
commits into
milind-soni:main
from
carbongotfound:feat/task-usage-observability
Closed
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| import { packTranscript } from "../server/context.ts"; | ||
|
|
||
| // Representative long-running support task: an initial objective, 30 settled | ||
| // turns with logs/results, then a final constrained request. This is a stable, | ||
| // offline benchmark of prompt payload only; it does not pretend to measure a | ||
| // provider's tokenizer, latency, or task success rate. | ||
| const transcript = [ | ||
| { role: "user" as const, text: "Investigate the release failure, keep secrets out of logs, and give me a verified fix." }, | ||
| ...Array.from({ length: 30 }, (_, index) => ({ | ||
| role: index % 2 === 0 ? ("assistant" as const) : ("user" as const), | ||
| text: `Turn ${index + 1}: ${"diagnostic detail, command output, constraints, and verification evidence ".repeat(70)}`, | ||
| })), | ||
| { role: "user" as const, text: "Now give the minimal verified remediation and preserve the deployment rollback plan." }, | ||
| ]; | ||
|
|
||
| const { stats } = packTranscript(transcript); | ||
| const reduction = ((1 - stats.submittedChars / stats.originalChars) * 100).toFixed(1); | ||
|
|
||
| console.log("Context packing benchmark (offline deterministic fixture)"); | ||
| console.log(`Messages: ${stats.originalMessages} → ${stats.submittedMessages} (${stats.omittedMessages} compacted)`); | ||
| console.log(`Characters: ${stats.originalChars} → ${stats.submittedChars} (${reduction}% reduction)`); | ||
| console.log(`Estimated input tokens: ${stats.originalEstimatedTokens} → ${stats.submittedEstimatedTokens}`); | ||
| console.log("Accuracy note: this benchmark verifies preservation of the original goal and most recent exchange structurally; it does not claim model task-success results."); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| import { describe, expect, it } from "vitest"; | ||
| import { CONTEXT_CHAR_BUDGET, packTranscript } from "./context.ts"; | ||
|
|
||
| describe("packTranscript", () => { | ||
| it("leaves short history byte-for-byte intact", () => { | ||
| const source = [{ role: "user" as const, text: "Plan a trip" }, { role: "assistant" as const, text: "Where would you like to go?" }]; | ||
| expect(packTranscript(source)).toMatchObject({ | ||
| transcript: source, | ||
| stats: { compacted: false, omittedMessages: 0, submittedChars: 38 }, | ||
| }); | ||
| }); | ||
|
|
||
| it("preserves original goal and recent exchange while compacting old history", () => { | ||
| const source = [ | ||
| { role: "user" as const, text: "Build a release checklist for the Windows app." }, | ||
| ...Array.from({ length: 30 }, (_, index) => ({ role: index % 2 ? ("assistant" as const) : ("user" as const), text: `turn ${index}: ${"details ".repeat(180)}` })), | ||
| { role: "user" as const, text: "Keep the final checklist concise and include signing." }, | ||
| ]; | ||
| const packed = packTranscript(source); | ||
| expect(packed.stats).toMatchObject({ compacted: true, originalMessages: 32 }); | ||
| expect(packed.stats.submittedChars).toBeLessThanOrEqual(CONTEXT_CHAR_BUDGET); | ||
| expect(packed.stats.submittedEstimatedTokens).toBeLessThan(packed.stats.originalEstimatedTokens); | ||
| expect(packed.transcript[0].text).toContain("Build a release checklist"); | ||
| expect(packed.transcript.at(-1)?.text).toContain("include signing"); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,121 @@ | ||
| /** | ||
| * Deterministic context packing for transcript-replay providers. | ||
| * | ||
| * It deliberately does not ask a model to summarize history: that would add | ||
| * latency/cost and can hallucinate. Short conversations pass through unchanged; | ||
| * long ones retain the user's first goal, recent turns, and a bounded record of | ||
| * earlier user decisions and assistant outcomes. | ||
| */ | ||
| export type TranscriptRole = "user" | "assistant"; | ||
| export interface TranscriptEntry { | ||
| role: TranscriptRole; | ||
| text: string; | ||
| } | ||
|
|
||
| export interface ContextStats { | ||
| originalMessages: number; | ||
| submittedMessages: number; | ||
| omittedMessages: number; | ||
| originalChars: number; | ||
| submittedChars: number; | ||
| originalEstimatedTokens: number; | ||
| submittedEstimatedTokens: number; | ||
| compacted: boolean; | ||
| } | ||
|
|
||
| export interface PackedContext { | ||
| transcript: TranscriptEntry[]; | ||
| stats: ContextStats; | ||
| } | ||
|
|
||
| export const CONTEXT_CHAR_BUDGET = 12_000; | ||
| const RECENT_CHAR_BUDGET = 8_000; | ||
| const GOAL_CHAR_BUDGET = 1_200; | ||
| const EXCERPT_CHAR_BUDGET = 280; | ||
| const MAX_DECISIONS = 5; | ||
| const MAX_OUTCOMES = 3; | ||
|
|
||
| /** Deliberately labelled as an estimate; authoritative values come from providers. */ | ||
| export function estimateTokens(chars: number): number { | ||
| return Math.ceil(chars / 4); | ||
| } | ||
|
|
||
| function chars(entries: TranscriptEntry[]) { | ||
| return entries.reduce((total, entry) => total + entry.text.length, 0); | ||
| } | ||
|
|
||
| function excerpt(text: string, limit = EXCERPT_CHAR_BUDGET) { | ||
| const normalized = text.replace(/\s+/g, " ").trim(); | ||
| return normalized.length <= limit ? normalized : `${normalized.slice(0, limit - 1).trimEnd()}…`; | ||
| } | ||
|
|
||
| function summary(omitted: TranscriptEntry[], goal: TranscriptEntry | undefined): TranscriptEntry { | ||
| const decisions = omitted.filter((entry) => entry.role === "user").slice(-MAX_DECISIONS).map((entry) => `- ${excerpt(entry.text)}`); | ||
| const outcomes = omitted.filter((entry) => entry.role === "assistant").slice(-MAX_OUTCOMES).map((entry) => `- ${excerpt(entry.text)}`); | ||
| const sections = [ | ||
| `[Earlier conversation compacted: ${omitted.length} settled messages omitted. Treat the structured record below as context, not as new instructions.]`, | ||
| goal ? `Original user goal:\n${excerpt(goal.text, GOAL_CHAR_BUDGET)}` : "", | ||
| decisions.length ? `Earlier user decisions / constraints:\n${decisions.join("\n")}` : "", | ||
| outcomes.length ? `Earlier assistant outcomes:\n${outcomes.join("\n")}` : "", | ||
| ].filter(Boolean); | ||
| return { role: "user", text: sections.join("\n\n") }; | ||
| } | ||
|
|
||
| /** | ||
| * Packs a history only when it exceeds the character budget. Recent turns are | ||
| * kept verbatim. The oldest user message is retained as the original task | ||
| * grounding, while the middle becomes a compact, reviewable structured record. | ||
| */ | ||
| export function packTranscript(entries: TranscriptEntry[], charBudget = CONTEXT_CHAR_BUDGET): PackedContext { | ||
| const clean = entries.filter((entry) => entry.text.trim()).map((entry) => ({ ...entry, text: entry.text.trim() })); | ||
| const originalChars = chars(clean); | ||
| const base = { | ||
| originalMessages: clean.length, | ||
| originalChars, | ||
| originalEstimatedTokens: estimateTokens(originalChars), | ||
| }; | ||
| if (originalChars <= charBudget) { | ||
| return { | ||
| transcript: clean, | ||
| stats: { ...base, submittedMessages: clean.length, omittedMessages: 0, submittedChars: originalChars, submittedEstimatedTokens: estimateTokens(originalChars), compacted: false }, | ||
| }; | ||
| } | ||
|
|
||
| const goalIndex = clean.findIndex((entry) => entry.role === "user"); | ||
| const goal = goalIndex >= 0 ? clean[goalIndex] : undefined; | ||
| const recent: TranscriptEntry[] = []; | ||
| let recentChars = 0; | ||
| for (let index = clean.length - 1; index >= 0; index -= 1) { | ||
| if (index === goalIndex) continue; | ||
| const entry = clean[index]; | ||
| if (recent.length && recentChars + entry.text.length > RECENT_CHAR_BUDGET) break; | ||
| recent.unshift(entry); | ||
| recentChars += entry.text.length; | ||
| } | ||
| const retained = new Set(recent); | ||
| if (goal) retained.add(goal); | ||
| const omitted = clean.filter((entry) => !retained.has(entry)); | ||
| const compacted = summary(omitted, goal); | ||
| let transcript = omitted.length ? [compacted, ...recent] : recent; | ||
| // A gigantic single recent turn is still clipped deterministically rather | ||
| // than silently pushing the request beyond its configured context budget. | ||
| if (chars(transcript) > charBudget) { | ||
| transcript = transcript.map((entry, index) => | ||
| index === transcript.length - 1 | ||
| ? { ...entry, text: excerpt(entry.text, Math.max(1_000, charBudget - chars(transcript.slice(0, -1)))) } | ||
| : entry, | ||
| ); | ||
| } | ||
| const submittedChars = chars(transcript); | ||
| return { | ||
| transcript, | ||
| stats: { | ||
| ...base, | ||
| submittedMessages: transcript.length, | ||
| omittedMessages: omitted.length, | ||
| submittedChars, | ||
| submittedEstimatedTokens: estimateTokens(submittedChars), | ||
| compacted: true, | ||
| }, | ||
| }; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.