"""Balanced page-local UPDATE prompts for ReadAll. ReadAll still reads every section and advances one serial memory in global section order. Pagination changes only the navigation view presented to an UPDATE request: documents with more than 24 sections use the balanced page containing the current global section, and both the outline labels and ``current_section_id`` become page-local ``1..N`` values. The prompt localizer deliberately edits only the contents of the existing ```` and ```` tags. It therefore supports both the block-tag layout in ``TEMPLATE_UPDATE_READTWICE`` and the inline ``current_section_id`` layout in ``SUMMARY_UPDATE_PROMPT`` without rebuilding either template. Documents with at most 24 sections are validated and then returned byte-for-byte unchanged. This module does not schedule UPDATE calls and does not own memory state. Callers must keep UPDATE execution in global section order and pass the serial memory forward across page boundaries. """ from __future__ import annotations from dataclasses import dataclass import math from typing import Any PROTOCOL_ID = "readall-balanced-paged-update-v1" TARGET_PAGE_SECTIONS = 24 def _positive_int(value: Any, name: str) -> int: if isinstance(value, bool) or not isinstance(value, int) or value <= 0: raise ValueError(f"{name} must be a positive integer") return int(value) def _required_text(value: Any, name: str) -> str: if not isinstance(value, str) or not value.strip(): raise ValueError(f"{name} must be a non-empty string") return value def _canonical_outline_bodies( outline: str, total_sections: int ) -> tuple[str, ...]: """Validate a global canonical outline and return entry bodies verbatim.""" total = _positive_int(total_sections, "total_sections") value = _required_text(outline, "outline") entries = value.splitlines() if len(entries) != total: raise ValueError(f"outline has {len(entries)} entries, expected {total}") bodies: list[str] = [] for global_section_id, entry in enumerate(entries, 1): prefix = f"[Section {global_section_id}] " if not entry.startswith(prefix): raise ValueError( f"outline entry {global_section_id} does not start with {prefix!r}" ) body = entry[len(prefix) :] if not body.strip(): raise ValueError(f"outline entry {global_section_id} has an empty body") bodies.append(body) return tuple(bodies) def _balanced_page_ranges(total_sections: int) -> tuple[tuple[int, int], ...]: """Return balanced contiguous zero-based ``[start, end)`` ranges.""" total = _positive_int(total_sections, "total_sections") page_count = max(1, int(math.ceil(total / TARGET_PAGE_SECTIONS))) quotient, remainder = divmod(total, page_count) sizes = [ quotient + int(page_index < remainder) for page_index in range(page_count) ] if ( min(sizes) <= 0 or max(sizes) > TARGET_PAGE_SECTIONS or max(sizes) - min(sizes) > 1 ): raise AssertionError("internal ReadAll page geometry drifted") ranges: list[tuple[int, int]] = [] start = 0 for size in sizes: end = start + size ranges.append((start, end)) start = end if start != total: raise AssertionError("ReadAll page ranges lost sections") return tuple(ranges) @dataclass(frozen=True) class ReadAllPage: """One page-local outline and its immutable global/local identity map.""" page_index: int global_section_ids: tuple[int, ...] local_section_ids: tuple[int, ...] outline: str @property def section_count(self) -> int: return len(self.global_section_ids) @property def global_to_local_section_ids(self) -> tuple[tuple[int, int], ...]: return tuple(zip(self.global_section_ids, self.local_section_ids)) @property def start_global_section_id(self) -> int: return self.global_section_ids[0] @property def end_global_section_id(self) -> int: return self.global_section_ids[-1] def local_section_id(self, global_section_id: int) -> int: section_id = _positive_int(global_section_id, "global_section_id") try: offset = self.global_section_ids.index(section_id) except ValueError as exc: raise ValueError( f"global Section {section_id} is not on page {self.page_index}" ) from exc return self.local_section_ids[offset] @dataclass(frozen=True) class ReadAllPagePlan: """Deterministic ReadAll pages with complete document-level mappings.""" protocol_id: str document_total_sections: int target_page_sections: int pages: tuple[ReadAllPage, ...] @property def page_count(self) -> int: return len(self.pages) @property def is_paged(self) -> bool: return self.page_count > 1 @property def page_sizes(self) -> tuple[int, ...]: return tuple(page.section_count for page in self.pages) @property def global_section_to_page_index(self) -> tuple[int, ...]: mapping = [-1] * self.document_total_sections for page in self.pages: for global_section_id in page.global_section_ids: offset = global_section_id - 1 if mapping[offset] != -1: raise AssertionError( f"duplicate global Section {global_section_id}" ) mapping[offset] = page.page_index if any(value < 0 for value in mapping): raise AssertionError("ReadAll pages do not cover every global section") return tuple(mapping) @property def global_section_to_local_section_id(self) -> tuple[int, ...]: mapping = [-1] * self.document_total_sections for page in self.pages: for global_id, local_id in page.global_to_local_section_ids: mapping[global_id - 1] = local_id if any(value < 1 for value in mapping): raise AssertionError("ReadAll pages do not localize every section") return tuple(mapping) def page_for_global_section(self, global_section_id: int) -> ReadAllPage: section_id = _positive_int(global_section_id, "global_section_id") if section_id > self.document_total_sections: raise ValueError("global_section_id exceeds total_sections") return self.pages[self.global_section_to_page_index[section_id - 1]] @dataclass(frozen=True) class ReadAllUpdateContext: """Auditable page and global/local identities for one UPDATE prompt.""" protocol_id: str document_total_sections: int target_page_sections: int page_index: int page_count: int page_section_count: int global_section_id: int local_section_id: int global_section_ids: tuple[int, ...] local_section_ids: tuple[int, ...] global_to_local_section_ids: tuple[tuple[int, int], ...] @property def page_global_section_ids(self) -> tuple[int, ...]: return self.global_section_ids @dataclass(frozen=True) class LocalizedReadAllUpdate: """A localized UPDATE prompt and the metadata required to audit it.""" message: str context: ReadAllUpdateContext @property def prompt(self) -> str: return self.message @dataclass(frozen=True) class _TagSpan: tag: str content_start: int content_end: int content: str def _tag_span(message: str, tag: str) -> _TagSpan: """Locate exactly one non-nested exact tag pair or fail closed.""" opening = f"<{tag}>" closing = f"" if message.count(opening) != 1 or message.count(closing) != 1: raise ValueError(f"prompt must contain exactly one {tag} tag pair") opening_start = message.find(opening) content_start = opening_start + len(opening) content_end = message.find(closing, content_start) if content_end < content_start: raise ValueError(f"prompt has malformed {tag} tag order") content = message[content_start:content_end] if opening in content or closing in content: raise ValueError(f"prompt has nested {tag} tags") return _TagSpan( tag=tag, content_start=content_start, content_end=content_end, content=content, ) def _content_core_and_edges(value: str, tag: str) -> tuple[str, str, str]: """Split tag content into surrounding whitespace and its nonempty core.""" core_start = len(value) - len(value.lstrip()) core_end = len(value.rstrip()) if core_start >= core_end: raise ValueError(f"{tag} tag content must be non-empty") return value[core_start:core_end], value[:core_start], value[core_end:] def _validate_plan(plan: ReadAllPagePlan) -> None: if plan.protocol_id != PROTOCOL_ID: raise AssertionError("ReadAll paged protocol ID drifted") if plan.target_page_sections != TARGET_PAGE_SECTIONS: raise AssertionError("ReadAll page cap drifted") if tuple(page.page_index for page in plan.pages) != tuple( range(plan.page_count) ): raise AssertionError("ReadAll page indices are not canonical") covered = tuple( section_id for page in plan.pages for section_id in page.global_section_ids ) if covered != tuple(range(1, plan.document_total_sections + 1)): raise AssertionError("ReadAll pages do not cover global sections exactly once") if max(plan.page_sizes) > TARGET_PAGE_SECTIONS: raise AssertionError("ReadAll page exceeds the 24-section cap") if max(plan.page_sizes) - min(plan.page_sizes) > 1: raise AssertionError("ReadAll pages are not balanced") if (plan.document_total_sections <= TARGET_PAGE_SECTIONS) != ( plan.page_count == 1 ): raise AssertionError("ReadAll short/long page boundary drifted") for page in plan.pages: if page.local_section_ids != tuple(range(1, page.section_count + 1)): raise AssertionError("ReadAll page-local section IDs are not canonical") # Exercise both complete mappings as part of plan admission. if len(plan.global_section_to_page_index) != plan.document_total_sections: raise AssertionError("ReadAll global/page mapping length drifted") if len(plan.global_section_to_local_section_id) != plan.document_total_sections: raise AssertionError("ReadAll global/local mapping length drifted") def plan_readall_pages(outline: str, total_sections: int) -> ReadAllPagePlan: """Build balanced contiguous pages with page-local one-based outlines.""" total = _positive_int(total_sections, "total_sections") outline_value = _required_text(outline, "outline") bodies = _canonical_outline_bodies(outline_value, total) pages: list[ReadAllPage] = [] for page_index, (start, end) in enumerate(_balanced_page_ranges(total)): global_ids = tuple(range(start + 1, end + 1)) local_ids = tuple(range(1, end - start + 1)) # The single-page arm retains the exact caller-provided outline bytes. page_outline = ( outline_value if start == 0 and end == total else "\n".join( f"[Section {local_id}] {bodies[global_id - 1]}" for local_id, global_id in zip(local_ids, global_ids) ) ) pages.append( ReadAllPage( page_index=page_index, global_section_ids=global_ids, local_section_ids=local_ids, outline=page_outline, ) ) plan = ReadAllPagePlan( protocol_id=PROTOCOL_ID, document_total_sections=total, target_page_sections=TARGET_PAGE_SECTIONS, pages=tuple(pages), ) _validate_plan(plan) return plan def localize_update_prompt( prompt: str, global_section_id: int, total_sections: int ) -> LocalizedReadAllUpdate: """Localize only an UPDATE prompt's outline and current-section tag. The input prompt must still contain the global canonical outline and its global ``current_section_id``. This fail-closed precondition prevents an already localized or mismatched row from being silently transformed twice. All bytes outside the two tag contents, including the complete memory, are preserved exactly. """ message = _required_text(prompt, "prompt") total = _positive_int(total_sections, "total_sections") section_id = _positive_int(global_section_id, "global_section_id") if section_id > total: raise ValueError("global_section_id exceeds total_sections") current_span = _tag_span(message, "current_section_id") outline_span = _tag_span(message, "outline") current_core, current_prefix, current_suffix = _content_core_and_edges( current_span.content, current_span.tag ) if not current_core.isascii() or not current_core.isdigit(): raise ValueError("current_section_id tag must contain one decimal integer") declared_section_id = int(current_core) if declared_section_id != section_id: raise ValueError( "current_section_id tag does not match global_section_id argument" ) outline_core, outline_prefix, outline_suffix = _content_core_and_edges( outline_span.content, outline_span.tag ) plan = plan_readall_pages(outline_core, total) page = plan.page_for_global_section(section_id) local_section_id = page.local_section_id(section_id) context = ReadAllUpdateContext( protocol_id=plan.protocol_id, document_total_sections=total, target_page_sections=plan.target_page_sections, page_index=page.page_index, page_count=plan.page_count, page_section_count=page.section_count, global_section_id=section_id, local_section_id=local_section_id, global_section_ids=page.global_section_ids, local_section_ids=page.local_section_ids, global_to_local_section_ids=page.global_to_local_section_ids, ) if not plan.is_paged: localized = message else: replacements = ( ( current_span.content_start, current_span.content_end, current_prefix + str(local_section_id) + current_suffix, ), ( outline_span.content_start, outline_span.content_end, outline_prefix + page.outline + outline_suffix, ), ) localized = message for start, end, replacement in sorted(replacements, reverse=True): localized = localized[:start] + replacement + localized[end:] return LocalizedReadAllUpdate( message=localized, context=context, ) __all__ = [ "LocalizedReadAllUpdate", "PROTOCOL_ID", "ReadAllPage", "ReadAllPagePlan", "ReadAllUpdateContext", "TARGET_PAGE_SECTIONS", "localize_update_prompt", "plan_readall_pages", ]