import pathlib from loop_claude.stop import Stop def read_premises(root: str) -> str | Stop: try: found = sections(pathlib.Path(root, "README.md").read_text(encoding="utf-8")) except OSError as failure: return Stop(1, f"README.md in {root}: {failure.strerror} - no premises.") except UnicodeDecodeError as failure: line = failure.object.count(b"\n", 0, failure.start) + 1 return Stop(1, f"README.md is not UTF-8 on line {line} - no premises.") for name in ("Goals", "Audience"): bodies = found.get(name, []) if not bodies: return Stop(1, f"README.md has no ## {name} heading - no premises.") if len(bodies) > 1: return Stop(1, f"README.md has ## {name} more than once - no premises.") if not bodies[0]: return Stop(1, f"README.md has nothing under ## {name} - no premises.") return f"## Goals\n{found['Goals'][0]}\n\n## Audience\n{found['Audience'][0]}" def sections(text: str) -> dict[str, list[str]]: blocks: list[tuple[str | None, list[str]]] = [] fenced = False for line in text.splitlines(): fenced ^= line.startswith("```") if not fenced and line.startswith("## "): blocks.append((line.strip()[3:], [])) elif not fenced and line.startswith("# "): blocks.append((None, [])) elif blocks and line.strip(): blocks[-1][1].append(line) found: dict[str, list[str]] = {} for name, body in blocks: if name is not None: found.setdefault(name, []).append("\n".join(body)) return found