@orbit-build/cli 0.4.6 → 0.4.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@orbit-build/cli",
3
- "version": "0.4.6",
3
+ "version": "0.4.8",
4
4
  "description": "Local-first AI coding agent CLI, TUI, Web UI, diagnostics, and LSP runtime",
5
5
  "keywords": [
6
6
  "ai",
@@ -115,6 +115,11 @@ python "<skill-root>/scripts/inspect_inputs.py" <project-root>
115
115
  python "<skill-root>/scripts/bootstrap_project.py" <project-root> --questions <N>
116
116
  ```
117
117
 
118
+ The inventory accepts canonical inputs under `question/` and supported problem
119
+ files placed directly in the project root. Root-level inputs remain in place and
120
+ are fingerprinted as immutable; do not move or duplicate them merely to satisfy
121
+ the canonical layout.
122
+
118
123
  The bootstrap is additive and idempotent. It may add missing q-folders and
119
124
  orchestrator entries, but must not overwrite authored content. Review
120
125
  `paper/contest-profile.json`; select `cumcm-2026` only when applicable. Do not
@@ -144,6 +149,12 @@ python <project-root>/code/run_all.py
144
149
  python "<skill-root>/scripts/capture_environment.py" <project-root>
145
150
  ```
146
151
 
152
+ Once numerical outputs and figures have been accepted, treat them as a frozen
153
+ phase. The finalizer records their hashes in `paper/evidence-freeze.json`.
154
+ After that file exists, `--run-code` fails closed instead of silently changing
155
+ accepted facts. Recalculation requires an explicit user request and the paired
156
+ flags `--run-code --refresh-evidence`.
157
+
147
158
  ### 4. Write or revise from evidence
148
159
 
149
160
  For every question, make the progression explicit: task interpretation,
@@ -172,6 +183,13 @@ Use the one-command finalizer after the substantive code and paper are complete:
172
183
  python <project-root>/code/finalize.py --run-code --strict-layout --render-pages
173
184
  ```
174
185
 
186
+ Use `--run-code` for the first finalization only. For later typography,
187
+ appendix, disclosure, packaging, or audit repairs, omit it:
188
+
189
+ ```powershell
190
+ python <project-root>/code/finalize.py --strict-layout --render-pages
191
+ ```
192
+
175
193
  The project-local launcher executes the active Skill's trusted finalizer without
176
194
  requiring a shell command outside the workspace. It records the environment,
177
195
  rebuilds with local TeX Live, audits and optionally
@@ -19,6 +19,7 @@
19
19
  \section{主要提示方式与过程}
20
20
  \TODO{概述如何提供题目、代码和证据约束,可列典型提示词;不得虚构未发生的交互。}
21
21
 
22
+ \clearpage
22
23
  \section{采纳、人工修改与核验}
23
24
  \renewcommand{\arraystretch}{1.3}
24
25
  \begin{longtable}{@{}L{0.06\textwidth}L{0.13\textwidth}L{0.15\textwidth}L{0.23\textwidth}L{0.25\textwidth}@{}}
@@ -16,6 +16,11 @@
16
16
  \IfFontExistsTF{Microsoft YaHei}
17
17
  {\setCJKmonofont{Microsoft YaHei}}
18
18
  {\setCJKmonofont{FandolFang-Regular}}
19
+ \IfFontExistsTF{JuliaMono}
20
+ {\setmonofont{JuliaMono}[Scale=0.875]}
21
+ {\IfFontExistsTF{Noto Sans Mono}
22
+ {\setmonofont{Noto Sans Mono}[Scale=MatchLowercase]}
23
+ {\IfFontExistsTF{DejaVu Sans Mono}{\setmonofont{DejaVu Sans Mono}[Scale=MatchLowercase]}{}}}
19
24
  \graphicspath{{../figures/}}
20
25
  \captionsetup{font=small,labelsep=quad}
21
26
  \setlength{\parindent}{2em}
@@ -10,6 +10,9 @@ from typing import Any
10
10
 
11
11
 
12
12
  FIGURE_SUFFIXES = {".pdf", ".png", ".jpg", ".jpeg", ".eps", ".svg"}
13
+ PROBLEM_SUFFIXES = {".pdf", ".doc", ".docx", ".csv", ".tsv", ".xls", ".xlsx"}
14
+ INVENTORY_EXCLUDED_PARTS = {"__pycache__", ".pytest_cache", ".mypy_cache", ".ruff_cache", ".orbit", "_work"}
15
+ FIGURE_STALE_TOLERANCE_SECONDS = 30.0
13
16
 
14
17
 
15
18
  def relative(root: Path, path: Path) -> str:
@@ -41,25 +44,68 @@ def latest_mtime(paths: list[Path]) -> float:
41
44
  return max((path.stat().st_mtime for path in paths if path.is_file()), default=0.0)
42
45
 
43
46
 
47
+ def inventory_files(root: Path, base: Path) -> list[Path]:
48
+ if not base.is_dir() or base.is_symlink():
49
+ return []
50
+ return [
51
+ path
52
+ for path in base.rglob("*")
53
+ if path.is_file()
54
+ and not path.is_symlink()
55
+ and path.suffix.lower() != ".pyc"
56
+ and not any(part in INVENTORY_EXCLUDED_PARTS for part in path.relative_to(root).parts)
57
+ ]
58
+
59
+
44
60
  def inspect_pdf(pdf: Path) -> dict[str, Any]:
45
61
  if not pdf.is_file():
46
62
  return {"status": "missing"}
47
63
  try:
48
64
  from pypdf import PdfReader
49
65
  except ImportError:
50
- return {"status": "dependency_missing", "dependency": "pypdf"}
66
+ PdfReader = None
67
+ if PdfReader is not None:
68
+ try:
69
+ reader = PdfReader(pdf)
70
+ pages = []
71
+ for index, page in enumerate(reader.pages, start=1):
72
+ text = (page.extract_text() or "").strip()
73
+ resources = page.get("/Resources") or {}
74
+ xobjects = resources.get("/XObject") if hasattr(resources, "get") else None
75
+ has_xobjects = bool(xobjects)
76
+ pages.append({"page": index, "text_characters": len(text), "has_xobjects": has_xobjects, "possibly_blank": not text and not has_xobjects})
77
+ return {"status": "ok", "backend": "pypdf", "pages": len(reader.pages), "page_checks": pages}
78
+ except Exception as error: # pypdf exposes parser-specific failures.
79
+ return {"status": "manual_review", "backend": "pypdf", "reason": str(error)}
80
+
81
+ pdf_module = None
51
82
  try:
52
- reader = PdfReader(pdf)
53
- pages = []
54
- for index, page in enumerate(reader.pages, start=1):
55
- text = (page.extract_text() or "").strip()
56
- resources = page.get("/Resources") or {}
57
- xobjects = resources.get("/XObject") if hasattr(resources, "get") else None
58
- has_xobjects = bool(xobjects)
59
- pages.append({"page": index, "text_characters": len(text), "has_xobjects": has_xobjects, "possibly_blank": not text and not has_xobjects})
60
- return {"status": "ok", "pages": len(reader.pages), "page_checks": pages}
61
- except Exception as error: # pypdf exposes parser-specific failures.
62
- return {"status": "manual_review", "reason": str(error)}
83
+ import pymupdf as pdf_module
84
+ except ImportError:
85
+ try:
86
+ import fitz as pdf_module
87
+ except ImportError:
88
+ pass
89
+ if pdf_module is not None:
90
+ try:
91
+ document = pdf_module.open(str(pdf))
92
+ pages = []
93
+ for index, page in enumerate(document, start=1):
94
+ text = (page.get_text() or "").strip()
95
+ has_xobjects = bool(page.get_images(full=True))
96
+ pages.append({"page": index, "text_characters": len(text), "has_xobjects": has_xobjects, "possibly_blank": not text and not has_xobjects})
97
+ return {"status": "ok", "backend": "pymupdf", "pages": len(document), "page_checks": pages}
98
+ except Exception as error:
99
+ return {"status": "manual_review", "backend": "pymupdf", "reason": str(error)}
100
+
101
+ pdfinfo = shutil.which("pdfinfo.exe") or shutil.which("pdfinfo")
102
+ if pdfinfo:
103
+ completed = subprocess.run([pdfinfo, str(pdf)], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, encoding="utf-8", errors="replace", check=False)
104
+ match = re.search(r"^Pages:\s+(\d+)\s*$", completed.stdout, re.MULTILINE | re.IGNORECASE)
105
+ if completed.returncode == 0 and match:
106
+ return {"status": "metadata_only", "backend": "pdfinfo", "pages": int(match.group(1)), "page_checks": []}
107
+ return {"status": "manual_review", "backend": "pdfinfo", "reason": completed.stdout[-500:]}
108
+ return {"status": "dependency_missing", "dependencies": ["pypdf", "pymupdf", "pdfinfo"]}
63
109
 
64
110
 
65
111
  def main() -> None:
@@ -73,6 +119,7 @@ def main() -> None:
73
119
  paper = root / "paper"
74
120
  findings: list[dict[str, str]] = []
75
121
  inventory: dict[str, list[str]] = {}
122
+ root_problem_files = [path for path in root.iterdir() if path.is_file() and not path.is_symlink() and path.suffix.lower() in PROBLEM_SUFFIXES]
76
123
  categories = {
77
124
  "problem_and_attachments": [root / "question"],
78
125
  "code": [root / "code"],
@@ -84,7 +131,9 @@ def main() -> None:
84
131
  files = []
85
132
  for base in bases:
86
133
  if base.is_dir():
87
- files.extend(path for path in base.rglob("*") if path.is_file() and not path.is_symlink())
134
+ files.extend(inventory_files(root, base))
135
+ if category == "problem_and_attachments":
136
+ files.extend(root_problem_files)
88
137
  if category == "tex":
89
138
  files = [path for path in files if path.suffix.lower() in {".tex", ".bib", ".cls", ".sty"}]
90
139
  inventory[category] = [relative(root, path) for path in sorted(files)]
@@ -118,8 +167,8 @@ def main() -> None:
118
167
  findings.append({"severity": "warning", "kind": "unreferenced_figure", "message": relative(root, figure)})
119
168
  question = next((part for part in figure.parts if re.fullmatch(r"q\d+", part)), None)
120
169
  if question:
121
- sources = [path for base in (root / "code" / question, root / "results" / question) if base.is_dir() for path in base.rglob("*") if path.is_file()]
122
- if latest_mtime(sources) > figure.stat().st_mtime:
170
+ sources = [path for base in (root / "results" / question,) if base.is_dir() for path in base.rglob("*") if path.is_file()]
171
+ if latest_mtime(sources) > figure.stat().st_mtime + FIGURE_STALE_TOLERANCE_SECONDS:
123
172
  findings.append({"severity": "warning", "kind": "possibly_stale_figure", "message": relative(root, figure)})
124
173
 
125
174
  question_sections = [path for path in (paper / "sections").glob("q*.tex") if re.fullmatch(r"q[1-9]\d*\.tex", path.name)] if (paper / "sections").is_dir() else []
@@ -129,7 +178,12 @@ def main() -> None:
129
178
  plain = re.sub(r"[{}%]", "", plain)
130
179
  if len(re.sub(r"\s+", "", plain)) < 500:
131
180
  findings.append({"severity": "warning", "kind": "thin_question_section", "message": relative(root, section)})
132
- required_groups = (("变量", "约束"), ("选择", "理由"), ("结果", "解释"), ("验证", "检验", "敏感", "稳健"))
181
+ required_groups = (
182
+ ("变量", "符号", "参数", "约束", "条件", "假设"),
183
+ ("选择", "理由", "原因", "采用", "建立", "基于", "考虑", "模型"),
184
+ ("结果", "解释", "表明", "说明", "可见", "得到", "结论", "分析"),
185
+ ("验证", "检验", "敏感", "稳健", "误差", "残差", "对比", "评估", "合理"),
186
+ )
133
187
  for group in required_groups:
134
188
  if not any(token in content for token in group):
135
189
  findings.append({"severity": "warning", "kind": "missing_reasoning_stage", "message": f"{relative(root, section)} lacks {'/'.join(group)}"})
@@ -153,6 +207,9 @@ def main() -> None:
153
207
  else:
154
208
  output_dir = paper / "build" / "page-review"
155
209
  output_dir.mkdir(parents=True, exist_ok=True)
210
+ for previous in output_dir.glob("page-*.png"):
211
+ if previous.is_file() and not previous.is_symlink():
212
+ previous.unlink()
156
213
  completed = subprocess.run([pdftoppm, "-png", "-r", "144", str(main_pdf), str(output_dir / "page")], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, encoding="utf-8", errors="replace", check=False)
157
214
  if completed.returncode:
158
215
  findings.append({"severity": "error", "kind": "render_failed", "message": completed.stdout[-500:]})
@@ -1,6 +1,7 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import argparse
4
+ import os
4
5
  import re
5
6
  import shutil
6
7
  import subprocess
@@ -80,10 +81,12 @@ def generate_appendices(root: Path, profile: dict[str, object]) -> None:
80
81
 
81
82
 
82
83
  def find_engine() -> tuple[list[str], str]:
84
+ xelatex = shutil.which("xelatex")
85
+ if os.name == "nt" and xelatex:
86
+ return [xelatex, "-interaction=nonstopmode", "-halt-on-error", "-file-line-error", "-output-directory=build", "main.tex"], "xelatex"
83
87
  latexmk = shutil.which("latexmk")
84
88
  if latexmk:
85
89
  return [latexmk, "-xelatex", "-interaction=nonstopmode", "-halt-on-error", "-file-line-error", "-outdir=build", "main.tex"], "latexmk"
86
- xelatex = shutil.which("xelatex")
87
90
  if xelatex:
88
91
  return [xelatex, "-interaction=nonstopmode", "-halt-on-error", "-file-line-error", "-output-directory=build", "main.tex"], "xelatex"
89
92
  raise SystemExit("Neither latexmk nor xelatex is available on PATH (TeX Live required).")
@@ -0,0 +1,107 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import hashlib
5
+ import json
6
+ from datetime import datetime, timezone
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from project_utils import iter_regular_files
11
+
12
+
13
+ EXCLUDED_PARTS = {"__pycache__", ".pytest_cache", ".mypy_cache", ".ruff_cache", "build"}
14
+ EVIDENCE_DIRECTORIES = ("results", "figures")
15
+
16
+
17
+ def sha256(path: Path) -> str:
18
+ digest = hashlib.sha256()
19
+ with path.open("rb") as stream:
20
+ for chunk in iter(lambda: stream.read(1024 * 1024), b""):
21
+ digest.update(chunk)
22
+ return digest.hexdigest()
23
+
24
+
25
+ def snapshot_evidence(root: Path) -> list[dict[str, Any]]:
26
+ entries: list[dict[str, Any]] = []
27
+ for directory in EVIDENCE_DIRECTORIES:
28
+ for path in iter_regular_files(root, directory, EXCLUDED_PARTS):
29
+ entries.append(
30
+ {
31
+ "path": path.relative_to(root).as_posix(),
32
+ "size_bytes": path.stat().st_size,
33
+ "sha256": sha256(path),
34
+ }
35
+ )
36
+ return sorted(entries, key=lambda item: str(item["path"]))
37
+
38
+
39
+ def freeze_path(root: Path) -> Path:
40
+ return root / "paper" / "evidence-freeze.json"
41
+
42
+
43
+ def load_freeze(root: Path) -> dict[str, Any] | None:
44
+ path = freeze_path(root)
45
+ if not path.is_file():
46
+ return None
47
+ payload = json.loads(path.read_text(encoding="utf-8"))
48
+ if not isinstance(payload, dict) or payload.get("schema_version") != 1 or not isinstance(payload.get("files"), list):
49
+ raise ValueError(f"invalid evidence freeze manifest: {path}")
50
+ return payload
51
+
52
+
53
+ def evidence_differences(root: Path) -> list[str]:
54
+ payload = load_freeze(root)
55
+ if payload is None:
56
+ return ["paper/evidence-freeze.json is missing"]
57
+ expected = {str(item["path"]): (int(item["size_bytes"]), str(item["sha256"])) for item in payload["files"] if isinstance(item, dict)}
58
+ actual = {str(item["path"]): (int(item["size_bytes"]), str(item["sha256"])) for item in snapshot_evidence(root)}
59
+ differences = [f"added evidence: {path}" for path in sorted(actual.keys() - expected.keys())]
60
+ differences.extend(f"removed evidence: {path}" for path in sorted(expected.keys() - actual.keys()))
61
+ differences.extend(f"changed evidence: {path}" for path in sorted(expected.keys() & actual.keys()) if expected[path] != actual[path])
62
+ return differences
63
+
64
+
65
+ def require_refresh_authorization(root: Path, refresh: bool) -> None:
66
+ if freeze_path(root).is_file() and not refresh:
67
+ raise SystemExit(
68
+ "Evidence is frozen by paper/evidence-freeze.json. Refusing to rerun code. "
69
+ "Use --refresh-evidence together with --run-code only after an explicit request to recompute results."
70
+ )
71
+
72
+
73
+ def write_freeze(root: Path) -> Path:
74
+ target = freeze_path(root)
75
+ target.parent.mkdir(parents=True, exist_ok=True)
76
+ payload = {
77
+ "schema_version": 1,
78
+ "state": "frozen",
79
+ "created_at": datetime.now(timezone.utc).isoformat(),
80
+ "files": snapshot_evidence(root),
81
+ }
82
+ temporary = target.with_name(f"{target.name}.tmp")
83
+ temporary.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
84
+ temporary.replace(target)
85
+ return target
86
+
87
+
88
+ def main() -> None:
89
+ parser = argparse.ArgumentParser(description="Create or verify the immutable numerical-evidence phase boundary.")
90
+ parser.add_argument("project_root", type=Path)
91
+ parser.add_argument("--write", action="store_true", help="replace the freeze manifest with the current results/figures snapshot")
92
+ args = parser.parse_args()
93
+ root = args.project_root.resolve()
94
+ if args.write:
95
+ path = write_freeze(root)
96
+ print(f"[OK] Evidence frozen: {path}")
97
+ return
98
+ differences = evidence_differences(root)
99
+ if differences:
100
+ for difference in differences:
101
+ print(f"[ERROR] {difference}")
102
+ raise SystemExit(1)
103
+ print(f"[OK] Evidence freeze verified: {freeze_path(root)}")
104
+
105
+
106
+ if __name__ == "__main__":
107
+ main()
@@ -5,6 +5,8 @@ import subprocess
5
5
  import sys
6
6
  from pathlib import Path
7
7
 
8
+ from evidence_freeze import require_refresh_authorization, write_freeze
9
+
8
10
 
9
11
  SCRIPT_ROOT = Path(__file__).resolve().parent
10
12
 
@@ -20,12 +22,16 @@ def main() -> None:
20
22
  parser = argparse.ArgumentParser(description="One-command execution, build, audit, package, and strict validation.")
21
23
  parser.add_argument("project_root", type=Path)
22
24
  parser.add_argument("--run-code", action="store_true", help="run code/run_all.py before building")
25
+ parser.add_argument("--refresh-evidence", action="store_true", help="explicitly authorize replacing an existing numerical-evidence freeze; requires --run-code")
23
26
  parser.add_argument("--strict-layout", action="store_true", help="fail on TeX underfull boxes as well as overfull boxes")
24
27
  parser.add_argument("--render-pages", action="store_true", help="render every final PDF page for visual review")
25
28
  parser.add_argument("--clean", action="store_true", help="remove deterministic caches after validation")
26
29
  args = parser.parse_args()
27
30
  root = args.project_root.resolve()
31
+ if args.refresh_evidence and not args.run_code:
32
+ raise SystemExit("--refresh-evidence requires --run-code")
28
33
  if args.run_code:
34
+ require_refresh_authorization(root, args.refresh_evidence)
29
35
  entry = root / "code" / "run_all.py"
30
36
  if not entry.is_file():
31
37
  raise SystemExit(f"Missing code entry point: {entry}")
@@ -38,6 +44,8 @@ def main() -> None:
38
44
  if args.render_pages:
39
45
  audit_flags.append("--render-pages")
40
46
  run("audit_paper.py", root, *audit_flags)
47
+ freeze = write_freeze(root)
48
+ print(f"[OK] Numerical evidence phase frozen: {freeze}")
41
49
  run("package_support.py", root)
42
50
  run("validate_project.py", root, "--strict")
43
51
  if args.clean:
@@ -122,19 +122,47 @@ def inspect_pdf(path: Path) -> dict[str, Any]:
122
122
  try:
123
123
  from pypdf import PdfReader
124
124
  except ImportError:
125
- pdfinfo = shutil.which("pdfinfo")
126
- if not pdfinfo:
127
- return result("dependency_missing", dependency="pypdf or Poppler", reason="cannot inspect PDF text/scans")
125
+ PdfReader = None
126
+ if PdfReader is not None:
127
+ try:
128
+ reader = PdfReader(path)
129
+ extracted = "".join((page.extract_text() or "") for page in reader.pages[: min(5, len(reader.pages))]).strip()
130
+ except Exception as error: # pypdf exposes several parser-specific exceptions.
131
+ return result("manual_review", reason=f"PDF extraction failed: {error}")
132
+ likely_scanned = len(extracted) < max(80, min(300, len(reader.pages) * 30))
133
+ return result("requires_ocr" if likely_scanned else "ok", backend="pypdf", pages=len(reader.pages), sampled_characters=len(extracted), likely_scanned=likely_scanned, text_excerpt=extracted[:50000])
134
+
135
+ pdf_module = None
136
+ try:
137
+ import pymupdf as pdf_module
138
+ except ImportError:
139
+ try:
140
+ import fitz as pdf_module
141
+ except ImportError:
142
+ pass
143
+ if pdf_module is not None:
144
+ try:
145
+ document = pdf_module.open(str(path))
146
+ extracted = "".join((document[index].get_text() or "") for index in range(min(5, len(document)))).strip()
147
+ likely_scanned = len(extracted) < max(80, min(300, len(document) * 30))
148
+ return result("requires_ocr" if likely_scanned else "ok", backend="pymupdf", pages=len(document), sampled_characters=len(extracted), likely_scanned=likely_scanned, text_excerpt=extracted[:50000])
149
+ except Exception as error:
150
+ return result("manual_review", reason=f"PDF extraction failed: {error}")
151
+
152
+ pdfinfo = shutil.which("pdfinfo.exe") or shutil.which("pdfinfo")
153
+ pdftotext = shutil.which("pdftotext.exe") or shutil.which("pdftotext")
154
+ if pdfinfo:
128
155
  completed = subprocess.run([pdfinfo, str(path)], text=True, encoding="utf-8", errors="replace", stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, check=False)
129
156
  match = re.search(r"^Pages:\s+(\d+)", completed.stdout, re.MULTILINE)
130
- return result("manual_review", pages=int(match.group(1)) if match else None, reason="text/scanned status not inspected")
131
- try:
132
- reader = PdfReader(path)
133
- extracted = "".join((page.extract_text() or "") for page in reader.pages[: min(5, len(reader.pages))]).strip()
134
- except Exception as error: # pypdf exposes several parser-specific exceptions.
135
- return result("manual_review", reason=f"PDF extraction failed: {error}")
136
- likely_scanned = len(extracted) < max(80, min(300, len(reader.pages) * 30))
137
- return result("requires_ocr" if likely_scanned else "ok", pages=len(reader.pages), sampled_characters=len(extracted), likely_scanned=likely_scanned, text_excerpt=extracted[:50000])
157
+ pages = int(match.group(1)) if match else None
158
+ if completed.returncode == 0 and pages and pdftotext:
159
+ text_process = subprocess.run([pdftotext, "-f", "1", "-l", str(min(5, pages)), str(path), "-"], text=True, encoding="utf-8", errors="replace", stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, check=False)
160
+ if text_process.returncode == 0:
161
+ extracted = text_process.stdout.strip()
162
+ likely_scanned = len(extracted) < max(80, min(300, pages * 30))
163
+ return result("requires_ocr" if likely_scanned else "ok", backend="poppler", pages=pages, sampled_characters=len(extracted), likely_scanned=likely_scanned, text_excerpt=extracted[:50000])
164
+ return result("manual_review", pages=pages, reason="text/scanned status not inspected")
165
+ return result("dependency_missing", dependency="pypdf, pymupdf, or Poppler", reason="cannot inspect PDF text/scans")
138
166
 
139
167
 
140
168
  def inspect_file(path: Path) -> dict[str, Any]:
@@ -154,23 +182,40 @@ def inspect_file(path: Path) -> dict[str, Any]:
154
182
  return result("unsupported", reason=f"unsupported extension {suffix or '[none]'}")
155
183
 
156
184
 
185
+ def discover_input_files(root: Path) -> list[Path]:
186
+ question = root / "question"
187
+ if question.exists() and (not question.is_dir() or question.is_symlink()):
188
+ raise SystemExit(f"Unsafe question path: {question}")
189
+ if question.is_dir():
190
+ question_files = sorted(path for path in question.rglob("*") if path.is_file())
191
+ if question_files:
192
+ return question_files
193
+
194
+ root_files = sorted(
195
+ path
196
+ for path in root.iterdir()
197
+ if path.is_file() and path.suffix.lower() in SUPPORTED
198
+ )
199
+ if root_files:
200
+ return root_files
201
+ raise SystemExit(
202
+ f"No supported problem inputs found in {question} or project root {root}"
203
+ )
204
+
205
+
157
206
  def main() -> None:
158
207
  parser = argparse.ArgumentParser(description="Inventory immutable question inputs.")
159
208
  parser.add_argument("project_root", type=Path)
160
209
  parser.add_argument("--refresh-baseline", action="store_true")
161
210
  args = parser.parse_args()
162
211
  root = args.project_root.resolve()
163
- question = root / "question"
164
- if not question.is_dir() or question.is_symlink():
165
- raise SystemExit(f"Missing or unsafe question directory: {question}")
166
212
 
167
213
  entries = []
168
- for path in sorted(question.rglob("*")):
214
+ for path in discover_input_files(root):
169
215
  if path.is_symlink():
170
216
  raise SystemExit(f"Symbolic links are not allowed in immutable input: {path}")
171
- if path.is_file():
172
- details = inspect_file(path)
173
- entries.append({"path": path.relative_to(root).as_posix(), "size_bytes": path.stat().st_size, "sha256": sha256(path), "supported": path.suffix.lower() in SUPPORTED, "status": details["status"], "details": details})
217
+ details = inspect_file(path)
218
+ entries.append({"path": path.relative_to(root).as_posix(), "size_bytes": path.stat().st_size, "sha256": sha256(path), "supported": path.suffix.lower() in SUPPORTED, "status": details["status"], "details": details})
174
219
 
175
220
  paper = root / "paper"
176
221
  paper.mkdir(parents=True, exist_ok=True)
@@ -36,6 +36,10 @@ def main() -> None:
36
36
  log = root / "paper" / "ai-use-log.md"
37
37
  if log.is_file() and not log.is_symlink():
38
38
  candidates.append(log)
39
+ freeze = root / "paper" / "evidence-freeze.json"
40
+ if not freeze.is_file() or freeze.is_symlink():
41
+ raise SystemExit("Missing paper/evidence-freeze.json; run the finalizer before packaging support files")
42
+ candidates.append(freeze)
39
43
 
40
44
  output.parent.mkdir(parents=True, exist_ok=True)
41
45
  with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_DEFLATED) as archive:
@@ -11,6 +11,10 @@ from pathlib import Path, PurePosixPath
11
11
  from typing import Any
12
12
 
13
13
  from project_utils import ensure_safe_file, load_profile, numeric_limit, question_numbers
14
+ from evidence_freeze import evidence_differences
15
+
16
+
17
+ INPUT_SUFFIXES = {".pdf", ".doc", ".docx", ".csv", ".tsv", ".xls", ".xlsx"}
14
18
 
15
19
 
16
20
  def sha256(path: Path) -> str:
@@ -219,12 +223,19 @@ def main() -> None:
219
223
  baseline = root / "paper" / "question-fingerprint.json"
220
224
  if not baseline.is_file():
221
225
  warnings.append("question fingerprint baseline is missing; run inspect_inputs.py")
222
- elif (root / "question").is_dir():
226
+ else:
223
227
  try:
224
228
  expected = {str(item["path"]): str(item["sha256"]) for item in read_json(baseline).get("files", [])}
225
- actual = {path.relative_to(root).as_posix(): sha256(path) for path in sorted((root / "question").rglob("*")) if path.is_file() and not path.is_symlink()}
229
+ candidates = []
230
+ question = root / "question"
231
+ if question.is_dir():
232
+ candidates.extend(path for path in question.rglob("*") if path.is_file())
233
+ candidates.extend(path for path in root.iterdir() if path.is_file() and path.suffix.lower() in INPUT_SUFFIXES)
234
+ if any(path.is_symlink() for path in candidates):
235
+ raise ValueError("symbolic input paths are not allowed")
236
+ actual = {path.relative_to(root).as_posix(): sha256(path) for path in sorted(set(candidates))}
226
237
  if actual != expected:
227
- errors.append("question/ changed after its fingerprint baseline was recorded")
238
+ errors.append("problem inputs changed after their fingerprint baseline was recorded")
228
239
  except (KeyError, OSError, ValueError, json.JSONDecodeError) as error:
229
240
  errors.append(f"invalid question fingerprint: {error}")
230
241
 
@@ -232,6 +243,12 @@ def main() -> None:
232
243
  if compile_result.returncode:
233
244
  errors.append("Python compile failed: " + compile_result.stdout.strip())
234
245
  validate_evidence(root, count, errors, warnings)
246
+ try:
247
+ frozen_differences = evidence_differences(root)
248
+ if frozen_differences:
249
+ errors.extend(frozen_differences)
250
+ except (KeyError, OSError, TypeError, ValueError, json.JSONDecodeError) as error:
251
+ errors.append(f"invalid evidence freeze: {error}")
235
252
 
236
253
  tex_files = [path for path in (root / "paper").rglob("*.tex") if path.is_file() and not path.is_symlink()]
237
254
  tex = "\n".join(path.read_text(encoding="utf-8", errors="replace") for path in tex_files)
@@ -275,6 +292,8 @@ def main() -> None:
275
292
  errors.append("support archive contains immutable question input files")
276
293
  if "paper/ai-use-log.md" in names and not bool(support_profile.get("include_ai_log")):
277
294
  errors.append("support archive leaks internal ai-use-log.md contrary to profile")
295
+ if "paper/evidence-freeze.json" not in names:
296
+ errors.append("support archive is missing paper/evidence-freeze.json")
278
297
  if bool(ai_profile.get("used")) and bool(ai_profile.get("details_pdf_required")) and "paper/AI工具使用详情.pdf" not in names:
279
298
  errors.append("support archive is missing required AI工具使用详情.pdf")
280
299
  except zipfile.BadZipFile: