When implementing algorithmic logic (parsing, path transforms, selection/slicing, or cost/estimate functions), treat correctness and runtime bounds as first-class requirements.
Apply this standard: 1) State the invariant explicitly
disabled overrides enabled: false).2) Avoid naive scaling/assumptions; cap complexity/cost
3) Add targeted tests that break naive implementations
Example pattern (estimation should be count-based, not payload-based):
const ESTIMATED_TOKENS_PER_IMAGE = 123;
function estimateTokensForImages(content: Array<{type: string; data?: string}>) {
const imageCount = content.filter(b => b.type === 'image').length;
return imageCount * ESTIMATED_TOKENS_PER_IMAGE;
}
Back it with tests that compare a huge base64 payload vs. a small one (same count → same estimate) and verify the estimate scales ~linearly with image count.
This combination prevents both subtle semantic bugs and worst-case performance surprises in the algorithmic parts of the system.