Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
179 changes: 179 additions & 0 deletions docs/full-audit-2026-10-13.md

Large diffs are not rendered by default.

19 changes: 14 additions & 5 deletions paperforge/external_import.py
Original file line number Diff line number Diff line change
Expand Up @@ -720,7 +720,7 @@ def approve_import(
for entry in manifest.get("sources") or []:
rel = str(entry.get("path") or "")
expected = str(entry.get("sha256") or "")
candidate = sources_dir.parent / rel
candidate = reject_symlink_components(sources_dir.parent / rel, anchor=sources_dir.parent)
if not candidate.is_file():
raise ApprovalError(f"source missing at approval: {rel}")
if hashlib.sha256(candidate.read_bytes()).hexdigest() != expected.lower():
Expand Down Expand Up @@ -806,9 +806,12 @@ def approval_valid(workspace: str | Path, memory: Any, import_id: str) -> tuple[
for entry in manifest.get("sources") or []:
rel = str(entry.get("path") or "")
expected = str(entry.get("sha256") or "")
candidate = sources_dir.parent / rel
if not candidate.is_file() or hashlib.sha256(candidate.read_bytes()).hexdigest() != expected.lower():
return False, f"source changed: {rel}"
try:
candidate = reject_symlink_components(sources_dir.parent / rel, anchor=sources_dir.parent)
if not candidate.is_file() or hashlib.sha256(candidate.read_bytes()).hexdigest() != expected.lower():
return False, f"source changed: {rel}"
except (OSError, ValueError):
return False, f"source missing or unsafe: {rel}"
return True, "approval valid"


Expand Down Expand Up @@ -1083,10 +1086,16 @@ def reconcile_imports(workspace: str | Path, memory: Any, *, repair: bool = Fals
try:
evidence = evidence_by_id[eid]
meta = json.loads(evidence["metadata_json"])
manifest_path = root / ".paperforge/imports" / row["import_id"] / "manifest.json"
manifest_path, _, sources_dir = _import_paths(root, str(row["import_id"]))
manifest, manifest_sha = _read_canonical_manifest(manifest_path)
source = next((s for s in manifest.get("sources", [])
if s.get("path") == meta.get("source_relpath")), None)
if source:
source_path = reject_symlink_components(
sources_dir.parent / str(source.get("path") or ""), anchor=sources_dir.parent)
if hashlib.sha256(source_path.read_bytes()).hexdigest() != str(source.get("sha256") or "").lower():
orphan_materializations.append(key)
break
if (meta.get("materialization_key") != key or meta.get("import_id") != row["import_id"]
or evidence["content_sha256"] != hashlib.sha256(evidence["excerpt"].encode()).hexdigest()
or meta.get("manifest_sha256") != row["manifest_sha256"] or manifest_sha != row["manifest_sha256"]
Expand Down
10 changes: 5 additions & 5 deletions paperforge/protected_blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,28 +49,28 @@ class ProtectedEditTransaction:

def __post_init__(self) -> None:
self.path = self.path.expanduser().resolve()
self.before_text = self.path.read_text(encoding="utf-8")
self.before_text = self.path.read_bytes().decode("utf-8")
self.before_blocks = extract_protected_blocks(self.before_text)
if self.require_markers and not self.before_blocks:
raise ProtectedBlockViolation("protected experiment markers are required")
self.before_sha256 = protected_blocks_sha256(self.before_text)

def verify(self) -> str:
after_text = self.path.read_text(encoding="utf-8")
after_text = self.path.read_bytes().decode("utf-8")
try:
after_blocks = extract_protected_blocks(after_text)
except ProtectedBlockViolation:
self.path.write_text(self.before_text, encoding="utf-8")
self.path.write_bytes(self.before_text.encode("utf-8"))
raise
if after_blocks != self.before_blocks:
self.path.write_text(self.before_text, encoding="utf-8")
self.path.write_bytes(self.before_text.encode("utf-8"))
raise ProtectedBlockViolation(
"protected experiment content changed; edit was rolled back"
)
return protected_blocks_sha256(after_text)

def rollback(self) -> None:
self.path.write_text(self.before_text, encoding="utf-8")
self.path.write_bytes(self.before_text.encode("utf-8"))


class ProtectedCoder:
Expand Down
10 changes: 5 additions & 5 deletions paperforge/publication/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ def publish(
+ json.dumps(failures, ensure_ascii=False, default=str)
)

tex_text = tex_path.read_text(encoding="utf-8")
tex_text = tex_path.read_bytes().decode("utf-8")
selected_profile = self._select_profile(template, profile, tex_text)
claim_manifest = None
effective_claim_spans = dict(claim_spans or {})
Expand Down Expand Up @@ -250,7 +250,7 @@ def publish(

if diagnosis.clean:
try:
invariant.verify(tex_path.read_text(encoding="utf-8"))
invariant.verify(tex_path.read_bytes().decode("utf-8"))
except PublicationInvariantViolation as exc:
issue = PublicationIssue(
"INVARIANT_VIOLATION",
Expand All @@ -272,7 +272,7 @@ def publish(

context = RepairContext(
round_number=round_number,
source_text=tex_path.read_text(encoding="utf-8"),
source_text=tex_path.read_bytes().decode("utf-8"),
tex_path=tex_path,
profile=selected_profile,
diagnosis=diagnosis,
Expand All @@ -299,7 +299,7 @@ def publish(
break

repair_side_effect = (
tex_path.read_text(encoding="utf-8") != transaction.before_text
tex_path.read_bytes().decode("utf-8") != transaction.before_text
or not bibliography_path.is_file()
or bibliography_path.read_bytes() != bibliography_baseline
)
Expand Down Expand Up @@ -332,7 +332,7 @@ def publish(
break

try:
tex_path.write_text(proposal.source_text, encoding="utf-8")
tex_path.write_bytes(proposal.source_text.encode("utf-8"))
transaction.verify()
invariant.verify(proposal.source_text)
if (
Expand Down
12 changes: 7 additions & 5 deletions paperforge/publication_artifacts.py
Original file line number Diff line number Diff line change
Expand Up @@ -445,16 +445,18 @@ def generate_figure(
# v1: each ledger row is one metric observation; pair x and y by run/model/seed group.
x_rows = [r for r in points if str(r.get("metric_name")) == spec.x_metric and r.get("value_str") is not None]
y_rows = [r for r in points if str(r.get("metric_name")) == spec.y_metric and r.get("value_str") is not None]
def pair_key(row: Mapping[str, Any]) -> str:
return json.dumps([dict(row.get("run_identity") or {}), row.get("measurement_kind")], sort_keys=True)

x_index: dict[str, list[dict[str, Any]]] = {}
for row in x_rows:
x_index.setdefault(pair_key(row), []).append(row)
series: dict[str, list[dict[str, str]]] = {}
for y in sorted(y_rows, key=lambda r: str(r.get("row_id"))):
identity = dict(y.get("run_identity") or {})
group = str(identity.get(spec.series_by) or y.get("measurement_kind") or "default")
# Never join observations across unlisted run dimensions or layers.
matches = [
x for x in x_rows
if dict(x.get("run_identity") or {}) == identity
and x.get("measurement_kind") == y.get("measurement_kind")
]
matches = x_index.get(pair_key(y), [])
if not matches:
continue
if len(matches) != 1:
Expand Down
46 changes: 46 additions & 0 deletions paperforge/references.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
from __future__ import annotations

import hashlib
import io
from collections.abc import Mapping, Sequence
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Any
from xml.etree import ElementTree as ET
from zipfile import BadZipFile, ZipFile

from .path_safety import reject_symlink_components

Expand All @@ -13,6 +16,7 @@
# Conservative default when callers do not supply an explicit budget.
# Reference truncation is explicit + auditable (never silent).
DEFAULT_REFERENCE_BUDGET_BYTES = 48 * 1024
MAX_DOCX_XML_BYTES = 8 * 1024 * 1024


class ReferenceError(RuntimeError):
Expand Down Expand Up @@ -167,6 +171,40 @@ def _extract_pdf(
return "", False, None, None, True, (detail or "no extractable text; likely scanned")


def _extract_docx(data: bytes, *, budget_bytes: int) -> tuple[str, bool, int, bool, str]:
"""Read only bounded main-body XML; never extract ZIP paths or relationships."""
try:
with ZipFile(io.BytesIO(data)) as package:
members = [item for item in package.infolist() if item.filename == "word/document.xml"]
if len(members) != 1 or members[0].file_size > MAX_DOCX_XML_BYTES:
raise ValueError("missing, duplicate or oversized document XML")
with package.open(members[0]) as source:
xml = source.read(MAX_DOCX_XML_BYTES + 1)
if len(xml) > MAX_DOCX_XML_BYTES:
raise ValueError("oversized document XML")
decoded = xml.decode("utf-8-sig")
if "<!DOCTYPE" in decoded.upper() or "<!ENTITY" in decoded.upper():
raise ValueError("XML entities are not accepted")
tree = ET.fromstring(decoded)
namespace = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"
# Font-mapped symbol codes are not Unicode; never guess or silently omit them.
if any(True for _ in tree.iter(namespace + "sym")):
raise ValueError("font-mapped symbols require manual review")
characters = {namespace + "tab": "\t", namespace + "br": "\n", namespace + "cr": "\n",
namespace + "noBreakHyphen": "\u2011", namespace + "softHyphen": "\u00ad"}
paragraphs = ["".join(node.text or "" if node.tag == namespace + "t"
else characters.get(node.tag, "") for node in paragraph.iter())
Comment on lines +195 to +196

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve DOCX symbol runs during extraction

Fresh reproduction on this exact head with a valid w:sym run (alpha<w:sym .../><w:t>beta</w:t>) still yields alphabeta and reports no need for human review because every unmapped inline element becomes an empty string. Word uses w:sym for displayed font-mapped characters such as mathematical or Greek symbols, so silently dropping it can corrupt identifiers and formulas; preserve these symbols or fail closed instead of concatenating adjacent text.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 09c758e. DOCX containing w:sym now fails closed with an empty excerpt and needs_human_review, retaining the original ZIP hash. Font-specific glyph codes are not guessed as Unicode. Added Symbol, Wingdings, and unknown-font regressions; repaired import/reference tests: 43 passed, full local suite: 946 passed / 5 skipped. Waiting for fresh exact-head CI and both reviews before merge.

for paragraph in tree.iter(namespace + "p")]
body = "\n".join(text for text in paragraphs if text.strip()).encode("utf-8")
if not body:
raise ValueError("no extractable main-body text")
text, truncated, read = _read_text_with_budget(body, budget_bytes=budget_bytes)
return text, truncated, read, False, (
"DOCX main-body text only; bytes_read counts extracted UTF-8; total_bytes counts ZIP bytes")
except (BadZipFile, KeyError, ValueError, ET.ParseError, OSError, RuntimeError, NotImplementedError):
return "", False, 0, True, "DOCX main-body text unavailable or unsafe; manual review required"


class ReferenceLoader:
"""Load reference_paths into audited excerpts. Materials are untrusted."""

Expand Down Expand Up @@ -195,6 +233,14 @@ def load(
sha = hashlib.sha256(data).hexdigest()
source_id = _stable_source_id(relative, sha)
suffix = Path(relative).suffix.lower()
if suffix == ".docx":
text, truncated, read, needs_human, detail = _extract_docx(data, budget_bytes=per_file)
excerpts.append(ReferenceExcerpt(
source_id=source_id, path=relative, sha256=sha, total_bytes=total,
bytes_read=read, truncated=truncated, excerpt=text,
line_start=1 if text else None, line_end=len(text.splitlines()) if text else None,
needs_human_review=needs_human, detail=detail))
continue
if suffix == ".pdf":
text, truncated, ps, pe, needs_human, detail = _extract_pdf(
data, budget_bytes=per_file
Expand Down
Loading
Loading