Files
msd-core/get-shit-done/bin/lib/prompt-budget.cjs
Tom Boucher 6a5fa59129 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>
2026-05-18 23:13:09 -04:00

400 lines
12 KiB
JavaScript

'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 };