@orbit-build/cli 0.5.6 → 0.5.7

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 (56) hide show
  1. package/README.md +4 -0
  2. package/commands/cumcm-draft.md +11 -0
  3. package/commands/math-draft.md +4 -8
  4. package/dist/index.js +380 -240
  5. package/package.json +1 -1
  6. package/skills/{math-model-draft → cumcm-draft}/SKILL.md +124 -27
  7. package/skills/cumcm-draft/agents/openai.yaml +6 -0
  8. package/skills/{math-model-draft → cumcm-draft}/assets/project-template/code/always/config.py +1 -0
  9. package/skills/{math-model-draft → cumcm-draft}/assets/project-template/code/always/data.py +1 -0
  10. package/skills/{math-model-draft → cumcm-draft}/assets/project-template/code/always/plotting.py +1 -0
  11. package/skills/{math-model-draft → cumcm-draft}/assets/project-template/code/always/validation.py +1 -0
  12. package/skills/{math-model-draft → cumcm-draft}/assets/project-template/code/finalize.py +9 -3
  13. package/skills/{math-model-draft → cumcm-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 +12 -3
  14. package/skills/{math-model-draft → cumcm-draft}/assets/project-template/paper/contest-profile.json +7 -4
  15. package/skills/{math-model-draft → cumcm-draft}/assets/project-template/paper/main.tex +28 -0
  16. package/skills/cumcm-draft/assets/project-template/paper/sections/ai-disclosure.tex +3 -0
  17. package/skills/cumcm-draft/assets/project-template/paper/sections/appendix.tex +3 -0
  18. package/skills/cumcm-draft/assets/project-template/paper/sections/references.tex +12 -0
  19. package/skills/{math-model-draft → cumcm-draft}/references/code-and-output-style.md +37 -6
  20. package/skills/cumcm-draft/references/cumcm-compliance.md +64 -0
  21. package/skills/{math-model-draft → cumcm-draft}/references/latex-figures-tables.md +5 -0
  22. package/skills/cumcm-draft/references/modeling-quality.md +161 -0
  23. package/skills/{math-model-draft → cumcm-draft}/references/paper-architecture.md +51 -5
  24. package/skills/cumcm-draft/references/project-architecture.md +124 -0
  25. package/skills/{math-model-draft → cumcm-draft}/scripts/audit_paper.py +40 -0
  26. package/skills/{math-model-draft → cumcm-draft}/scripts/bootstrap_project.py +44 -42
  27. package/skills/{math-model-draft → cumcm-draft}/scripts/build_paper.py +76 -5
  28. package/skills/{math-model-draft → cumcm-draft}/scripts/clean_project.py +7 -1
  29. package/skills/{math-model-draft → cumcm-draft}/scripts/package_support.py +8 -1
  30. package/skills/{math-model-draft → cumcm-draft}/scripts/project_utils.py +12 -9
  31. package/skills/{math-model-draft → cumcm-draft}/scripts/validate_project.py +191 -6
  32. package/skills/mcm-draft/SKILL.md +11 -0
  33. package/skills/mcm-draft/agents/openai.yaml +6 -0
  34. package/skills/math-model-draft/agents/openai.yaml +0 -6
  35. package/skills/math-model-draft/assets/project-template/paper/sections/ai-disclosure.tex +0 -3
  36. package/skills/math-model-draft/assets/project-template/paper/sections/appendix.tex +0 -9
  37. package/skills/math-model-draft/assets/project-template/paper/sections/references.tex +0 -6
  38. package/skills/math-model-draft/references/cumcm-compliance.md +0 -56
  39. package/skills/math-model-draft/references/modeling-quality.md +0 -91
  40. package/skills/math-model-draft/references/project-architecture.md +0 -65
  41. /package/skills/{math-model-draft → cumcm-draft}/assets/project-template/code/always/__init__.py +0 -0
  42. /package/skills/{math-model-draft → cumcm-draft}/assets/project-template/code/requirements.txt +0 -0
  43. /package/skills/{math-model-draft → cumcm-draft}/assets/project-template/paper/ai-use-log.md +0 -0
  44. /package/skills/{math-model-draft → cumcm-draft}/assets/project-template/paper/sections/abstract.tex +0 -0
  45. /package/skills/{math-model-draft → cumcm-draft}/assets/project-template/paper/sections/assumptions.tex +0 -0
  46. /package/skills/{math-model-draft → cumcm-draft}/assets/project-template/paper/sections/data.tex +0 -0
  47. /package/skills/{math-model-draft → cumcm-draft}/assets/project-template/paper/sections/evaluation.tex +0 -0
  48. /package/skills/{math-model-draft → cumcm-draft}/assets/project-template/paper/sections/problem-analysis.tex +0 -0
  49. /package/skills/{math-model-draft → cumcm-draft}/assets/project-template/paper/sections/problem-restatement.tex +0 -0
  50. /package/skills/{math-model-draft → cumcm-draft}/assets/project-template/paper/sections/source-code.tex +0 -0
  51. /package/skills/{math-model-draft → cumcm-draft}/assets/project-template/paper/sections/support-files.tex +0 -0
  52. /package/skills/{math-model-draft → cumcm-draft}/references/paper-revision.md +0 -0
  53. /package/skills/{math-model-draft → cumcm-draft}/scripts/capture_environment.py +0 -0
  54. /package/skills/{math-model-draft → cumcm-draft}/scripts/evidence_freeze.py +0 -0
  55. /package/skills/{math-model-draft → cumcm-draft}/scripts/finalize_project.py +0 -0
  56. /package/skills/{math-model-draft → cumcm-draft}/scripts/inspect_inputs.py +0 -0
@@ -0,0 +1,161 @@
1
+ # Modeling and evidence quality
2
+
3
+ ## Translate the task
4
+
5
+ For every subproblem record:
6
+
7
+ - target quantity or decision;
8
+ - observational unit and time/space scale;
9
+ - controllable and uncontrollable variables;
10
+ - constraints, units, and required deliverable;
11
+ - dependence on earlier subproblems;
12
+ - acceptable error or comparison criterion.
13
+
14
+ ## Audit data before modeling
15
+
16
+ - Inventory sheets, tables, row counts, columns, units, formulas, and blanks.
17
+ - Preserve identifiers as strings when leading zeros matter.
18
+ - Distinguish structural zeros, measured zeros, missing values, and below-limit
19
+ values.
20
+ - Check duplicate entities, inconsistent units, impossible ranges, leakage,
21
+ and repeated measurements.
22
+ - Explain every exclusion or imputation and save an audit table.
23
+ - Fit preprocessing on training data only when evaluating predictions.
24
+ - Use compositional-data methods for constrained proportions when ordinary
25
+ correlations or Euclidean distances would be misleading.
26
+
27
+ ## Audit business semantics before transformation
28
+
29
+ - Build a short field ledger: source meaning, unit, observation time, valid
30
+ range, structural missingness, and permitted transformation.
31
+ - Do not apply one arithmetic rule to semantically different promotions,
32
+ tariffs, bundles, censored values, or status flags.
33
+ - Preserve raw columns beside derived columns. Mark ambiguous or impossible
34
+ values explicitly instead of clipping them into apparently valid evidence.
35
+ - Distinguish a global event date from sparse row-level event notes. If a note
36
+ identifies a store-wide event, verify whether all entities on that date need
37
+ the event indicator.
38
+ - Name event-window statistics precisely: number of qualifying days, last
39
+ qualifying offset, and longest consecutive run are different quantities.
40
+
41
+ ## Enforce decision-time availability
42
+
43
+ For every prediction or decision feature, record one class:
44
+
45
+ - known or planned before the decision;
46
+ - obtainable from a separate forecast available before the decision;
47
+ - realized only after the target outcome.
48
+
49
+ Use only the first two classes at their historically available versions.
50
+ Lag end-of-day inventory, returns, stockouts, backorders, realized weather, or
51
+ other post-outcome variables when predicting the same day. Apply the same rule
52
+ to recursive future prediction; do not train with observed lags and silently
53
+ replace them with unavailable contemporaneous values at deployment.
54
+
55
+ ## Select models by the problem
56
+
57
+ Start with a transparent baseline. Add complexity only when it improves a
58
+ defined criterion or resolves a structural limitation.
59
+
60
+ Compare candidates on:
61
+
62
+ - compatibility with assumptions and data volume;
63
+ - interpretability required by the question;
64
+ - constraint handling;
65
+ - uncertainty quantification;
66
+ - stability and computational cost;
67
+ - out-of-sample or scenario performance.
68
+
69
+ Do not combine algorithms merely to appear innovative.
70
+
71
+ Use distinct data roles:
72
+
73
+ - training/estimation fits model parameters;
74
+ - validation selects model family, features, weights, thresholds, interval
75
+ calibration, and policy parameters;
76
+ - test evaluates the locked pipeline once.
77
+
78
+ Never report the best test candidate after trying several candidates on the
79
+ test set. An ensemble is allowed to collapse to one component or assign another
80
+ component zero weight. A simple winning baseline is a valid final model.
81
+
82
+ ## Validate at the right level
83
+
84
+ Choose evidence appropriate to the claim:
85
+
86
+ - regression: residual structure, error metrics, intervals, collinearity;
87
+ - classification: class counts, confusion matrix, per-class precision/recall,
88
+ F1, calibration, stratified or grouped validation;
89
+ - clustering: stability, silhouette or domain separation, sensitivity to k;
90
+ - optimization: feasibility, optimality gap/bounds, baseline comparison,
91
+ parameter sensitivity, multiple starts;
92
+ - time series: rolling-origin validation, residual autocorrelation, intervals;
93
+ - simulation: convergence, Monte Carlo error, scenario coverage;
94
+ - mechanistic model: dimensional checks, conservation, limiting cases,
95
+ parameter identifiability;
96
+ - ranking/evaluation: weight sensitivity, rank stability, consistency checks.
97
+
98
+ Respect grouped, temporal, or spatial dependence. Do not randomly split rows
99
+ that share the same entity or leak future information.
100
+
101
+ For sequential optimization or simulation, separate parameter estimation,
102
+ policy selection, and policy evaluation by time or independent scenarios.
103
+ Do not use final-test feasibility or Pareto filters to guarantee that every
104
+ reported test metric improves.
105
+
106
+ ## Verify cross-question contracts
107
+
108
+ - Define the producer, relative result path, schema, entity key, date range,
109
+ units, and missing-data policy for every upstream artifact.
110
+ - Make downstream code read that artifact directly and fail closed on missing
111
+ entities, duplicate keys, stale dates, unexpected units, or incomplete rows.
112
+ - Do not replace a missing upstream forecast with an attachment, historical
113
+ mean, or freshly fitted proxy without disclosing and validating the fallback.
114
+ - Re-run all downstream questions after an upstream fact changes; then update
115
+ figures, paper values, conclusions, and the evidence map together.
116
+
117
+ ## State optimization claims honestly
118
+
119
+ - Say “best among the evaluated candidates” or “model-constrained optimum”
120
+ unless a global-optimality proof or bound exists.
121
+ - State the objective, horizon, constraints, search grid, and data window next
122
+ to the recommended decision.
123
+ - Report constraint conflicts and units/entities that worsen even when the
124
+ aggregate objective improves.
125
+ - Preserve non-ideal but validated outcomes, including zero ensemble weight,
126
+ retained original policies, higher safety stock, or an absent improvement.
127
+
128
+ ## Quantify uncertainty and robustness
129
+
130
+ - Perturb influential inputs over defensible ranges.
131
+ - Refit or rerun the full pipeline rather than perturbing only the final table.
132
+ - Report which conclusions are invariant and which change.
133
+ - Use bootstrap or simulation when analytic intervals are unavailable.
134
+ - Distinguish parameter uncertainty, measurement error, model-form error, and
135
+ scenario uncertainty.
136
+
137
+ ## Maintain evidence lineage
138
+
139
+ Every paper claim must map to:
140
+
141
+ - generating module/function;
142
+ - input dataset or upstream result;
143
+ - result file and field/table;
144
+ - validation evidence;
145
+ - paper section and figure/table label.
146
+
147
+ Keep this mapping in `paper/evidence-map.yaml`. Do not type important numbers
148
+ into LaTeX from memory.
149
+
150
+ Use `status: verified` only after the producing code has run and the claim's
151
+ schema, constraints, selection protocol, and independent validation evidence
152
+ have passed. File existence or agreement between JSON and TeX is not enough.
153
+
154
+ ## Prevent unsupported output
155
+
156
+ - Never invent sample sizes, parameter values, citations, or performance.
157
+ - Never call a result significant without a defined statistical test.
158
+ - Never infer causality from association without an identification argument.
159
+ - Never claim generalization beyond observed conditions without scenarios or
160
+ external evidence.
161
+ - Preserve an explicit `TODO` when evidence cannot be obtained.
@@ -47,12 +47,14 @@ For CUMCM-style papers use:
47
47
  only content genuinely reused across questions.
48
48
  8. One major section per qN.
49
49
  9. Model evaluation, limitations, and possible extensions.
50
- 10. AI-use declaration when required by the active contest profile.
50
+ 10. Corresponding inline AI marks and an AI tool reference entry when AI was
51
+ used; a concise disclosure paragraph may also be included.
51
52
  11. References.
52
53
  12. Appendix:
53
- support-file list and complete runnable source when required by the active
54
- contest profile. A separately submitted AI-use details PDF is not duplicated
55
- as a long appendix unless the rules explicitly request that.
54
+ the exact support-archive file list followed by complete runnable source.
55
+ Group the list by directory instead of omitting names or printing one noisy
56
+ path per line. Keep `AI工具使用详情.pdf` in the support ZIP rather than
57
+ duplicating its contents in the paper.
56
58
 
57
59
  Do not include a table of contents when CUMCM rules prohibit it.
58
60
 
@@ -82,7 +84,12 @@ Reject an abstract that:
82
84
 
83
85
  ## Subproblem microstructure
84
86
 
85
- Use the following internal order for each `qN`:
87
+ Keep one major section per numbered question. This mapping is useful to judges
88
+ and should not be replaced by paper-wide “method”, “results”, and “discussion”
89
+ sections that mix evidence from different questions.
90
+
91
+ Within each question, use an adaptive two-level outline. A substantial question
92
+ normally needs five to seven domain-specific subsections in this order:
86
93
 
87
94
  1. **Objective and inputs**: what is computed, for whom, and under which units.
88
95
  2. **Method choice**: candidate methods and why the chosen one fits.
@@ -93,9 +100,48 @@ Use the following internal order for each `qN`:
93
100
  7. **Validation**: error, uncertainty, robustness, sensitivity, or comparison.
94
101
  8. **Sub-conclusion**: directly answer the statement in two or three sentences.
95
102
 
103
+ These are reasoning stages, not mandatory literal titles. Combine adjacent
104
+ stages when the question is short or one stage has no independent evidence;
105
+ split a stage when it contains distinct models or decisions. Prefer headings
106
+ such as “时间外推性能”, “弹性模型与稳定性处理”, or “历史回放与Pareto筛选” over
107
+ repeated generic headings such as “方法选择与模型建立” or “结果与解释”. A
108
+ subsection should contain a real claim, derivation, artifact, or validation—not
109
+ exist merely to make the outline longer.
110
+
111
+ Use the PDF bookmark pane as a structural test: collapsing a question should
112
+ show the question-level answer; expanding it should reveal the modeling and
113
+ evidence chain without requiring the judge to scan prose. If a question spans
114
+ more than about one page but exposes only one or two undifferentiated
115
+ subsections, refine the outline before adding more text.
116
+
96
117
  For dependent questions, begin by declaring which upstream artifacts are used
97
118
  and why error propagation is acceptable.
98
119
 
120
+ ## Detail budget
121
+
122
+ - Keep a body table to one page whenever possible.
123
+ - Summarize all-item or all-date outputs by decision-relevant group, then point
124
+ to the complete CSV/XLSX in support materials.
125
+ - Print the exact grouped file inventory required by current CUMCM rules, but
126
+ keep machine-readable result rows in support CSV/XLSX rather than the body.
127
+ - Build source appendices from actual runnable files, not a parallel
128
+ `core_code` summary that can drift from execution.
129
+ - Exclude finalizers, packagers, audit scripts, empty package markers, caches,
130
+ and generated source from the modeling-code appendix.
131
+
132
+ ## Reference-paper comparison
133
+
134
+ - Split page counts into body, references, source appendix, and result appendix
135
+ before comparing two PDFs.
136
+ - Compare each subproblem's question, method, evidence, interpretation,
137
+ validation, and limitations; do not use total length as a quality proxy.
138
+ - Normalize for subproblem count and domain. Equation-heavy mechanistic models
139
+ naturally need more derivation than empirical prediction pipelines.
140
+ - Do not expand the body to compensate for a complete source appendix, or
141
+ shrink the body because the appendix already makes the PDF long.
142
+ - Require every bibliography item to have at least one in-text citation, placed
143
+ next to the method or claim it supports.
144
+
99
145
  ## Reasoning and prose rules
100
146
 
101
147
  - Lead each paragraph with its claim; follow with evidence and implication.
@@ -0,0 +1,124 @@
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
+ - Do not create a common result directory. Give cleaned data, audits, and every
44
+ other generated artifact to the earliest subproblem that produces it; later
45
+ subproblems declare and consume that upstream `results/qN` dependency.
46
+ - Each `code/qN/main.py` must run independently after its prerequisites exist.
47
+ - `code/qN/main.py` only orchestrates loading, domain computation, validation,
48
+ and reporting. Name sibling modules after real responsibilities discovered
49
+ from the problem; never require a universal `model.py` or `output.py`.
50
+ - Keep domain-module dependencies acyclic and add concise Chinese `#` comments
51
+ where a reviewer needs the assumption, unit, guard, or execution rationale.
52
+ - `code/run_all.py` runs subproblems in dependency order.
53
+ - `results/qN` owns numeric and tabular evidence for subproblem N.
54
+ - `figures/qN` owns final visuals for subproblem N. Put diagnostic-only images
55
+ in a temporary build directory and remove them before handoff.
56
+ - `paper/sections/qN.tex` may consume only declared evidence from matching or
57
+ explicitly upstream result directories.
58
+ - Treat every cross-question result as a typed interface. The consumer checks
59
+ required columns, unique entity/date keys, units, expected coverage, and
60
+ freshness before computing. Missing coverage is an error, not permission to
61
+ rebuild an undeclared proxy.
62
+ - Keep model-selection, validation, and test artifacts under the producing
63
+ `results/qN`; these are evidence, not disposable debug output.
64
+
65
+ ## Naming
66
+
67
+ - Use `q1`, `q2`, ... exactly; do not mix `Q1`, `question1`, or Chinese folder
68
+ names.
69
+ - Prefer descriptive Chinese artifact names when they improve hand editing.
70
+ - Use stable ASCII Python module names.
71
+ - Use UTF-8 for text and UTF-8 with BOM for CSV intended for Excel.
72
+ - Include units in column labels or metadata.
73
+
74
+ ## Compatibility with legacy reproduction folders
75
+
76
+ Some existing projects place `question/` next to a `reproduce/` directory.
77
+ Read those inputs in place, but do not move them automatically. For a new
78
+ project, make `question/` a peer of `code/`, `results/`, `figures/`, and
79
+ `paper/` as the canonical structure above.
80
+
81
+ When the user explicitly requests a compact handoff patterned after an
82
+ existing project, this layout is also valid:
83
+
84
+ ```text
85
+ project-root/
86
+ ├── main.tex
87
+ ├── main.pdf
88
+ ├── AI工具使用详情.tex
89
+ ├── AI工具使用详情.pdf
90
+ ├── 支撑材料.zip
91
+ ├── question/ # still immutable
92
+ └── produce/
93
+ ├── code/
94
+ │ ├── always/
95
+ │ ├── q1/
96
+ │ └── ...
97
+ └── results/
98
+ ├── q1/
99
+ └── ...
100
+ ```
101
+
102
+ Use `main` as the neutral basename unless submission rules require a
103
+ team-specific name. Do not add `core_code/`; the PDF appendix must include the
104
+ actual runnable files from `produce/code/`. Keep paper sources out of
105
+ `produce/`; inline the complete paper into one root `main.tex` for the compact
106
+ handoff. Split section files are an authoring aid, not a delivery requirement,
107
+ and should be removed after a verified merge unless the user requests them.
108
+ Build the support ZIP while `produce/figures/` still exists so the archive and
109
+ appendix list remain complete. After the PDF and ZIP are both inspected, remove
110
+ reproducible workspace figures from a minimal handoff if requested. Running
111
+ `produce/code/run_all.py` must recreate them before recompiling `main.tex`.
112
+
113
+ The formal CUMCM submission pair is the paper PDF plus one support ZIP/RAR.
114
+ Keep `AI工具使用详情.pdf` inside that archive; a root copy may remain for editing
115
+ and inspection. Place separately required filled Excel/Word artifacts at root
116
+ only when the problem statement or submission system requires them there.
117
+ Internal evidence remains in `produce/results/qN`; do not promote every CSV or
118
+ diagnostic file to the root.
119
+
120
+ Before compact handoff, remove nested ZIP/RAR/7z copies from `produce/code`,
121
+ `produce/results`, and `produce/figures`; remove scratch verification, cleanup,
122
+ rebuild, and PDF-contact scripts after their reusable checks live in the Skill
123
+ finalizer. Keep only direct runtime dependencies in `requirements.txt`, plus
124
+ the file-format engines actually required to read the supplied inputs.
@@ -13,6 +13,12 @@ FIGURE_SUFFIXES = {".pdf", ".png", ".jpg", ".jpeg", ".eps", ".svg"}
13
13
  PROBLEM_SUFFIXES = {".pdf", ".doc", ".docx", ".csv", ".tsv", ".xls", ".xlsx"}
14
14
  INVENTORY_EXCLUDED_PARTS = {"__pycache__", ".pytest_cache", ".mypy_cache", ".ruff_cache", ".orbit", "_work"}
15
15
  FIGURE_STALE_TOLERANCE_SECONDS = 30.0
16
+ GENERIC_QUESTION_HEADINGS = {
17
+ "题意、变量与约束",
18
+ "方法选择与模型建立",
19
+ "结果与解释",
20
+ "验证、小结与衔接",
21
+ }
16
22
 
17
23
 
18
24
  def relative(root: Path, path: Path) -> str:
@@ -57,6 +63,39 @@ def inventory_files(root: Path, base: Path) -> list[Path]:
57
63
  ]
58
64
 
59
65
 
66
+ def question_outline_findings(label: str, content: str) -> list[dict[str, str]]:
67
+ findings: list[dict[str, str]] = []
68
+ titles = [title.strip() for title in re.findall(r"\\subsection\*?\{([^{}]+)\}", content)]
69
+ plain = re.sub(r"\\[A-Za-z@]+\*?(?:\[[^]]*\])?", "", content)
70
+ plain = re.sub(r"[{}%\s]", "", plain)
71
+ if len(plain) >= 1200 and len(titles) < 4:
72
+ findings.append(
73
+ {
74
+ "severity": "warning",
75
+ "kind": "coarse_question_outline",
76
+ "message": f"{label} has {len(titles)} subsection(s) for a substantial question",
77
+ }
78
+ )
79
+ generic = [title for title in titles if title in GENERIC_QUESTION_HEADINGS]
80
+ if len(generic) >= 3:
81
+ findings.append(
82
+ {
83
+ "severity": "warning",
84
+ "kind": "generic_question_outline",
85
+ "message": f"{label} repeats broad scaffold headings: {'; '.join(generic)}",
86
+ }
87
+ )
88
+ if len(titles) > 8:
89
+ findings.append(
90
+ {
91
+ "severity": "warning",
92
+ "kind": "fragmented_question_outline",
93
+ "message": f"{label} has {len(titles)} subsections; merge headings without independent claims or evidence",
94
+ }
95
+ )
96
+ return findings
97
+
98
+
60
99
  def inspect_pdf(pdf: Path) -> dict[str, Any]:
61
100
  if not pdf.is_file():
62
101
  return {"status": "missing"}
@@ -174,6 +213,7 @@ def main() -> None:
174
213
  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 []
175
214
  for section in sorted(question_sections):
176
215
  content = tex_texts.get(section, "")
216
+ findings.extend(question_outline_findings(relative(root, section), content))
177
217
  plain = re.sub(r"\\[A-Za-z@]+\*?(?:\[[^]]*\])?", "", content)
178
218
  plain = re.sub(r"[{}%]", "", plain)
179
219
  if len(re.sub(r"\s+", "", plain)) < 500:
@@ -90,8 +90,6 @@ def create_question_files(
90
90
  files = {
91
91
  root / "code" / name / "__init__.py": "",
92
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
93
  root / "paper" / "sections" / f"{name}.tex": question_tex(number),
96
94
  }
97
95
  for path, content in files.items():
@@ -162,7 +160,19 @@ def extend_evidence_map(root: Path, count: int, created: list[str], updated: lis
162
160
  additions: list[str] = []
163
161
  for i in range(1, count + 1):
164
162
  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"])
163
+ additions.extend(
164
+ [
165
+ f"q{i}:",
166
+ " claims:",
167
+ f" - id: q{i}-main-result",
168
+ f" generated_by: code/q{i}/main.py",
169
+ f" source: results/q{i}/summary.json",
170
+ f" paper_section: paper/sections/q{i}.tex",
171
+ " upstream: TODO",
172
+ " validation: TODO",
173
+ " status: TODO",
174
+ ]
175
+ )
166
176
  if not additions:
167
177
  return
168
178
  rendered = content.rstrip() + "\n" + "\n".join(additions) + "\n"
@@ -184,63 +194,55 @@ def write_if_missing(root: Path, path: Path, content: str, created: list[str], p
184
194
  def question_main(name: str) -> str:
185
195
  return f'''from __future__ import annotations
186
196
 
197
+ import json
198
+
187
199
  from always.config import question_output_dirs
188
- from {name}.model import solve
189
- from {name}.output import save_outputs
190
200
 
191
201
 
192
202
  def main() -> None:
193
203
  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
204
  results_dir.mkdir(parents=True, exist_ok=True)
223
205
  figure_dir.mkdir(parents=True, exist_ok=True)
206
+
207
+ # 脚手架只保留入口;读题后请创建按实际职责命名的领域模块。
208
+ summary = {{
209
+ "question": "{name}",
210
+ "status": "TODO",
211
+ "validation": {{"selection_data": "TODO", "test_data": "TODO", "checks": []}},
212
+ "claims": [],
213
+ }}
224
214
  (results_dir / "summary.json").write_text(
225
- json.dumps(result, ensure_ascii=False, indent=2) + "\\n", encoding="utf-8"
215
+ json.dumps(summary, ensure_ascii=False, indent=2) + "\\n",
216
+ encoding="utf-8",
226
217
  )
218
+ print("[OK] {name} scaffold completed")
219
+
220
+
221
+ if __name__ == "__main__":
222
+ main()
227
223
  '''
228
224
 
229
225
 
230
226
  def question_tex(number: int) -> str:
231
227
  return rf'''\section{{问题{number}:TODO[写明本题目标]}}
232
228
 
233
- \subsection{{题意、变量与约束}}
234
- \TODO{{明确本题交付、变量、单位、目标、约束及其与前后小题的数据关系。}}
229
+ \subsection{{目标、输入与问题接口}}
230
+ \TODO{{明确本题交付、输入、单位及其与前后小题的数据关系;成稿时把本标题改成领域化标题。}}
231
+
232
+ \subsection{{方法比较与选择依据}}
233
+ \TODO{{比较候选方法,说明所选方法为何匹配数据、约束和决策目标。}}\AIUseMark
234
+
235
+ \subsection{{模型构建与参数来源}}
236
+ \TODO{{定义变量、目标函数、约束和参数来源,保持符号、单位与代码一致。}}
235
237
 
236
- \subsection{{方法选择与模型建立}}
237
- \TODO{{比较候选方法,说明选择理由,给出公式、参数来源和实际求解算法。}}
238
+ \subsection{{求解流程与实现口径}}
239
+ \TODO{{说明算法步骤、数据切分、边界处理及结果文件的生成路径。}}
238
240
 
239
- \subsection{{结果与解释}}
240
- \TODO{{从 results/q{number}/ 引用实际数值,引用 figures/q{number}/ 的当前图并解释。}}
241
+ \subsection{{结果解释与有效性检验}}
242
+ \TODO{{从 results/q{number}/ 引用实际数值和 figures/q{number}/ 的当前图,解释结果并报告误差、敏感性、稳健性或基线比较。}}
241
243
 
242
- \subsection{{验证、小结与衔接}}
243
- \TODO{{报告适当的误差、敏感性、稳健性或基线比较,回答本题并衔接下一问。}}
244
+ \subsection{{本问结论与后续接口}}
245
+ \TODO{{用两三句话直接回答本题,并说明输出如何进入下一问;成稿时按实际内容改名。}}
244
246
  '''
245
247
 
246
248
 
@@ -5,13 +5,30 @@ import os
5
5
  import re
6
6
  import shutil
7
7
  import subprocess
8
+ from collections import defaultdict
8
9
  from pathlib import Path
9
10
 
10
11
  from project_utils import iter_regular_files, load_profile, numeric_limit
11
12
 
12
13
 
13
- EXCLUDED_PARTS = {"__pycache__", ".pytest_cache", ".mypy_cache", "build"}
14
+ EXCLUDED_PARTS = {
15
+ "__pycache__",
16
+ ".pytest_cache",
17
+ ".mypy_cache",
18
+ ".ruff_cache",
19
+ ".ipynb_checkpoints",
20
+ "build",
21
+ }
14
22
  CODE_SUFFIXES = {".py", ".r", ".jl", ".m", ".cpp", ".c", ".h"}
23
+ SOURCE_APPENDIX_EXCLUDED = {"code/finalize.py"}
24
+ LISTING_LANGUAGES = {
25
+ ".py": "Python",
26
+ ".r": "R",
27
+ ".m": "Matlab",
28
+ ".cpp": "C++",
29
+ ".c": "C",
30
+ ".h": "C++",
31
+ }
15
32
  BUILD_ARTIFACT_SUFFIXES = {
16
33
  ".aux",
17
34
  ".bbl",
@@ -47,6 +64,13 @@ def tex_breakable_path(value: str) -> str:
47
64
  return f"\\texttt{{{escaped}}}"
48
65
 
49
66
 
67
+ def tex_file_name(value: str) -> str:
68
+ """Render ASCII names as paths while keeping CJK names in a CJK-capable font."""
69
+ if value.isascii():
70
+ return f"\\path{{{tex_path(value)}}}"
71
+ return tex_text(value)
72
+
73
+
50
74
  def generate_appendices(root: Path, profile: dict[str, object]) -> None:
51
75
  sections = root / "paper" / "sections"
52
76
  sections.mkdir(parents=True, exist_ok=True)
@@ -61,20 +85,67 @@ def generate_appendices(root: Path, profile: dict[str, object]) -> None:
61
85
  ai_pdf = root / "paper" / "AI工具使用详情.pdf"
62
86
  if ai_pdf.is_file():
63
87
  support.append("paper/AI工具使用详情.pdf")
64
- rows = ["\\begin{itemize}"] + [f" \\item {tex_breakable_path(path)}" for path in sorted(set(support))] + ["\\end{itemize}"]
88
+ support.append("paper/evidence-freeze.json")
89
+ support_profile = profile["support"]
90
+ assert isinstance(support_profile, dict)
91
+ ai_log = root / "paper" / "ai-use-log.md"
92
+ if bool(support_profile.get("include_ai_log")) and ai_log.is_file():
93
+ support.append("paper/ai-use-log.md")
94
+ grouped: dict[str, list[str]] = defaultdict(list)
95
+ for path in sorted(set(support)):
96
+ item = Path(path)
97
+ grouped[item.parent.as_posix()].append(item.name)
98
+ rows = [
99
+ "\\section{支撑材料文件列表}",
100
+ "下表与最终支撑材料压缩包逐项对应;为便于核对,文件按目录归并列示。",
101
+ "\\small",
102
+ "\\renewcommand{\\arraystretch}{1.15}",
103
+ "\\begin{longtable}{@{}>{\\raggedright\\arraybackslash}p{0.28\\textwidth}>{\\raggedright\\arraybackslash}p{0.66\\textwidth}@{}}",
104
+ " \\toprule",
105
+ " 目录 & 文件名 \\\\",
106
+ " \\midrule",
107
+ " \\endfirsthead",
108
+ " \\toprule",
109
+ " 目录 & 文件名(续) \\\\",
110
+ " \\midrule",
111
+ " \\endhead",
112
+ ]
113
+ for directory, names in grouped.items():
114
+ directory_cell = "根目录" if directory == "." else f"\\path{{{tex_path(directory)}}}"
115
+ file_cell = ";\\allowbreak{}".join(tex_file_name(name) for name in names)
116
+ rows.append(f" {directory_cell} & {file_cell} \\\\")
117
+ rows.extend([" \\bottomrule", "\\end{longtable}", "\\normalsize"])
65
118
  support_path.write_text("\n".join(rows) + "\n", encoding="utf-8")
66
119
  else:
67
120
  support_path.write_text("% Disabled by paper/contest-profile.json.\n", encoding="utf-8")
68
121
 
69
122
  source_path = sections / "source-code.tex"
70
123
  if bool(paper_profile.get("include_source_appendix")):
71
- listings = []
124
+ listings = [
125
+ "\\section{完整可运行程序代码}",
126
+ "本附录直接引用当前建模源码,不另建可能与实际执行漂移的删减版 \\texttt{core\\_code}。"
127
+ "空包初始化文件与终检启动器不重复刊载。",
128
+ ]
129
+ current_group: str | None = None
72
130
  for path in iter_regular_files(root, "code", EXCLUDED_PARTS):
73
131
  if path.suffix.lower() not in CODE_SUFFIXES:
74
132
  continue
75
- relative = (Path("..") / path.relative_to(root)).as_posix()
76
133
  display = path.relative_to(root).as_posix()
77
- listings.extend([f"\\noindent\\textbf{{程序文件}}\\quad {tex_breakable_path(display)}\\par", "\\VerbatimInput[fontsize=\\scriptsize,breaklines=true," f"breakanywhere=true]{{{tex_path(relative)}}}"])
134
+ if display in SOURCE_APPENDIX_EXCLUDED or path.name == "__init__.py" or path.stat().st_size == 0:
135
+ continue
136
+ relative = (Path("..") / path.relative_to(root)).as_posix()
137
+ group = path.relative_to(root / "code").parent.as_posix()
138
+ if group != current_group:
139
+ group_label = "统一入口" if group == "." else f"模块 {group}"
140
+ listings.append(f"\\subsection{{{tex_text(group_label)}}}")
141
+ current_group = group
142
+ language = LISTING_LANGUAGES.get(path.suffix.lower(), "")
143
+ listings.extend(
144
+ [
145
+ f"\\subsubsection*{{\\path{{{tex_path(display)}}}}}",
146
+ f"\\lstinputlisting[style=modelpython,language={{{language}}}]{{{tex_path(relative)}}}",
147
+ ]
148
+ )
78
149
  source_path.write_text("\n\n".join(listings) + "\n", encoding="utf-8")
79
150
  else:
80
151
  source_path.write_text("% Disabled by paper/contest-profile.json.\n", encoding="utf-8")