# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-silent-budget-underflow-when-tool-result-tokens-are-counted-after-eviction-rather-than-before.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-silent-budget-underflow-when-tool-result-tokens-are-counted-after-eviction-rather-than-before.warrant.json
# Markdown SHA-256:   677b1b29bc1a54c6283b99654e0beb74d5f88cee808658d5ef172a96b969c926
# Code AST SHA-256:   0c6f3b1a1b3f2344f8560dab986dd3eb7e17392c35d6ab46d475dbf7ca4bd74f
# Verified Classes:   TruncatedToolResultError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class TruncatedToolResultError(RuntimeError):
    """Raised when a tool result is admitted to the transcript after silent truncation."""


def admit_tool_result(
    result_text: str,
    result_token_count: int,
    budget: int,
    pinned_tokens: int,
    retained_tokens: int,
    evictable_tokens: int,
    truncation_marker_present: bool,
) -> str:
    slack = budget - pinned_tokens - retained_tokens
    if result_token_count <= slack:
        return result_text

    deficit = result_token_count - slack
    if deficit > evictable_tokens:
        # Eviction cannot converge; the only remaining move is truncation.
        if not truncation_marker_present:
            raise TruncatedToolResultError(
                f"result needs {result_token_count} tokens, slack is {slack}, "
                f"evictable is {evictable_tokens}, deficit {deficit} cannot be closed; "
                f"refusing to admit silently truncated result"
            )
        # Marker present: truncation is visible to the model, admit with marker.
        return result_text[: slack] + "\n[RESULT TRUNCATED: tail omitted]\n"

    # Eviction can close the gap; caller must evict before appending.
    return result_text
