@orbit-build/cli 0.4.4 → 0.4.5

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.
Files changed (44) hide show
  1. package/commands/math-draft.md +11 -0
  2. package/dist/index.js +103 -10
  3. package/package.json +4 -2
  4. package/skills/math-model-draft/SKILL.md +216 -0
  5. package/skills/math-model-draft/agents/openai.yaml +6 -0
  6. package/skills/math-model-draft/assets/project-template/code/always/__init__.py +1 -0
  7. package/skills/math-model-draft/assets/project-template/code/always/config.py +17 -0
  8. package/skills/math-model-draft/assets/project-template/code/always/data.py +23 -0
  9. package/skills/math-model-draft/assets/project-template/code/always/plotting.py +24 -0
  10. package/skills/math-model-draft/assets/project-template/code/always/validation.py +20 -0
  11. package/skills/math-model-draft/assets/project-template/code/finalize.py +55 -0
  12. package/skills/math-model-draft/assets/project-template/code/requirements.txt +11 -0
  13. package/skills/math-model-draft/assets/project-template/paper/AI/345/267/245/345/205/267/344/275/277/347/224/250/350/257/246/346/203/205.tex +34 -0
  14. package/skills/math-model-draft/assets/project-template/paper/ai-use-log.md +7 -0
  15. package/skills/math-model-draft/assets/project-template/paper/contest-profile.json +25 -0
  16. package/skills/math-model-draft/assets/project-template/paper/main.tex +53 -0
  17. package/skills/math-model-draft/assets/project-template/paper/sections/abstract.tex +6 -0
  18. package/skills/math-model-draft/assets/project-template/paper/sections/ai-disclosure.tex +3 -0
  19. package/skills/math-model-draft/assets/project-template/paper/sections/appendix.tex +9 -0
  20. package/skills/math-model-draft/assets/project-template/paper/sections/assumptions.tex +5 -0
  21. package/skills/math-model-draft/assets/project-template/paper/sections/data.tex +19 -0
  22. package/skills/math-model-draft/assets/project-template/paper/sections/evaluation.tex +9 -0
  23. package/skills/math-model-draft/assets/project-template/paper/sections/problem-analysis.tex +3 -0
  24. package/skills/math-model-draft/assets/project-template/paper/sections/problem-restatement.tex +3 -0
  25. package/skills/math-model-draft/assets/project-template/paper/sections/references.tex +6 -0
  26. package/skills/math-model-draft/assets/project-template/paper/sections/source-code.tex +1 -0
  27. package/skills/math-model-draft/assets/project-template/paper/sections/support-files.tex +3 -0
  28. package/skills/math-model-draft/references/code-and-output-style.md +91 -0
  29. package/skills/math-model-draft/references/cumcm-compliance.md +56 -0
  30. package/skills/math-model-draft/references/latex-figures-tables.md +60 -0
  31. package/skills/math-model-draft/references/modeling-quality.md +91 -0
  32. package/skills/math-model-draft/references/paper-architecture.md +125 -0
  33. package/skills/math-model-draft/references/paper-revision.md +76 -0
  34. package/skills/math-model-draft/references/project-architecture.md +65 -0
  35. package/skills/math-model-draft/scripts/audit_paper.py +185 -0
  36. package/skills/math-model-draft/scripts/bootstrap_project.py +275 -0
  37. package/skills/math-model-draft/scripts/build_paper.py +226 -0
  38. package/skills/math-model-draft/scripts/capture_environment.py +46 -0
  39. package/skills/math-model-draft/scripts/clean_project.py +46 -0
  40. package/skills/math-model-draft/scripts/finalize_project.py +49 -0
  41. package/skills/math-model-draft/scripts/inspect_inputs.py +193 -0
  42. package/skills/math-model-draft/scripts/package_support.py +52 -0
  43. package/skills/math-model-draft/scripts/project_utils.py +106 -0
  44. package/skills/math-model-draft/scripts/validate_project.py +313 -0
@@ -0,0 +1,76 @@
1
+ # Existing-paper revision and consistency audit
2
+
3
+ Use this workflow when a project already contains TeX/PDF, code, outputs, or
4
+ reference papers. The objective is to make the submitted paper true, complete,
5
+ and readable while preserving good authored work.
6
+
7
+ ## Read before editing
8
+
9
+ Inventory and read, where present:
10
+
11
+ - problem statements, official templates, rules, and attachments;
12
+ - the newest code tree and its configuration/entry points;
13
+ - `results/` machine-readable outputs and `figures/`;
14
+ - all TeX entry points, included sections, bibliography, and current PDF;
15
+ - excellent/reference papers, especially their final results tables.
16
+
17
+ Resolve ambiguous “latest” directories by modification time plus entry-point
18
+ references. Do not infer currency from a folder name alone.
19
+
20
+ ## Question-by-question completeness
21
+
22
+ Each question should form a traceable argument:
23
+
24
+ 1. what the question asks and what is delivered;
25
+ 2. variables, targets, units, constraints, and upstream inputs;
26
+ 3. why the chosen model fits better than plausible alternatives;
27
+ 4. equations and parameter provenance;
28
+ 5. solver/algorithm steps matching the actual implementation;
29
+ 6. numerical results sourced from JSON/CSV/XLSX;
30
+ 7. interpretation in the problem's terms;
31
+ 8. appropriate validation, sensitivity, uncertainty, or baseline comparison;
32
+ 9. direct conclusion and link to the next question.
33
+
34
+ Thin prose is repaired with local evidence-backed additions. Do not add a
35
+ method simply because another paper uses it.
36
+
37
+ ## Numerical cross-check
38
+
39
+ Build a ledger for every material value: source path and field, paper locations,
40
+ unit, transformation, precision, and status. Compare abstract, body, tables,
41
+ captions, figures, conclusions, and appendices. Check negative signs, percentage
42
+ versus fraction, coordinate/order conventions, constraint directions, and
43
+ rounding. A program-generated JSON/CSV value wins over a hand-entered TeX value
44
+ unless code/output is proven stale and rerun.
45
+
46
+ ## Figures and tables
47
+
48
+ Confirm each figure was produced by current code, appears near first discussion,
49
+ has a preceding textual reference, and receives interpretation beyond repeating
50
+ its caption. Check Chinese fonts, legends, units, resolution, clipping, overlap,
51
+ float drift, cross-question placement, and blank-page/whitespace effects. Remove
52
+ obsolete figures only when provenance proves they are generated duplicates and
53
+ the deletion is safe; otherwise report them.
54
+
55
+ For comparisons with excellent papers, use their final result table as the
56
+ paper's authoritative value and verify that aliases such as “论文1/2/3” match
57
+ table columns, prose, and bibliography entries.
58
+
59
+ ## Editing boundaries
60
+
61
+ - Preserve the abstract's information density. Each question should retain its
62
+ model, algorithm, key numerical result, and conclusion.
63
+ - Prefer localized additions, factual corrections, and float placement fixes.
64
+ - Do not change global spacing or reformat the entire paper unless a verified
65
+ layout defect requires it.
66
+ - Regenerate pasted code appendices from current source; do not hand-maintain
67
+ stale listings.
68
+ - Do not delete important or unknown materials. Ask only when a model direction
69
+ would change or a deletion cannot be proven safe.
70
+
71
+ ## Final QA
72
+
73
+ Compile with local TeX Live. Inspect the actual final PDF page by page and the
74
+ log for missing glyphs, undefined citations/references, overfull/underfull boxes,
75
+ blank pages, orphan headings, table/figure overflow, and abnormal whitespace.
76
+ Clean only deterministic caches and temporary page renders after QA.
@@ -0,0 +1,65 @@
1
+ # Project architecture
2
+
3
+ Use one stable project root. Keep inputs, code, paper, results, and figures
4
+ separate so a human can replace any layer without reorganizing the project.
5
+
6
+ ```text
7
+ project-root/
8
+ ├── question/ # Immutable problem PDF/DOCX and source data
9
+ ├── code/
10
+ │ ├── requirements.txt
11
+ │ ├── run_all.py
12
+ │ ├── always/ # Shared configuration, data, plotting, checks
13
+ │ ├── q1/
14
+ │ ├── q2/
15
+ │ └── ...
16
+ ├── results/
17
+ │ ├── q1/ # Tables, metrics, filled workbooks, models
18
+ │ ├── q2/
19
+ │ └── ...
20
+ ├── figures/
21
+ │ ├── q1/ # Final paper-ready figures only
22
+ │ ├── q2/
23
+ │ └── ...
24
+ └── paper/
25
+ ├── main.tex
26
+ ├── references.bib
27
+ ├── evidence-map.yaml
28
+ ├── sections/
29
+ │ ├── q1.tex
30
+ │ ├── q2.tex
31
+ │ └── ...
32
+ └── build/ # LaTeX intermediates and final PDF
33
+ ```
34
+
35
+ ## Ownership rules
36
+
37
+ - `question/` is read-only. Never normalize, rename, fill, or save over input.
38
+ - Ignore blank workbooks/sheets unless the statement explicitly assigns them a
39
+ role. Record that they were blank.
40
+ - A required filled table belongs in `results/qN`, even when its blank template
41
+ came from `question/`.
42
+ - `code/always` contains only logic used by two or more subproblems.
43
+ - Each `code/qN/main.py` must run independently after its prerequisites exist.
44
+ - `code/run_all.py` runs subproblems in dependency order.
45
+ - `results/qN` owns numeric and tabular evidence for subproblem N.
46
+ - `figures/qN` owns final visuals for subproblem N. Put diagnostic-only images
47
+ in a temporary build directory and remove them before handoff.
48
+ - `paper/sections/qN.tex` may consume only declared evidence from matching or
49
+ explicitly upstream result directories.
50
+
51
+ ## Naming
52
+
53
+ - Use `q1`, `q2`, ... exactly; do not mix `Q1`, `question1`, or Chinese folder
54
+ names.
55
+ - Prefer descriptive Chinese artifact names when they improve hand editing.
56
+ - Use stable ASCII Python module names.
57
+ - Use UTF-8 for text and UTF-8 with BOM for CSV intended for Excel.
58
+ - Include units in column labels or metadata.
59
+
60
+ ## Compatibility with legacy reproduction folders
61
+
62
+ Some existing projects place `question/` next to a `reproduce/` directory.
63
+ Read those inputs in place, but do not move them automatically. For a new
64
+ project, make `question/` a peer of `code/`, `results/`, `figures/`, and
65
+ `paper/` as the canonical structure above.
@@ -0,0 +1,185 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ import re
6
+ import shutil
7
+ import subprocess
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+
12
+ FIGURE_SUFFIXES = {".pdf", ".png", ".jpg", ".jpeg", ".eps", ".svg"}
13
+
14
+
15
+ def relative(root: Path, path: Path) -> str:
16
+ try:
17
+ return path.resolve().relative_to(root.resolve()).as_posix()
18
+ except ValueError:
19
+ return str(path)
20
+
21
+
22
+ def resolve_tex_asset(root: Path, paper: Path, raw: str, suffixes: tuple[str, ...]) -> Path | None:
23
+ normalized = raw.strip().replace("\\", "/")
24
+ candidates = [paper / normalized, root / normalized, root / "figures" / normalized]
25
+ expanded = []
26
+ for candidate in candidates:
27
+ expanded.append(candidate)
28
+ if not candidate.suffix:
29
+ expanded.extend(candidate.with_suffix(suffix) for suffix in suffixes)
30
+ for candidate in expanded:
31
+ try:
32
+ candidate.resolve().relative_to(root.resolve())
33
+ except ValueError:
34
+ continue
35
+ if candidate.is_file() and not candidate.is_symlink():
36
+ return candidate.resolve()
37
+ return None
38
+
39
+
40
+ def latest_mtime(paths: list[Path]) -> float:
41
+ return max((path.stat().st_mtime for path in paths if path.is_file()), default=0.0)
42
+
43
+
44
+ def inspect_pdf(pdf: Path) -> dict[str, Any]:
45
+ if not pdf.is_file():
46
+ return {"status": "missing"}
47
+ try:
48
+ from pypdf import PdfReader
49
+ except ImportError:
50
+ return {"status": "dependency_missing", "dependency": "pypdf"}
51
+ 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)}
63
+
64
+
65
+ def main() -> None:
66
+ parser = argparse.ArgumentParser(description="Audit TeX/PDF, figures, results, code, and reference-paper consistency surfaces.")
67
+ parser.add_argument("project_root", type=Path)
68
+ parser.add_argument("--render-pages", action="store_true")
69
+ parser.add_argument("--fail-on-findings", action="store_true")
70
+ parser.add_argument("--fail-on-errors", action="store_true")
71
+ args = parser.parse_args()
72
+ root = args.project_root.resolve()
73
+ paper = root / "paper"
74
+ findings: list[dict[str, str]] = []
75
+ inventory: dict[str, list[str]] = {}
76
+ categories = {
77
+ "problem_and_attachments": [root / "question"],
78
+ "code": [root / "code"],
79
+ "results": [root / "results"],
80
+ "figures": [root / "figures"],
81
+ "tex": [paper],
82
+ }
83
+ for category, bases in categories.items():
84
+ files = []
85
+ for base in bases:
86
+ if base.is_dir():
87
+ files.extend(path for path in base.rglob("*") if path.is_file() and not path.is_symlink())
88
+ if category == "tex":
89
+ files = [path for path in files if path.suffix.lower() in {".tex", ".bib", ".cls", ".sty"}]
90
+ inventory[category] = [relative(root, path) for path in sorted(files)]
91
+ reference_dirs = [path for path in root.rglob("*") if path.is_dir() and re.search(r"优秀|参考论文|excellent|reference.?paper", path.name, re.IGNORECASE)]
92
+ inventory["reference_papers"] = [relative(root, path) for base in reference_dirs for path in sorted(base.rglob("*")) if path.is_file() and not path.is_symlink()]
93
+
94
+ tex_files = [path for path in paper.rglob("*.tex") if path.is_file() and not path.is_symlink()]
95
+ tex_texts = {path: path.read_text(encoding="utf-8", errors="replace") for path in tex_files}
96
+ combined = "\n".join(tex_texts.values())
97
+ for source, content in tex_texts.items():
98
+ for raw in re.findall(r"\\(?:input|include)\{([^}]+)\}", content):
99
+ if resolve_tex_asset(root, paper, raw, (".tex",)) is None:
100
+ findings.append({"severity": "error", "kind": "missing_tex_input", "message": f"{relative(root, source)} -> {raw}"})
101
+ for raw in re.findall(r"\\includegraphics(?:\[[^]]*\])?\{([^}]+)\}", content):
102
+ if resolve_tex_asset(root, paper, raw, tuple(FIGURE_SUFFIXES)) is None:
103
+ findings.append({"severity": "error", "kind": "missing_figure", "message": f"{relative(root, source)} -> {raw}"})
104
+
105
+ labels = set(re.findall(r"\\label\{([^}]+)\}", combined))
106
+ refs = set(re.findall(r"\\(?:ref|eqref|pageref)\{([^}]+)\}", combined))
107
+ for key in sorted(refs - labels):
108
+ findings.append({"severity": "error", "kind": "undefined_label", "message": key})
109
+ citations = set(item.strip() for group in re.findall(r"\\cite\{([^}]+)\}", combined) for item in group.split(","))
110
+ bibliography_keys = set(re.findall(r"\\bibitem(?:\[[^]]*\])?\{([^}]+)\}", combined))
111
+ for key in sorted(citations - bibliography_keys):
112
+ findings.append({"severity": "error", "kind": "undefined_citation", "message": key})
113
+
114
+ referenced_names = {Path(raw.replace("\\", "/")).stem.lower() for raw in re.findall(r"\\includegraphics(?:\[[^]]*\])?\{([^}]+)\}", combined)}
115
+ figure_files = [path for path in (root / "figures").rglob("*") if path.is_file() and path.suffix.lower() in FIGURE_SUFFIXES and not path.is_symlink()] if (root / "figures").is_dir() else []
116
+ for figure in figure_files:
117
+ if figure.stem.lower() not in referenced_names:
118
+ findings.append({"severity": "warning", "kind": "unreferenced_figure", "message": relative(root, figure)})
119
+ question = next((part for part in figure.parts if re.fullmatch(r"q\d+", part)), None)
120
+ 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:
123
+ findings.append({"severity": "warning", "kind": "possibly_stale_figure", "message": relative(root, figure)})
124
+
125
+ 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 []
126
+ for section in sorted(question_sections):
127
+ content = tex_texts.get(section, "")
128
+ plain = re.sub(r"\\[A-Za-z@]+\*?(?:\[[^]]*\])?", "", content)
129
+ plain = re.sub(r"[{}%]", "", plain)
130
+ if len(re.sub(r"\s+", "", plain)) < 500:
131
+ findings.append({"severity": "warning", "kind": "thin_question_section", "message": relative(root, section)})
132
+ required_groups = (("变量", "约束"), ("选择", "理由"), ("结果", "解释"), ("验证", "检验", "敏感", "稳健"))
133
+ for group in required_groups:
134
+ if not any(token in content for token in group):
135
+ findings.append({"severity": "warning", "kind": "missing_reasoning_stage", "message": f"{relative(root, section)} lacks {'/'.join(group)}"})
136
+
137
+ main_pdf = paper / "main.pdf"
138
+ source_files = tex_files + [path for base_name in ("code", "results", "figures") for path in (root / base_name).rglob("*") if path.is_file()] if all((root / name).exists() for name in ("code", "results", "figures")) else tex_files
139
+ if not main_pdf.is_file():
140
+ findings.append({"severity": "error", "kind": "missing_pdf", "message": "paper/main.pdf"})
141
+ elif latest_mtime(source_files) > main_pdf.stat().st_mtime:
142
+ findings.append({"severity": "warning", "kind": "stale_pdf", "message": "paper/main.pdf is older than TeX/code/results/figures"})
143
+ pdf_check = inspect_pdf(main_pdf)
144
+ for page in pdf_check.get("page_checks", []):
145
+ if page.get("possibly_blank"):
146
+ findings.append({"severity": "error", "kind": "possibly_blank_page", "message": f"paper/main.pdf page {page['page']}"})
147
+
148
+ rendered: list[str] = []
149
+ if args.render_pages and main_pdf.is_file():
150
+ pdftoppm = shutil.which("pdftoppm.exe") or shutil.which("pdftoppm")
151
+ if not pdftoppm:
152
+ findings.append({"severity": "warning", "kind": "render_dependency_missing", "message": "pdftoppm not found"})
153
+ else:
154
+ output_dir = paper / "build" / "page-review"
155
+ output_dir.mkdir(parents=True, exist_ok=True)
156
+ 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
+ if completed.returncode:
158
+ findings.append({"severity": "error", "kind": "render_failed", "message": completed.stdout[-500:]})
159
+ else:
160
+ rendered = [relative(root, path) for path in sorted(output_dir.glob("page-*.png"))]
161
+
162
+ report = {
163
+ "schema_version": 1,
164
+ "project_root": str(root),
165
+ "inventory": inventory,
166
+ "pdf": pdf_check,
167
+ "rendered_pages": rendered,
168
+ "findings": findings,
169
+ "summary": {"errors": sum(item["severity"] == "error" for item in findings), "warnings": sum(item["severity"] == "warning" for item in findings)},
170
+ }
171
+ output = paper / "build" / "revision-audit.json"
172
+ output.parent.mkdir(parents=True, exist_ok=True)
173
+ output.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
174
+ print(f"[RUN] Paper audit: {report['summary']['errors']} error(s), {report['summary']['warnings']} warning(s)")
175
+ for item in findings:
176
+ print(f"[{item['severity'].upper()}] {item['kind']}: {item['message']}")
177
+ print(f"[OK] Audit report: {output}")
178
+ if args.fail_on_findings and findings:
179
+ raise SystemExit(1)
180
+ if args.fail_on_errors and report["summary"]["errors"]:
181
+ raise SystemExit(1)
182
+
183
+
184
+ if __name__ == "__main__":
185
+ main()
@@ -0,0 +1,275 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ import re
6
+ import shutil
7
+ from pathlib import Path
8
+
9
+ from project_utils import question_numbers
10
+
11
+
12
+ SKILL_ROOT = Path(__file__).resolve().parents[1]
13
+ TEMPLATE_ROOT = SKILL_ROOT / "assets" / "project-template"
14
+
15
+
16
+ def main() -> None:
17
+ parser = argparse.ArgumentParser(
18
+ description="Create or extend a non-destructive modeling project skeleton."
19
+ )
20
+ parser.add_argument("project_root", type=Path)
21
+ parser.add_argument("--questions", type=int, required=True)
22
+ args = parser.parse_args()
23
+ if not 1 <= args.questions <= 20:
24
+ raise SystemExit("--questions must be between 1 and 20.")
25
+
26
+ root = args.project_root.resolve()
27
+ created: list[str] = []
28
+ updated: list[str] = []
29
+ preserved: list[str] = []
30
+ for directory in (
31
+ root / "question",
32
+ root / "code" / "always",
33
+ root / "paper" / "sections",
34
+ root / "paper" / "build",
35
+ ):
36
+ directory.mkdir(parents=True, exist_ok=True)
37
+
38
+ declared = read_declared_count(root)
39
+ discovered = max(question_numbers(root), default=0)
40
+ question_count = max(args.questions, declared, discovered)
41
+ copy_template_tree(root, created, preserved)
42
+ create_question_files(root, question_count, created, updated, preserved)
43
+ extend_evidence_map(root, question_count, created, updated)
44
+
45
+ print(f"[OK] Project skeleton ready: {root}")
46
+ print(
47
+ f" Questions: {question_count}; created {len(created)}, "
48
+ f"updated {len(updated)}, preserved {len(preserved)} file(s)."
49
+ )
50
+ if updated:
51
+ print(" Updated orchestrators: " + ", ".join(updated))
52
+
53
+
54
+ def read_declared_count(root: Path) -> int:
55
+ path = root / "paper" / "question-count.json"
56
+ if not path.is_file():
57
+ return 0
58
+ try:
59
+ count = int(json.loads(path.read_text(encoding="utf-8")).get("questions", 0))
60
+ except (OSError, ValueError, json.JSONDecodeError):
61
+ return 0
62
+ return count if 1 <= count <= 20 else 0
63
+
64
+
65
+ def copy_template_tree(root: Path, created: list[str], preserved: list[str]) -> None:
66
+ for source in TEMPLATE_ROOT.rglob("*"):
67
+ if not source.is_file():
68
+ continue
69
+ relative = source.relative_to(TEMPLATE_ROOT)
70
+ target = root / relative
71
+ target.parent.mkdir(parents=True, exist_ok=True)
72
+ if target.exists():
73
+ preserved.append(relative.as_posix())
74
+ else:
75
+ shutil.copy2(source, target)
76
+ created.append(relative.as_posix())
77
+
78
+
79
+ def create_question_files(
80
+ root: Path,
81
+ count: int,
82
+ created: list[str],
83
+ updated: list[str],
84
+ preserved: list[str],
85
+ ) -> None:
86
+ for number in range(1, count + 1):
87
+ name = f"q{number}"
88
+ for directory in (root / "code" / name, root / "results" / name, root / "figures" / name):
89
+ directory.mkdir(parents=True, exist_ok=True)
90
+ files = {
91
+ root / "code" / name / "__init__.py": "",
92
+ root / "code" / name / "main.py": question_main(name),
93
+ root / "code" / name / "model.py": question_model(name),
94
+ root / "code" / name / "output.py": question_output(),
95
+ root / "paper" / "sections" / f"{name}.tex": question_tex(number),
96
+ }
97
+ for path, content in files.items():
98
+ write_if_missing(root, path, content, created, preserved)
99
+
100
+ merge_questions_tex(root, count, created, updated)
101
+ merge_run_all(root, count, created, updated)
102
+ write_count(root, count, created, updated)
103
+
104
+
105
+ def merge_questions_tex(root: Path, count: int, created: list[str], updated: list[str]) -> None:
106
+ path = root / "paper" / "sections" / "questions.tex"
107
+ if not path.exists():
108
+ path.write_text("".join(f"\\input{{sections/q{i}}}\n" for i in range(1, count + 1)), encoding="utf-8")
109
+ created.append(path.relative_to(root).as_posix())
110
+ return
111
+ content = path.read_text(encoding="utf-8")
112
+ additions = [f"\\input{{sections/q{i}}}" for i in range(1, count + 1) if not re.search(rf"\\input\{{sections/q{i}\}}", content)]
113
+ if additions:
114
+ path.write_text(content.rstrip() + "\n" + "\n".join(additions) + "\n", encoding="utf-8")
115
+ updated.append(path.relative_to(root).as_posix())
116
+
117
+
118
+ def merge_run_all(root: Path, count: int, created: list[str], updated: list[str]) -> None:
119
+ path = root / "code" / "run_all.py"
120
+ if not path.exists():
121
+ path.write_text(run_all(count), encoding="utf-8")
122
+ created.append(path.relative_to(root).as_posix())
123
+ return
124
+ content = path.read_text(encoding="utf-8")
125
+ missing = [f'q{i}.main' for i in range(1, count + 1) if f'"q{i}.main"' not in content and f"'q{i}.main'" not in content]
126
+ if not missing:
127
+ return
128
+ match = re.search(r"(?ms)(^\s*modules\s*=\s*\[.*?)(^\s*\])", content)
129
+ if not match:
130
+ print(f"[WARN] Preserved custom run_all.py; add manually: {', '.join(missing)}")
131
+ return
132
+ indent = re.match(r"\s*", match.group(2)).group(0)
133
+ rows = "".join(f'{indent} "{module}",\n' for module in missing)
134
+ content = content[: match.start(2)] + rows + content[match.start(2) :]
135
+ path.write_text(content, encoding="utf-8")
136
+ updated.append(path.relative_to(root).as_posix())
137
+
138
+
139
+ def write_count(root: Path, count: int, created: list[str], updated: list[str]) -> None:
140
+ path = root / "paper" / "question-count.json"
141
+ existing: dict[str, object] = {}
142
+ if path.is_file():
143
+ try:
144
+ payload = json.loads(path.read_text(encoding="utf-8"))
145
+ if isinstance(payload, dict):
146
+ existing = payload
147
+ except (OSError, json.JSONDecodeError):
148
+ pass
149
+ existing["questions"] = count
150
+ existing["support_paths"] = [item for i in range(1, count + 1) for item in (f"code/q{i}", f"results/q{i}", f"figures/q{i}")]
151
+ rendered = json.dumps(existing, ensure_ascii=False, indent=2) + "\n"
152
+ if path.exists() and path.read_text(encoding="utf-8") == rendered:
153
+ return
154
+ was_present = path.exists()
155
+ path.write_text(rendered, encoding="utf-8")
156
+ (updated if was_present else created).append(path.relative_to(root).as_posix())
157
+
158
+
159
+ def extend_evidence_map(root: Path, count: int, created: list[str], updated: list[str]) -> None:
160
+ path = root / "paper" / "evidence-map.yaml"
161
+ content = path.read_text(encoding="utf-8") if path.exists() else "# Claims must resolve to program-generated evidence.\n"
162
+ additions: list[str] = []
163
+ for i in range(1, count + 1):
164
+ if not re.search(rf"(?m)^q{i}:\s*$", content):
165
+ additions.extend([f"q{i}:", " claims:", f" - id: q{i}-main-result", f" source: results/q{i}/summary.json", f" paper_section: paper/sections/q{i}.tex", " status: TODO"])
166
+ if not additions:
167
+ return
168
+ rendered = content.rstrip() + "\n" + "\n".join(additions) + "\n"
169
+ existed = path.exists()
170
+ path.write_text(rendered, encoding="utf-8")
171
+ (updated if existed else created).append(path.relative_to(root).as_posix())
172
+
173
+
174
+ def write_if_missing(root: Path, path: Path, content: str, created: list[str], preserved: list[str]) -> None:
175
+ relative = path.relative_to(root).as_posix()
176
+ if path.exists():
177
+ preserved.append(relative)
178
+ return
179
+ path.parent.mkdir(parents=True, exist_ok=True)
180
+ path.write_text(content, encoding="utf-8")
181
+ created.append(relative)
182
+
183
+
184
+ def question_main(name: str) -> str:
185
+ return f'''from __future__ import annotations
186
+
187
+ from always.config import question_output_dirs
188
+ from {name}.model import solve
189
+ from {name}.output import save_outputs
190
+
191
+
192
+ def main() -> None:
193
+ results_dir, figure_dir = question_output_dirs("{name}")
194
+ result = solve()
195
+ save_outputs(result, results_dir, figure_dir)
196
+ print("[OK] {name} completed")
197
+
198
+
199
+ if __name__ == "__main__":
200
+ main()
201
+ '''
202
+
203
+
204
+ def question_model(name: str) -> str:
205
+ return f'''from __future__ import annotations
206
+
207
+
208
+ def solve() -> dict[str, object]:
209
+ # Replace only after inputs, assumptions, constraints, and units are audited.
210
+ return {{"question": "{name}", "status": "TODO", "claims": []}}
211
+ '''
212
+
213
+
214
+ def question_output() -> str:
215
+ return '''from __future__ import annotations
216
+
217
+ import json
218
+ from pathlib import Path
219
+
220
+
221
+ def save_outputs(result: dict[str, object], results_dir: Path, figure_dir: Path) -> None:
222
+ results_dir.mkdir(parents=True, exist_ok=True)
223
+ figure_dir.mkdir(parents=True, exist_ok=True)
224
+ (results_dir / "summary.json").write_text(
225
+ json.dumps(result, ensure_ascii=False, indent=2) + "\\n", encoding="utf-8"
226
+ )
227
+ '''
228
+
229
+
230
+ def question_tex(number: int) -> str:
231
+ return rf'''\section{{问题{number}:TODO[写明本题目标]}}
232
+
233
+ \subsection{{题意、变量与约束}}
234
+ \TODO{{明确本题交付、变量、单位、目标、约束及其与前后小题的数据关系。}}
235
+
236
+ \subsection{{方法选择与模型建立}}
237
+ \TODO{{比较候选方法,说明选择理由,给出公式、参数来源和实际求解算法。}}
238
+
239
+ \subsection{{结果与解释}}
240
+ \TODO{{从 results/q{number}/ 引用实际数值,引用 figures/q{number}/ 的当前图并解释。}}
241
+
242
+ \subsection{{验证、小结与衔接}}
243
+ \TODO{{报告适当的误差、敏感性、稳健性或基线比较,回答本题并衔接下一问。}}
244
+ '''
245
+
246
+
247
+ def run_all(count: int) -> str:
248
+ rows = "".join(f' "q{i}.main",\n' for i in range(1, count + 1))
249
+ return f'''from __future__ import annotations
250
+
251
+ import importlib
252
+ import sys
253
+ from pathlib import Path
254
+
255
+ CODE_ROOT = Path(__file__).resolve().parent
256
+ sys.path.insert(0, str(CODE_ROOT))
257
+ sys.dont_write_bytecode = True
258
+
259
+
260
+ def main() -> None:
261
+ modules = [
262
+ {rows} ]
263
+ for module in modules:
264
+ print(f"[RUN] {{module.split('.', maxsplit=1)[0]}}")
265
+ importlib.import_module(module).main()
266
+ print(f"[OK] All questions completed: {{CODE_ROOT.parent}}")
267
+
268
+
269
+ if __name__ == "__main__":
270
+ main()
271
+ '''
272
+
273
+
274
+ if __name__ == "__main__":
275
+ main()