feat(3081): auto-trim review prompts for small-context model reviewers (#3708)

* feat(3081): auto-trim review prompts for small-context model reviewers

Adds review.max_prompt_tokens and review.max_prompt_tokens_per_reviewer
config keys. When configured, the /gsd-review workflow deterministically
trims the assembled prompt before sending to each reviewer (drop CONTEXT
→ RESEARCH → REQUIREMENTS; head-shrink PROJECT.md; tail-truncate PLANs
proportionally; reserve disclosure-note tokens upfront). Trim metadata
is recorded in REVIEWS.md frontmatter. Reviewer is skipped with a
warning if even the minimum review set exceeds the budget.

Closes #3081

* fix(3081): register prompt-budget in SDK query registry and update inventory manifest

review.md references `gsd-sdk query prompt-budget` at three call sites, but the
command had no handler in the SDK registry — failing the registry-integration
drift-guard test on all 6 CI matrix legs. Added a native TypeScript SDK handler
(sdk/src/query/prompt-budget.ts) that ports the applyBudget logic from the CJS
module, registered it in DOMAIN_STATIC_CATALOG, and regenerated
docs/INVENTORY-MANIFEST.json to include the new cli_modules/prompt-budget.cjs entry.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(3081): bump ws to 8.20.1 and allowlist prompt-budget sibling pair

Two additional CI failures after the registry fix:

1. ws moderate CVE (GHSA-58qx-3vcg-4xpx, uninitialized memory disclosure):
   The advisory covers ws >=8.0.0 <8.20.1. Both root and sdk/package.json
   pinned ^8.20.0 which resolved to 8.20.0. Bumped both to 8.20.1 to clear
   the npm audit drift-guard test (bug-3588-npm-audit-clean.test.cjs).

2. lint-shared-module-handsync detected the new prompt-budget.ts / prompt-budget.cjs
   sibling pair without an allowlist entry. Added a cooperatingSiblings entry
   to scripts/shared-module-handsync-allowlist.json with classification and
   justification matching the established pattern.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(3081): align prompt-budget skip semantics across CJS and SDK dispatch paths

Replace brittle `[ $EXIT -eq 2 ]` guards with `[ $EXIT -ne 0 ]` in all three
local-reviewer blocks (Ollama, LM Studio, llama.cpp) in workflows/review.md.
Any non-zero exit from prompt-budget now triggers a skip with a descriptive
warning — exit 2/11 prints "budget too small", any other non-zero prints
"unexpected exit code". This ensures the SDK bridge dispatch path (exit 11
via GSDError(Blocked)) triggers the same skip as the CJS path (exit 2).

The SDK handler (sdk/src/query/prompt-budget.ts) already writes both metadata
and prompt files before throwing, so no change needed there.

The Ollama block also gains the missing OLLAMA_SKIP guard so the reviewer
invocation is actually skipped (previously the block only suppressed the
OLLAMA_PROMPT_FILE update but still ran the curl invocation).

SDK integration path (hardFailed via GSDError(Blocked) → exit 11) is covered
by handler unit tests in tests/prompt-budget.test.cjs; no gsd-sdk-*.test.cjs
exercising the full bridge dispatch for this command exists yet — that gap
remains and is documented here.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix prompt-budget trim ordering and review guard follow-ups

* perf: optimize prompt-budget and dedup reviewer trim workflow

* fix(3708): drop source-grep theater tests to satisfy lint-no-source-grep

All four test files added in commit 2df566ed were pure source-grep theater:
they read .cjs / .ts / .md source files and asserted that specific string
literals were present or absent. None exercised runtime behaviour.

Deleted:
- tests/gsd-tools-memory-optimizer.test.cjs   — 7 includes() on gsd-tools.cjs
- tests/prompt-budget-hotpath-optimizer.test.cjs — includes() on prompt-budget.cjs + .ts
- tests/prompt-budget-io-optimizer.test.cjs   — includes() on prompt-budget.ts + gsd-tools.cjs
- tests/review-workflow-budget-dedup.test.cjs — includes() on review.md

Behavioural coverage for the prompt-budget feature already exists in
tests/prompt-budget.test.cjs and tests/prompt-budget-cli.test.cjs (also
added by this PR). No replacement tests needed.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(3708): correct budget-pressure threshold and minSet accounting

Two bugs in applyBudget caused premature trimming and false hard-fails:

1. UNNEEDED_TRIM: budgetUnderPressure compared baseTokens against
   effectiveBudget - NOTE_RESERVE_TOKENS, triggering trim pressure 80
   tokens before the budget was actually exceeded. Fix: compare against
   effectiveBudget directly; NOTE_RESERVE_TOKENS are still reserved in
   contentBudget once real pressure is confirmed.

2. FALSE_HARDFAIL: minSet included NOTE_RESERVE_TOKENS unconditionally,
   treating the note as mandatory even when no trim would occur and no
   note would be injected. Fix: exclude NOTE_RESERVE_TOKENS from minSet;
   a prompt that fits untrimmed needs no note and must not hard-fail.

Both fixes applied in CJS and TypeScript implementations. Two regression
tests added (cycles 11 and 12) that reproduce each case behaviorally.

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Tom Boucher
2026-05-18 23:13:09 -04:00
committed by GitHub
parent e15348ea43
commit 6a5fa59129
21 changed files with 2008 additions and 33 deletions

View File

@@ -448,7 +448,7 @@ async function main() {
'from-gsd2, frontmatter, gap-analysis, generate-claude-md, generate-claude-profile, ' +
'generate-dev-preferences, generate-slug, graphify, history-digest, init, intel, ' +
'learnings, list-todos, milestone, phase, phase-plan-index, phases, profile-questionnaire, ' +
'profile-sample, progress, requirements, resolve-model, roadmap, scaffold, state, ' +
'profile-sample, progress, prompt-budget, requirements, resolve-model, roadmap, scaffold, state, ' +
'template, validate, verify, verify-path-exists, verify-summary, workstream, worktree\n\n' +
'Global flags:\n' +
' --raw Emit raw output without post-processing\n' +
@@ -494,7 +494,7 @@ async function main() {
const SKIP_ROOT_RESOLUTION = new Set([
'generate-slug', 'current-timestamp', 'verify-path-exists',
'verify-summary', 'template', 'frontmatter', 'detect-custom-files',
'worktree',
'worktree', 'prompt-budget',
]);
if (!SKIP_ROOT_RESOLUTION.has(command)) {
cwd = findProjectRoot(cwd);
@@ -503,14 +503,16 @@ async function main() {
// When --pick is active, intercept stdout to extract the requested field.
if (pickField) {
const origWriteSync = fs.writeSync;
const chunks = [];
let captured = '';
fs.writeSync = function (fd, data, ...rest) {
if (fd === 1) { chunks.push(String(data)); return; }
if (fd === 1) {
captured += String(data);
return;
}
return origWriteSync.call(fs, fd, data, ...rest);
};
const cleanup = () => {
fs.writeSync = origWriteSync;
const captured = chunks.join('');
let jsonStr = captured;
if (jsonStr.startsWith('@file:')) {
jsonStr = fs.readFileSync(jsonStr.slice(6), 'utf-8');
@@ -540,9 +542,12 @@ async function main() {
// every workflow to have a bash-specific `if [[ "$INIT" == @file:* ]]` check
// that breaks on PowerShell and other non-bash shells.
const origWriteSync2 = fs.writeSync;
const outChunks = [];
let captured = '';
fs.writeSync = function (fd, data, ...rest) {
if (fd === 1) { outChunks.push(String(data)); return; }
if (fd === 1) {
captured += String(data);
return;
}
return origWriteSync2.call(fs, fd, data, ...rest);
};
try {
@@ -550,7 +555,6 @@ async function main() {
} finally {
fs.writeSync = origWriteSync2;
}
let captured = outChunks.join('');
if (captured.startsWith('@file:')) {
captured = fs.readFileSync(captured.slice(6), 'utf-8');
}
@@ -1368,7 +1372,7 @@ async function runCommand(command, args, cwd, raw, defaultValue, originalCommand
let manifest;
try {
manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
manifest = JSON.parse(await fs.promises.readFile(manifestPath, 'utf8'));
} catch {
const out = { custom_files: [], custom_count: 0, manifest_found: false, error: 'manifest parse error' };
process.stdout.write(JSON.stringify(out, null, 2));
@@ -1387,31 +1391,27 @@ async function runCommand(command, args, cwd, raw, defaultValue, originalCommand
'skills',
];
function walkDir(dir, baseDir) {
const results = [];
if (!fs.existsSync(dir)) return results;
function collectCustomFiles(dir, baseDir, manifestKeys, out) {
if (!fs.existsSync(dir)) return;
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
results.push(...walkDir(fullPath, baseDir));
} else {
// Use forward slashes for cross-platform manifest key compatibility
const relPath = path.relative(baseDir, fullPath).replace(/\\/g, '/');
results.push(relPath);
collectCustomFiles(fullPath, baseDir, manifestKeys, out);
continue;
}
// Use forward slashes for cross-platform manifest key compatibility
const relPath = path.relative(baseDir, fullPath).replace(/\\/g, '/');
if (!manifestKeys.has(relPath)) {
out.push(relPath);
}
}
return results;
}
const customFiles = [];
for (const managedDir of GSD_MANAGED_DIRS) {
const absDir = path.join(resolvedConfigDir, managedDir);
if (!fs.existsSync(absDir)) continue;
for (const relPath of walkDir(absDir, resolvedConfigDir)) {
if (!manifestKeys.has(relPath)) {
customFiles.push(relPath);
}
}
collectCustomFiles(absDir, resolvedConfigDir, manifestKeys, customFiles);
}
const out = {
@@ -1432,6 +1432,177 @@ async function runCommand(command, args, cwd, raw, defaultValue, originalCommand
break;
}
// ─── Prompt Budget ────────────────────────────────────────────────────
//
// Assemble and deterministically trim review prompt sections to fit a
// token budget. Used by the /gsd-review workflow before dispatching to
// small-context local model servers (Ollama, llama.cpp, LM Studio).
//
// Required flags:
// --budget <N> Token budget (integer > 0)
// --instructions-file <path> Review instructions
// --roadmap-file <path> Roadmap section
// --plan-file <path> Plan file (may be repeated)
// --output-prompt <path> Write trimmed prompt here
// --output-metadata <path> Write metadata JSON here
//
// Optional flags:
// --safety-margin-pct <N> Default 10
// --project-md-head-lines <N> Default 40
// --project-file <path>
// --context-file <path>
// --research-file <path>
// --requirements-file <path>
//
// Exit codes:
// 0 success (trim or no-trim)
// 1 invocation error (missing required arg, missing file, invalid budget)
// 2 hardFailed: prompt cannot fit effective budget after trim policy
case 'prompt-budget': {
const promptBudget = require('./lib/prompt-budget.cjs');
// ── Collect multi-value --plan-file flags ──────────────────────────
const planFiles = [];
for (let i = 1; i < args.length; i++) {
if (args[i] === '--plan-file' && args[i + 1] && !args[i + 1].startsWith('--')) {
planFiles.push(args[i + 1]);
i++;
}
}
// ── Parse single-value flags ───────────────────────────────────────
const flagMap = new Map();
for (let i = 1; i < args.length; i++) {
const current = args[i];
const next = args[i + 1];
if (!current.startsWith('--')) continue;
if (!next || next.startsWith('--')) {
if (!flagMap.has(current)) flagMap.set(current, null);
continue;
}
if (!flagMap.has(current)) flagMap.set(current, next);
i++;
}
const getFlag = (flag) => flagMap.get(flag) ?? null;
const budgetStr = getFlag('--budget');
const instructionsFile = getFlag('--instructions-file');
const roadmapFile = getFlag('--roadmap-file');
const outputPromptFile = getFlag('--output-prompt');
const outputMetadataFile = getFlag('--output-metadata');
const safetyMarginStr = getFlag('--safety-margin-pct');
const projectMdHeadLinesStr = getFlag('--project-md-head-lines');
const projectFile = getFlag('--project-file');
const contextFile = getFlag('--context-file');
const researchFile = getFlag('--research-file');
const requirementsFile = getFlag('--requirements-file');
// ── Validate required args ─────────────────────────────────────────
if (!budgetStr) {
process.stderr.write('Error: --budget <N> is required\n');
process.exit(1);
}
const budget = parseInt(budgetStr, 10);
if (!Number.isFinite(budget) || budget <= 0) {
process.stderr.write('Error: --budget must be a positive integer\n');
process.exit(1);
}
if (!instructionsFile) {
process.stderr.write('Error: --instructions-file <path> is required\n');
process.exit(1);
}
if (!roadmapFile) {
process.stderr.write('Error: --roadmap-file <path> is required\n');
process.exit(1);
}
if (planFiles.length === 0) {
process.stderr.write('Error: at least one --plan-file <path> is required\n');
process.exit(1);
}
if (!outputPromptFile) {
process.stderr.write('Error: --output-prompt <path> is required\n');
process.exit(1);
}
if (!outputMetadataFile) {
process.stderr.write('Error: --output-metadata <path> is required\n');
process.exit(1);
}
// ── Validate and read required files ──────────────────────────────
async function readRequired(filePath, flagName) {
const resolved = path.resolve(filePath);
try {
return await fs.promises.readFile(resolved, 'utf8');
} catch (err) {
if (err && err.code === 'ENOENT') {
process.stderr.write(`Error: file not found for ${flagName}: ${resolved}\n`);
process.exit(1);
}
process.stderr.write(`Error: cannot read file for ${flagName}: ${resolved}\n`);
process.exit(1);
}
}
async function readOptional(filePath) {
if (!filePath) return null;
const resolved = path.resolve(filePath);
try {
return await fs.promises.readFile(resolved, 'utf8');
} catch (err) {
if (err && err.code === 'ENOENT') return null;
process.stderr.write(`Error: cannot read optional file: ${resolved}\n`);
process.exit(1);
}
}
const instructions = await readRequired(instructionsFile, '--instructions-file');
const roadmap = await readRequired(roadmapFile, '--roadmap-file');
const plans = await Promise.all(planFiles.map(async (p) => {
const resolved = path.resolve(p);
try {
const content = await fs.promises.readFile(resolved, 'utf8');
return { file: path.basename(p), content };
} catch (err) {
if (err && err.code === 'ENOENT') {
process.stderr.write(`Error: plan file not found: ${resolved}\n`);
process.exit(1);
}
process.stderr.write(`Error: cannot read plan file: ${resolved}\n`);
process.exit(1);
}
}));
const projectMd = await readOptional(projectFile);
const context = await readOptional(contextFile);
const research = await readOptional(researchFile);
const requirements = await readOptional(requirementsFile);
// ── Build options ─────────────────────────────────────────────────
const options = {};
if (safetyMarginStr !== null) {
const pct = parseInt(safetyMarginStr, 10);
if (Number.isFinite(pct)) options.safetyMarginPct = pct;
}
if (projectMdHeadLinesStr !== null) {
const lines = parseInt(projectMdHeadLinesStr, 10);
if (Number.isFinite(lines)) options.projectMdHeadLines = lines;
}
// ── Call applyBudget ──────────────────────────────────────────────
const sections = { instructions, roadmap, plans, projectMd, context, research, requirements };
const { prompt, metadata } = promptBudget.applyBudget({ sections, budget, options });
// ── Write outputs ─────────────────────────────────────────────────
await fs.promises.writeFile(path.resolve(outputMetadataFile), JSON.stringify(metadata, null, 2));
await fs.promises.writeFile(path.resolve(outputPromptFile), prompt);
if (metadata.hardFailed) {
process.exit(2);
}
break;
}
default: {
// #3243: if the caller passed a dotted form (e.g. "foo.bar"), the shim
// above split it so `command` here is the head ("foo"). Use

View File

@@ -0,0 +1,399 @@
'use strict';
/**
* prompt-budget.cjs
*
* Pure functions for assembling and trimming review prompts to fit within
* a token budget. Used by the review pipeline to support small-context models.
*
* Trim priority (in order — never violate):
* 1. Instructions: ALWAYS kept verbatim
* 2. Reserve note tokens FIRST when any trim is anticipated
* 3. Roadmap: ALWAYS kept verbatim
* 4. PROJECT.md: head-shrink to projectMdHeadLines (default 40) if over budget
* 5. Plans: tail-truncate proportionally; never drop a whole plan
* 6. Context: DROP first if still over
* 7. Research: DROP second if still over
* 8. Requirements: DROP last (last-resort)
* 9. Hard-fail: if minimum-set exceeds effectiveBudget
*/
const NOTE_RESERVE_TOKENS = 80;
const DEFAULT_NOTE_TEMPLATE = [
'<note>',
'Prompt automatically trimmed to fit a {budget}-token budget.',
'Omitted sections: {omittedList}.',
'Plan content truncated by approximately {planTruncationPct}%.',
'Treat any missing context as out-of-scope rather than a review concern.',
'</note>',
].join('\n');
/**
* Estimate tokens for a string. Chars / 4, rounded up.
*
* @param {string} text
* @returns {number}
*/
function estimateTokens(text) {
if (!text) return 0;
return Math.ceil(text.length / 4);
}
/**
* Render the trim-disclosure note.
*
* @param {string} template
* @param {number} budget
* @param {string[]} omitted
* @param {number} planTruncationPct
* @returns {string}
*/
function renderNote(template, budget, omitted, planTruncationPct) {
const omittedList = omitted.length > 0 ? omitted.join(', ') : 'none';
return template
.replace('{budget}', String(budget))
.replace('{omittedList}', omittedList)
.replace('{planTruncationPct}', String(Math.round(planTruncationPct)));
}
/**
* Head-shrink a string to at most `maxLines` lines.
*
* @param {string} text
* @param {number} maxLines
* @returns {string}
*/
function headShrink(text, maxLines) {
if (maxLines <= 0) return '';
let idx = -1;
let seen = 0;
while (seen < maxLines) {
idx = text.indexOf('\n', idx + 1);
if (idx === -1) return text;
seen += 1;
}
return text.slice(0, idx);
}
/**
* Tail-truncate a string to at most `maxChars` characters.
*
* @param {string} text
* @param {number} maxChars
* @returns {string}
*/
function tailTruncate(text, maxChars) {
if (text.length <= maxChars) return text;
return text.slice(0, maxChars);
}
/**
* Assemble the final prompt string from its sections.
*
* @param {object} parts
* @returns {string}
*/
function assemblePrompt(parts) {
const {
instructions,
note,
roadmap,
projectMd,
plans,
context,
research,
requirements,
} = parts;
const blocks = [];
blocks.push(instructions);
if (note) blocks.push(note);
blocks.push('## Roadmap\n\n' + roadmap);
if (projectMd) blocks.push('## Project\n\n' + projectMd);
const planBlocks = plans
.map((p) => '### ' + p.file + '\n\n' + p.content)
.join('\n\n');
blocks.push('## Plans\n\n' + planBlocks);
if (context) blocks.push('## Context\n\n' + context);
if (research) blocks.push('## Research\n\n' + research);
if (requirements) blocks.push('## Requirements\n\n' + requirements);
return blocks.join('\n\n');
}
/**
* Apply a token budget to a set of review prompt sections.
* Returns the trimmed prompt and structured metadata.
*
* @param {object} param0
* @param {object} param0.sections
* @param {number} param0.budget
* @param {object} [param0.options]
* @returns {{ prompt: string, metadata: object }}
*/
function applyBudget({ sections, budget, options = {} }) {
const {
safetyMarginPct = 10,
noteTemplate = DEFAULT_NOTE_TEMPLATE,
projectMdHeadLines = 40,
} = options;
const effectiveBudget = Math.floor(budget * (1 - safetyMarginPct / 100));
const {
instructions,
roadmap,
plans,
projectMd: projectMdRaw = null,
context: contextRaw = null,
research: researchRaw = null,
requirements: requirementsRaw = null,
} = sections;
// Working mutable state
let projectMd = projectMdRaw;
let context = contextRaw;
let research = researchRaw;
let requirements = requirementsRaw;
let workingPlans = plans.map((p) => ({ file: p.file, content: p.content }));
const omitted = [];
let projectMdShrunk = false;
let planTruncationPct = 0;
let noteInjected = false;
let hardFailed = false;
// Minimum-set check: instructions + roadmap + 1KB per plan.
// NOTE_RESERVE_TOKENS is intentionally excluded here: a note is only injected
// when trimming actually occurs, and a prompt that fits without any trim needs
// no note at all. Including NOTE_RESERVE_TOKENS here would cause false hard-fails
// for prompts that genuinely fit the effective budget untrimmed.
const MIN_PLAN_BYTES = 1024;
const minPlanTokens = plans.reduce((sum, p) => {
return sum + estimateTokens(p.content.slice(0, MIN_PLAN_BYTES));
}, 0);
const minSet =
estimateTokens(instructions) +
estimateTokens(roadmap) +
minPlanTokens;
if (minSet > effectiveBudget) {
return {
prompt: '',
metadata: {
budget,
effectiveBudget,
estimatedTokens: 0,
omitted: [],
projectMdShrunk: false,
planTruncationPct: 0,
hardFailed: true,
noteInjected: false,
},
};
}
// ── Budget accounting ──────────────────────────────────────────────────────
const TOKENS_ROADMAP_HEADER = estimateTokens('## Roadmap\n\n');
const TOKENS_PROJECT_HEADER = estimateTokens('## Project\n\n');
const TOKENS_PLANS_HEADER = estimateTokens('## Plans\n\n');
const TOKENS_CONTEXT_HEADER = estimateTokens('## Context\n\n');
const TOKENS_RESEARCH_HEADER = estimateTokens('## Research\n\n');
const TOKENS_REQUIREMENTS_HEADER = estimateTokens('## Requirements\n\n');
const TOKENS_PLAN_ITEM_HEADERS = workingPlans.reduce(
(sum, p) => sum + estimateTokens('### ' + p.file + '\n\n'),
0
);
const staticBaseTokens =
estimateTokens(instructions) +
TOKENS_ROADMAP_HEADER +
estimateTokens(roadmap) +
TOKENS_PLANS_HEADER +
TOKENS_PLAN_ITEM_HEADERS;
let projectTokens = projectMd
? TOKENS_PROJECT_HEADER + estimateTokens(projectMd)
: 0;
let contextTokens = context
? TOKENS_CONTEXT_HEADER + estimateTokens(context)
: 0;
let researchTokens = research
? TOKENS_RESEARCH_HEADER + estimateTokens(research)
: 0;
let requirementsTokens = requirements
? TOKENS_REQUIREMENTS_HEADER + estimateTokens(requirements)
: 0;
let planContentTokens = workingPlans.reduce(
(sum, p) => sum + estimateTokens(p.content),
0
);
const getCurrentBaseTokens = () =>
staticBaseTokens +
projectTokens +
planContentTokens +
contextTokens +
researchTokens +
requirementsTokens;
let currentBaseTokens = getCurrentBaseTokens();
// Detect budget pressure: is ANY trim needed?
// Pressure exists when the current base tokens already exceed the effective
// budget. Only when pressure is real do we reserve NOTE_RESERVE_TOKENS so
// the note itself fits after trimming. Checking against
// effectiveBudget - NOTE_RESERVE_TOKENS (the old threshold) would cause
// spurious pressure 80 tokens early, dropping sections that fit fine.
const baseTokens = currentBaseTokens;
const budgetUnderPressure = baseTokens > effectiveBudget;
// Available for content (reserve note slot when under pressure)
let contentBudget = budgetUnderPressure
? effectiveBudget - NOTE_RESERVE_TOKENS
: effectiveBudget;
// ── Trim step 1: head-shrink PROJECT.md ───────────────────────────────────
if (currentBaseTokens > contentBudget && projectMd) {
const shrunk = headShrink(projectMd, projectMdHeadLines);
if (shrunk !== projectMd) {
projectMd = shrunk;
projectMdShrunk = true;
projectTokens = TOKENS_PROJECT_HEADER + estimateTokens(projectMd);
currentBaseTokens = getCurrentBaseTokens();
}
}
// ── Trim step 2: proportional plan truncation ─────────────────────────────
if (currentBaseTokens > contentBudget) {
// Compute tokens available for plan content only
const overhead =
staticBaseTokens +
projectTokens +
contextTokens +
researchTokens +
requirementsTokens;
const planBudgetTokens = contentBudget - overhead;
const totalPlanTokens = planContentTokens;
if (planBudgetTokens > 0 && planBudgetTokens < totalPlanTokens) {
// Proportional share per plan (at least 1KB per plan)
const totalOriginalChars = plans.reduce(
(sum, p) => sum + p.content.length,
0
);
const totalPlanCharsBudget = planBudgetTokens * 4;
workingPlans = workingPlans.map((p) => {
const proportionalShare =
totalOriginalChars > 0
? Math.floor((p.content.length / totalOriginalChars) * totalPlanCharsBudget)
: 0;
const maxChars = Math.max(proportionalShare, MIN_PLAN_BYTES);
return { file: p.file, content: tailTruncate(p.content, maxChars) };
});
const newTotalChars = workingPlans.reduce(
(sum, p) => sum + p.content.length,
0
);
if (totalOriginalChars > 0) {
planTruncationPct =
((totalOriginalChars - newTotalChars) / totalOriginalChars) * 100;
}
planContentTokens = workingPlans.reduce(
(sum, p) => sum + estimateTokens(p.content),
0
);
currentBaseTokens = getCurrentBaseTokens();
}
}
// ── Trim step 3: drop context ─────────────────────────────────────────────
if (currentBaseTokens > contentBudget && context) {
context = null;
omitted.push('context');
contextTokens = 0;
currentBaseTokens = getCurrentBaseTokens();
}
// ── Trim step 4: drop research ────────────────────────────────────────────
if (currentBaseTokens > contentBudget && research) {
research = null;
omitted.push('research');
researchTokens = 0;
currentBaseTokens = getCurrentBaseTokens();
}
// ── Trim step 5: drop requirements (last resort) ──────────────────────────
if (currentBaseTokens > contentBudget && requirements) {
requirements = null;
omitted.push('requirements');
requirementsTokens = 0;
currentBaseTokens = getCurrentBaseTokens();
}
// ── Decide whether note is actually needed ────────────────────────────────
const anyTrimOccurred =
omitted.length > 0 || projectMdShrunk || planTruncationPct > 0;
let note = null;
if (anyTrimOccurred) {
note = renderNote(noteTemplate, budget, omitted, planTruncationPct);
noteInjected = true;
}
// ── Assemble ──────────────────────────────────────────────────────────────
const prompt = assemblePrompt({
instructions,
note,
roadmap,
projectMd,
plans: workingPlans,
context,
research,
requirements,
});
const estimatedTokens = estimateTokens(prompt);
if (estimatedTokens > effectiveBudget) {
hardFailed = true;
return {
prompt: '',
metadata: {
budget,
effectiveBudget,
estimatedTokens,
omitted,
projectMdShrunk,
planTruncationPct,
hardFailed,
noteInjected,
},
};
}
return {
prompt,
metadata: {
budget,
effectiveBudget,
estimatedTokens,
omitted,
projectMdShrunk,
planTruncationPct,
hardFailed,
noteInjected,
},
};
}
module.exports = { estimateTokens, applyBudget };