@louisultra/dsh-verymath 0.0.0-stage → 0.3.1
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/CHANGELOG.md +110 -0
- package/LICENSE +21 -0
- package/NOTICE.md +35 -0
- package/README.md +104 -2
- package/README_EN.md +105 -0
- package/UPSTREAM.json +106 -0
- package/cordis.patch.yml +12 -0
- package/lib/core/error.d.ts +20 -0
- package/lib/core/error.js +25 -0
- package/lib/core/gates.d.ts +42 -0
- package/lib/core/gates.js +217 -0
- package/lib/core/glossary.d.ts +101 -0
- package/lib/core/glossary.js +243 -0
- package/lib/core/graph.d.ts +118 -0
- package/lib/core/graph.js +460 -0
- package/lib/core/index.d.ts +120 -0
- package/lib/core/index.js +197 -0
- package/lib/core/paper.d.ts +163 -0
- package/lib/core/paper.js +73 -0
- package/lib/core/paths.d.ts +2 -0
- package/lib/core/paths.js +12 -0
- package/lib/core/sage.d.ts +61 -0
- package/lib/core/sage.js +212 -0
- package/lib/core/skills.d.ts +11 -0
- package/lib/core/skills.js +110 -0
- package/lib/tool/index.d.ts +21 -0
- package/lib/tool/index.js +1144 -0
- package/package.json +90 -4
- package/skills/after-ocr/SKILL.md +123 -0
- package/skills/after-ocr/references/audit-schema.md +94 -0
- package/skills/after-ocr/references/error-taxonomy.md +179 -0
- package/skills/after-ocr/scripts/merge_audit_logs.py +329 -0
- package/skills/after-ocr/scripts/scan_markdown_ocr.py +350 -0
- package/skills/after-ocr/tests/test_scripts.py +84 -0
- package/skills/discover-math-problems/SKILL.md +115 -0
- package/skills/discover-math-problems/references/artifact-contract.md +93 -0
- package/skills/discover-math-problems/references/autonomous-research-protocol.md +86 -0
- package/skills/discover-math-problems/references/conjecture-generation-protocol.md +63 -0
- package/skills/discover-math-problems/references/extremal-graph-variants.md +53 -0
- package/skills/graph-theory-paper-reading/SKILL.md +600 -0
- package/skills/invariant-computation/SKILL.md +169 -0
- package/skills/invariant-computation/examples/invariant_summary.example.json +51 -0
- package/skills/invariant-computation/manifest.yaml +46 -0
- package/skills/invariant-computation/references/INDEX.md +20 -0
- package/skills/invariant-computation/references/failure_modes.md +40 -0
- package/skills/invariant-computation/references/method_route_map.md +177 -0
- package/skills/invariant-computation/references/source_notes.md +19 -0
- package/skills/invariant-computation/references/tool_catalog.md +65 -0
- package/skills/invariant-computation/references/validation_checks.md +52 -0
- package/skills/invariant-computation/schema/invariant_summary.schema.json +260 -0
- package/skills/lean-formalization/SKILL.md +110 -0
- package/skills/lean-formalization/lean-runtime/config/env.example +5 -0
- package/skills/lean-formalization/lean-runtime/config/lean_agent.example.toml +28 -0
- package/skills/lean-formalization/lean-runtime/config/numina_runtime.example.toml +12 -0
- package/skills/lean-formalization/lean-runtime/examples/smoke/LocalLeanSmoke.lean +7 -0
- package/skills/lean-formalization/lean-runtime/prompts/complete_sorries.md +3 -0
- package/skills/lean-formalization/lean-runtime/prompts/formalize_statement.md +3 -0
- package/skills/lean-formalization/lean-runtime/prompts/prove_theorem.md +3 -0
- package/skills/lean-formalization/lean-runtime/prompts/repair_lean_file.md +3 -0
- package/skills/lean-formalization/lean-runtime/references/backend_adapter_checklist.md +36 -0
- package/skills/lean-formalization/lean-runtime/references/direct_lean_workflow.md +48 -0
- package/skills/lean-formalization/lean-runtime/references/failure_taxonomy.md +17 -0
- package/skills/lean-formalization/lean-runtime/references/interactive_orchestration.md +83 -0
- package/skills/lean-formalization/lean-runtime/references/lean_agent_capability_map.md +116 -0
- package/skills/lean-formalization/lean-runtime/references/lean_lsp_mcp_adapter.md +219 -0
- package/skills/lean-formalization/lean-runtime/references/lean_runtime_configuration.md +92 -0
- package/skills/lean-formalization/lean-runtime/references/numina_reverse_analysis.md +80 -0
- package/skills/lean-formalization/lean-runtime/references/numina_runtime.md +41 -0
- package/skills/lean-formalization/lean-runtime/references/numina_subagent_troubleshooting.md +77 -0
- package/skills/lean-formalization/lean-runtime/references/review_checklist.md +10 -0
- package/skills/lean-formalization/lean-runtime/references/specialist_agent_patterns.md +65 -0
- package/skills/lean-formalization/lean-runtime/schemas/config.schema.json +12 -0
- package/skills/lean-formalization/lean-runtime/schemas/result.schema.json +33 -0
- package/skills/lean-formalization/lean-runtime/schemas/task.schema.json +30 -0
- package/skills/lean-formalization/lean-runtime/scripts/ai4m_lean.py +222 -0
- package/skills/lean-formalization/lean-runtime/scripts/check_lean_project.py +134 -0
- package/skills/lean-formalization/lean-runtime/scripts/common.py +296 -0
- package/skills/lean-formalization/lean-runtime/scripts/configure_lean.py +222 -0
- package/skills/lean-formalization/lean-runtime/scripts/detect_sorry.py +49 -0
- package/skills/lean-formalization/lean-runtime/scripts/direct_task.py +100 -0
- package/skills/lean-formalization/lean-runtime/scripts/extract_minimal_failure.py +74 -0
- package/skills/lean-formalization/lean-runtime/scripts/numina_runtime.py +414 -0
- package/skills/lean-formalization/lean-runtime/scripts/smoke_test.py +75 -0
- package/skills/lean-formalization/lean-runtime/scripts/tool_status.py +79 -0
- package/skills/lean-formalization/lean-runtime/scripts/validate_patch.py +81 -0
- package/skills/lean-formalization/lean-runtime/scripts/verify_delivery.py +484 -0
- package/skills/lean-formalization/lean-runtime/tests/fixtures/after_bad.lean +4 -0
- package/skills/lean-formalization/lean-runtime/tests/fixtures/after_statement_changed.lean +4 -0
- package/skills/lean-formalization/lean-runtime/tests/fixtures/before.lean +4 -0
- package/skills/lean-formalization/lean-runtime/tests/fixtures/failure.lean +7 -0
- package/skills/lean-formalization/lean-runtime/tests/test_check_lean_project.py +59 -0
- package/skills/lean-formalization/lean-runtime/tests/test_cli.py +377 -0
- package/skills/lean-formalization/lean-runtime/tests/test_common_config.py +84 -0
- package/skills/lean-formalization/lean-runtime/tests/test_configure_lean.py +138 -0
- package/skills/lean-formalization/lean-runtime/tests/test_detect_sorry.py +24 -0
- package/skills/lean-formalization/lean-runtime/tests/test_direct_task.py +69 -0
- package/skills/lean-formalization/lean-runtime/tests/test_numina_runtime.py +168 -0
- package/skills/lean-formalization/lean-runtime/tests/test_validate_patch.py +29 -0
- package/skills/lean-setup/SKILL.md +99 -0
- package/skills/least-squares/README.md +85 -0
- package/skills/least-squares/SKILL.md +613 -0
- package/skills/least-squares/examples.md +380 -0
- package/skills/math-beamer/SKILL.md +325 -0
- package/skills/math-beamer/references/build-and-layout-audit.md +63 -0
- package/skills/math-beamer/references/math-domain-patterns.md +56 -0
- package/skills/math-beamer/references/template-policy.md +43 -0
- package/skills/math-beamer/references/template-source-index.md +51 -0
- package/skills/math-beamer/templates/catalog.yaml +235 -0
- package/skills/math-beamer/templates/packs/algebra-number-theory-talk/main.tex +45 -0
- package/skills/math-beamer/templates/packs/algebra-number-theory-talk/template.yaml +9 -0
- package/skills/math-beamer/templates/packs/algorithm-talk/main.tex +43 -0
- package/skills/math-beamer/templates/packs/algorithm-talk/template.yaml +9 -0
- package/skills/math-beamer/templates/packs/analysis-core-talk/main.tex +49 -0
- package/skills/math-beamer/templates/packs/analysis-core-talk/template.yaml +19 -0
- package/skills/math-beamer/templates/packs/backup-heavy-talk/main.tex +40 -0
- package/skills/math-beamer/templates/packs/backup-heavy-talk/template.yaml +9 -0
- package/skills/math-beamer/templates/packs/beamerposter-a0/main.tex +45 -0
- package/skills/math-beamer/templates/packs/beamerposter-a0/template.yaml +12 -0
- package/skills/math-beamer/templates/packs/combinatorics-graph-talk/main.tex +53 -0
- package/skills/math-beamer/templates/packs/combinatorics-graph-talk/template.yaml +18 -0
- package/skills/math-beamer/templates/packs/control-systems-talk/main.tex +51 -0
- package/skills/math-beamer/templates/packs/control-systems-talk/template.yaml +18 -0
- package/skills/math-beamer/templates/packs/course-lecture-zh/main.tex +43 -0
- package/skills/math-beamer/templates/packs/course-lecture-zh/template.yaml +9 -0
- package/skills/math-beamer/templates/packs/data-experiment-results/main.tex +45 -0
- package/skills/math-beamer/templates/packs/data-experiment-results/template.yaml +9 -0
- package/skills/math-beamer/templates/packs/dynamical-systems-talk/main.tex +42 -0
- package/skills/math-beamer/templates/packs/dynamical-systems-talk/template.yaml +9 -0
- package/skills/math-beamer/templates/packs/geometry-topology-talk/main.tex +43 -0
- package/skills/math-beamer/templates/packs/geometry-topology-talk/template.yaml +9 -0
- package/skills/math-beamer/templates/packs/information-coding-crypto-talk/main.tex +49 -0
- package/skills/math-beamer/templates/packs/information-coding-crypto-talk/template.yaml +18 -0
- package/skills/math-beamer/templates/packs/logic-foundations-category-talk/main.tex +51 -0
- package/skills/math-beamer/templates/packs/logic-foundations-category-talk/template.yaml +18 -0
- package/skills/math-beamer/templates/packs/numerical-analysis-talk/main.tex +51 -0
- package/skills/math-beamer/templates/packs/numerical-analysis-talk/template.yaml +9 -0
- package/skills/math-beamer/templates/packs/optimization-talk/main.tex +58 -0
- package/skills/math-beamer/templates/packs/optimization-talk/template.yaml +9 -0
- package/skills/math-beamer/templates/packs/pde-analysis-talk/main.tex +49 -0
- package/skills/math-beamer/templates/packs/pde-analysis-talk/template.yaml +9 -0
- package/skills/math-beamer/templates/packs/probability-statistics-talk/main.tex +52 -0
- package/skills/math-beamer/templates/packs/probability-statistics-talk/template.yaml +9 -0
- package/skills/math-beamer/templates/packs/reading-group-paper/main.tex +46 -0
- package/skills/math-beamer/templates/packs/reading-group-paper/template.yaml +9 -0
- package/skills/math-beamer/templates/packs/seminar-minimal-en/main.tex +60 -0
- package/skills/math-beamer/templates/packs/seminar-minimal-en/template.yaml +13 -0
- package/skills/math-beamer/templates/packs/seminar-minimal-zh/main.tex +60 -0
- package/skills/math-beamer/templates/packs/seminar-minimal-zh/template.yaml +13 -0
- package/skills/math-beamer/templates/packs/theorem-proof-talk/main.tex +60 -0
- package/skills/math-beamer/templates/packs/theorem-proof-talk/template.yaml +9 -0
- package/skills/math-beamer/templates/packs/thesis-defense/main.tex +42 -0
- package/skills/math-beamer/templates/packs/thesis-defense/template.yaml +9 -0
- package/skills/math-beamer/templates/packs/workshop-tutorial/main.tex +32 -0
- package/skills/math-beamer/templates/packs/workshop-tutorial/template.yaml +9 -0
- package/skills/math-beamer/templates/preview-gallery.md +32 -0
- package/skills/math-beamer/templates/previews/algebra-number-theory-talk-content.png +0 -0
- package/skills/math-beamer/templates/previews/algebra-number-theory-talk-cover.png +0 -0
- package/skills/math-beamer/templates/previews/algorithm-talk-content.png +0 -0
- package/skills/math-beamer/templates/previews/algorithm-talk-cover.png +0 -0
- package/skills/math-beamer/templates/previews/analysis-core-talk-content.png +0 -0
- package/skills/math-beamer/templates/previews/analysis-core-talk-cover.png +0 -0
- package/skills/math-beamer/templates/previews/backup-heavy-talk-content.png +0 -0
- package/skills/math-beamer/templates/previews/backup-heavy-talk-cover.png +0 -0
- package/skills/math-beamer/templates/previews/beamerposter-a0-content.png +0 -0
- package/skills/math-beamer/templates/previews/beamerposter-a0-cover.png +0 -0
- package/skills/math-beamer/templates/previews/combinatorics-graph-talk-content.png +0 -0
- package/skills/math-beamer/templates/previews/combinatorics-graph-talk-cover.png +0 -0
- package/skills/math-beamer/templates/previews/control-systems-talk-content.png +0 -0
- package/skills/math-beamer/templates/previews/control-systems-talk-cover.png +0 -0
- package/skills/math-beamer/templates/previews/course-lecture-zh-content.png +0 -0
- package/skills/math-beamer/templates/previews/course-lecture-zh-cover.png +0 -0
- package/skills/math-beamer/templates/previews/data-experiment-results-content.png +0 -0
- package/skills/math-beamer/templates/previews/data-experiment-results-cover.png +0 -0
- package/skills/math-beamer/templates/previews/dynamical-systems-talk-content.png +0 -0
- package/skills/math-beamer/templates/previews/dynamical-systems-talk-cover.png +0 -0
- package/skills/math-beamer/templates/previews/geometry-topology-talk-content.png +0 -0
- package/skills/math-beamer/templates/previews/geometry-topology-talk-cover.png +0 -0
- package/skills/math-beamer/templates/previews/information-coding-crypto-talk-content.png +0 -0
- package/skills/math-beamer/templates/previews/information-coding-crypto-talk-cover.png +0 -0
- package/skills/math-beamer/templates/previews/logic-foundations-category-talk-content.png +0 -0
- package/skills/math-beamer/templates/previews/logic-foundations-category-talk-cover.png +0 -0
- package/skills/math-beamer/templates/previews/numerical-analysis-talk-content.png +0 -0
- package/skills/math-beamer/templates/previews/numerical-analysis-talk-cover.png +0 -0
- package/skills/math-beamer/templates/previews/optimization-talk-content.png +0 -0
- package/skills/math-beamer/templates/previews/optimization-talk-cover.png +0 -0
- package/skills/math-beamer/templates/previews/pde-analysis-talk-content.png +0 -0
- package/skills/math-beamer/templates/previews/pde-analysis-talk-cover.png +0 -0
- package/skills/math-beamer/templates/previews/probability-statistics-talk-content.png +0 -0
- package/skills/math-beamer/templates/previews/probability-statistics-talk-cover.png +0 -0
- package/skills/math-beamer/templates/previews/reading-group-paper-content.png +0 -0
- package/skills/math-beamer/templates/previews/reading-group-paper-cover.png +0 -0
- package/skills/math-beamer/templates/previews/seminar-minimal-en-content.png +0 -0
- package/skills/math-beamer/templates/previews/seminar-minimal-en-cover.png +0 -0
- package/skills/math-beamer/templates/previews/seminar-minimal-zh-content.png +0 -0
- package/skills/math-beamer/templates/previews/seminar-minimal-zh-cover.png +0 -0
- package/skills/math-beamer/templates/previews/theorem-proof-talk-content.png +0 -0
- package/skills/math-beamer/templates/previews/theorem-proof-talk-cover.png +0 -0
- package/skills/math-beamer/templates/previews/thesis-defense-content.png +0 -0
- package/skills/math-beamer/templates/previews/thesis-defense-cover.png +0 -0
- package/skills/math-beamer/templates/previews/workshop-tutorial-content.png +0 -0
- package/skills/math-beamer/templates/previews/workshop-tutorial-cover.png +0 -0
- package/skills/math-beamer/templates/review-report.md +54 -0
- package/skills/math-beamer/templates/slide-source-ledger.md +22 -0
- package/skills/math-beamer/templates/source-packet.md +50 -0
- package/skills/math-glossary/SKILL.md +347 -0
- package/skills/math-glossary/references/glossary-schema.md +71 -0
- package/skills/math-glossary/references/glossary-usage-guide.md +176 -0
- package/skills/math-glossary/references/glossary-web-template.md +127 -0
- package/skills/math-glossary/references/glossary.schema.json +76 -0
- package/skills/math-glossary/references/user-manual.md +435 -0
- package/skills/math-glossary/requirements-ai.txt +3 -0
- package/skills/math-glossary/requirements.txt +3 -0
- package/skills/math-glossary/scripts/glossary_backup.py +42 -0
- package/skills/math-glossary/scripts/glossary_build.py +467 -0
- package/skills/math-glossary/scripts/glossary_enrich_examples.py +283 -0
- package/skills/math-glossary/scripts/glossary_export.py +333 -0
- package/skills/math-glossary/scripts/glossary_web.py +1265 -0
- package/skills/math-paper-reading/README.md +163 -0
- package/skills/math-paper-reading/SKILL.md +48 -0
- package/skills/math-paper-reading/agent_router.md +36 -0
- package/skills/math-paper-reading/references/proof_pattern_taxonomy.md +123 -0
- package/skills/math-paper-reading/references/quality_rubric.md +36 -0
- package/skills/math-paper-reading/skill_base.md +627 -0
- package/skills/math-paper-reading/skill_literature_search.md +866 -0
- package/skills/math-paper-reading/skill_paper_deep_read.md +1024 -0
- package/skills/math-paper-reading/skill_pathway_proof.md +718 -0
- package/skills/math-paper-reading/skill_reference_manager.md +746 -0
- package/skills/matlab-runner/SKILL.md +217 -0
- package/skills/matlab-runner/examples/README.md +33 -0
- package/skills/matlab-runner/examples/matrix_report.m +28 -0
- package/skills/matlab-runner/examples/plot_damped_sine.m +64 -0
- package/skills/matlab-runner/examples/test_vector_norm.m +12 -0
- package/skills/matlab-runner/references/client-setup.md +24 -0
- package/skills/matlab-runner/references/file-session-safety.md +86 -0
- package/skills/matlab-runner/references/numerical-safety.md +126 -0
- package/skills/matlab-runner/references/resource-safety.md +125 -0
- package/skills/mixed-integer-programming/SKILL.md +119 -0
- package/skills/mixed-integer-programming/lp-examples.md +251 -0
- package/skills/mixed-integer-programming/mip-examples-verified.md +118 -0
- package/skills/open-problem-research-pipeline/SKILL.md +76 -0
- package/skills/open-problem-research-pipeline/skill_literature_analysis.md +201 -0
- package/skills/open-problem-research-pipeline/skill_literature_proof_framework.md +206 -0
- package/skills/open-problem-research-pipeline/skill_literature_search.md +172 -0
- package/skills/open-problem-research-pipeline/skill_qskill.md +177 -0
- package/skills/osqp-solver/SKILL.md +245 -0
- package/skills/osqp-solver/references/citation.md +25 -0
- package/skills/osqp-solver/references/dual-infeasible-example.json +14 -0
- package/skills/osqp-solver/references/feasible-example.json +21 -0
- package/skills/osqp-solver/references/primal-infeasible-example.json +17 -0
- package/skills/osqp-solver/references/python-api.md +95 -0
- package/skills/osqp-solver/references/verification.md +94 -0
- package/skills/osqp-solver/scripts/check_osqp_environment.py +120 -0
- package/skills/osqp-solver/scripts/solve_qp.py +943 -0
- package/skills/paper-writing/SKILL.md +115 -0
- package/skills/paper-writing/skill_claim_evidence_ledger.md +55 -0
- package/skills/paper-writing/skill_formula_environment_and_readability.md +41 -0
- package/skills/paper-writing/skill_latex_build_and_layout_audit.md +73 -0
- package/skills/paper-writing/skill_notation_and_variable_consistency.md +42 -0
- package/skills/paper-writing/skill_paper_skeleton_and_logical_architecture.md +54 -0
- package/skills/paper-writing/skill_proof_obligation_and_assumption_audit.md +57 -0
- package/skills/paper-writing/templates/claim-evidence-ledger.md +23 -0
- package/skills/paper-writing/templates/proof-obligation-ledger.md +22 -0
- package/skills/paper-writing/templates/rapid-prototype-paper-skeleton.md +46 -0
- package/skills/paper-writing/templates/source-packet.md +37 -0
- package/skills/paper-writing/templates/submission-readiness.md +41 -0
- package/skills/proof-blueprint-review/SKILL.md +129 -0
- package/skills/proof-blueprint-review/references/agent-mediated-proof-protocol.md +57 -0
- package/skills/proof-blueprint-review/references/generation-agent.md +45 -0
- package/skills/proof-blueprint-review/references/proof-acceptance-contract.md +41 -0
- package/skills/proof-blueprint-review/references/verification-agent.md +37 -0
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Co-Mathematician research-workspace gate checks — TypeScript port of the
|
|
3
|
+
* documented workspace contract (upstream `harness/co_math/gating.py`):
|
|
4
|
+
* three gates over a plain-file workspace layout
|
|
5
|
+
* (`project/GOALS.yaml`, `workstreams/<id>/{status.yaml, report.md, reviews/}`).
|
|
6
|
+
* Pure file-contract validation, no upstream code copied.
|
|
7
|
+
* @module @louisultra/dsh-verymath/core
|
|
8
|
+
*/
|
|
9
|
+
import { readFile, readdir, stat } from 'node:fs/promises';
|
|
10
|
+
import { join } from 'node:path';
|
|
11
|
+
import { VeryMathError } from "./error.js";
|
|
12
|
+
import { load as loadYaml } from 'js-yaml';
|
|
13
|
+
/** The workspace root containing `project/` and `workstreams/`. */
|
|
14
|
+
export function workspaceRoots(workspace) {
|
|
15
|
+
return { projectDir: join(workspace, 'project'), workstreamsDir: join(workspace, 'workstreams') };
|
|
16
|
+
}
|
|
17
|
+
/** Read `project/GOALS.yaml`; a missing file means "no goals recorded". */
|
|
18
|
+
export async function loadGoals(workspace) {
|
|
19
|
+
const { projectDir } = workspaceRoots(workspace);
|
|
20
|
+
try {
|
|
21
|
+
const raw = await readFile(join(projectDir, 'GOALS.yaml'), 'utf8');
|
|
22
|
+
const data = (loadYaml(raw) ?? {});
|
|
23
|
+
const goals = Array.isArray(data.goals) ? data.goals : [];
|
|
24
|
+
return { goals };
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return { goals: [] };
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
/** List workstream directories (recognized by their marker files). */
|
|
31
|
+
export async function listWorkstreams(workspace, workstreamId) {
|
|
32
|
+
const { workstreamsDir } = workspaceRoots(workspace);
|
|
33
|
+
if (workstreamId !== undefined) {
|
|
34
|
+
return [join(workstreamsDir, workstreamId)];
|
|
35
|
+
}
|
|
36
|
+
try {
|
|
37
|
+
const entries = await readdir(workstreamsDir, { withFileTypes: true });
|
|
38
|
+
const dirs = [];
|
|
39
|
+
for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
|
|
40
|
+
if (!entry.isDirectory())
|
|
41
|
+
continue;
|
|
42
|
+
const dir = join(workstreamsDir, entry.name);
|
|
43
|
+
if (await isWorkstreamDir(dir))
|
|
44
|
+
dirs.push(dir);
|
|
45
|
+
}
|
|
46
|
+
return dirs;
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
return [];
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
async function isWorkstreamDir(dir) {
|
|
53
|
+
for (const marker of ['status.yaml', 'WORKSTREAM.md', 'report.md', 'messages.jsonl']) {
|
|
54
|
+
try {
|
|
55
|
+
await stat(join(dir, marker));
|
|
56
|
+
return true;
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
// try next marker
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return false;
|
|
63
|
+
}
|
|
64
|
+
async function loadStatus(workstream) {
|
|
65
|
+
try {
|
|
66
|
+
const raw = await readFile(join(workstream, 'status.yaml'), 'utf8');
|
|
67
|
+
return (loadYaml(raw) ?? {});
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
return {};
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
async function loadReviews(workstream) {
|
|
74
|
+
let files;
|
|
75
|
+
try {
|
|
76
|
+
files = (await readdir(join(workstream, 'reviews'))).filter(name => name.endsWith('.json')).sort();
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
return [];
|
|
80
|
+
}
|
|
81
|
+
const reviews = [];
|
|
82
|
+
for (const file of files) {
|
|
83
|
+
try {
|
|
84
|
+
const data = JSON.parse(await readFile(join(workstream, 'reviews', file), 'utf8'));
|
|
85
|
+
reviews.push({
|
|
86
|
+
file,
|
|
87
|
+
reviewer: String(data.reviewer ?? file.replace(/\.json$/u, '')),
|
|
88
|
+
approved: data.approved === true,
|
|
89
|
+
// Upstream contract: only an explicit severity === 'blocking' blocks.
|
|
90
|
+
severity: String(data.severity ?? ''),
|
|
91
|
+
resolved: data.resolved === true,
|
|
92
|
+
resolves: Array.isArray(data.resolves) ? data.resolves.map(item => String(item)) : [],
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
reviews.push({ file, reviewer: file.replace(/\.json$/u, ''), approved: false, severity: 'blocking', resolved: false, resolves: [] });
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return reviews;
|
|
100
|
+
}
|
|
101
|
+
/** Whether a report body contains the `## <section>` heading (case-insensitive, exact line). */
|
|
102
|
+
export function hasSection(text, section) {
|
|
103
|
+
const expected = `## ${section}`.toLowerCase();
|
|
104
|
+
return text.split('\n').some(line => line.trim().toLowerCase() === expected);
|
|
105
|
+
}
|
|
106
|
+
/** Issues for one workstream per the upstream completion contract. */
|
|
107
|
+
export async function workstreamIssues(workstream) {
|
|
108
|
+
const label = workstream.split('/').pop() ?? workstream;
|
|
109
|
+
const issues = [];
|
|
110
|
+
const status = await loadStatus(workstream);
|
|
111
|
+
const reviews = await loadReviews(workstream);
|
|
112
|
+
let reportText;
|
|
113
|
+
try {
|
|
114
|
+
reportText = await readFile(join(workstream, 'report.md'), 'utf8');
|
|
115
|
+
}
|
|
116
|
+
catch {
|
|
117
|
+
reportText = undefined;
|
|
118
|
+
}
|
|
119
|
+
if (reportText === undefined)
|
|
120
|
+
issues.push(`${label}: report.md is missing.`);
|
|
121
|
+
const approvedReviewers = reviews.filter(review => review.approved).map(review => review.reviewer);
|
|
122
|
+
const coordinator = String(status.coordinator ?? 'workstream_coordinator');
|
|
123
|
+
const independentApprovals = approvedReviewers.filter(reviewer => reviewer !== coordinator);
|
|
124
|
+
if (independentApprovals.length === 0) {
|
|
125
|
+
issues.push(`${label}: missing independent reviewer approval.`);
|
|
126
|
+
}
|
|
127
|
+
const resolvedNames = new Set();
|
|
128
|
+
for (const review of reviews) {
|
|
129
|
+
if (review.resolved) {
|
|
130
|
+
resolvedNames.add(review.file);
|
|
131
|
+
resolvedNames.add(review.file.replace(/\.json$/u, ''));
|
|
132
|
+
}
|
|
133
|
+
for (const target of review.resolves) {
|
|
134
|
+
resolvedNames.add(target);
|
|
135
|
+
resolvedNames.add(target.split('/').pop() ?? target);
|
|
136
|
+
resolvedNames.add(target.replace(/\.json$/u, ''));
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
for (const review of reviews) {
|
|
140
|
+
if (review.severity === 'blocking' && !resolvedNames.has(review.file) && !resolvedNames.has(review.file.replace(/\.json$/u, ''))) {
|
|
141
|
+
issues.push(`${label}: blocking review in ${review.file}.`);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
if (reportText !== undefined) {
|
|
145
|
+
if (!hasSection(reportText, 'Provenance'))
|
|
146
|
+
issues.push(`${label}: report.md is missing a Provenance section.`);
|
|
147
|
+
if (!hasSection(reportText, 'Uncertainty'))
|
|
148
|
+
issues.push(`${label}: report.md is missing an Uncertainty section.`);
|
|
149
|
+
if (!hasSection(reportText, 'Failed Explorations'))
|
|
150
|
+
issues.push(`${label}: report.md is missing a Failed Explorations section.`);
|
|
151
|
+
}
|
|
152
|
+
return issues;
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Gate 1: at least one goal in `project/GOALS.yaml` has `status: approved`
|
|
156
|
+
* (or the named goal does).
|
|
157
|
+
*/
|
|
158
|
+
export async function checkGoalApproval(workspace, goalId) {
|
|
159
|
+
const { goals } = await loadGoals(workspace);
|
|
160
|
+
const issues = [];
|
|
161
|
+
if (goalId !== undefined) {
|
|
162
|
+
const goal = goals.find(goal => String(goal.id ?? '') === goalId);
|
|
163
|
+
if (goal === undefined) {
|
|
164
|
+
issues.push(`Goal ${goalId} was not found.`);
|
|
165
|
+
}
|
|
166
|
+
else if (String(goal.status ?? '').toLowerCase() !== 'approved') {
|
|
167
|
+
issues.push(`Goal ${goalId} is not approved (status: ${String(goal.status ?? 'missing')}).`);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
else if (!goals.some(goal => String(goal.status ?? '').toLowerCase() === 'approved')) {
|
|
171
|
+
issues.push('No approved goals are recorded.');
|
|
172
|
+
}
|
|
173
|
+
return { gate: 'goal_approval', passed: issues.length === 0, issues, details: { goalId } };
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Gate 2: every (selected) workstream has report.md, an independent reviewer
|
|
177
|
+
* approval, no unresolved blocking reviews, and the three mandatory sections.
|
|
178
|
+
*/
|
|
179
|
+
export async function checkWorkstreamCompletion(workspace, workstreamId) {
|
|
180
|
+
const workstreams = await listWorkstreams(workspace, workstreamId);
|
|
181
|
+
const issues = [];
|
|
182
|
+
const details = { workstreams: workstreams.map(path => path.split('/').pop()) };
|
|
183
|
+
if (workstreams.length === 0)
|
|
184
|
+
issues.push('No workstream directories were found.');
|
|
185
|
+
for (const workstream of workstreams)
|
|
186
|
+
issues.push(...(await workstreamIssues(workstream)));
|
|
187
|
+
return { gate: 'workstream_completion', passed: issues.length === 0, issues, details };
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Gate 3: which workstreams would pass the completion gate (final render
|
|
191
|
+
* approval set).
|
|
192
|
+
*/
|
|
193
|
+
export async function checkFinalRender(workspace) {
|
|
194
|
+
const workstreams = await listWorkstreams(workspace);
|
|
195
|
+
const approved = [];
|
|
196
|
+
const rejected = {};
|
|
197
|
+
for (const workstream of workstreams) {
|
|
198
|
+
const label = workstream.split('/').pop() ?? workstream;
|
|
199
|
+
const issues = await workstreamIssues(workstream);
|
|
200
|
+
if (issues.length === 0)
|
|
201
|
+
approved.push(label);
|
|
202
|
+
else
|
|
203
|
+
rejected[label] = issues;
|
|
204
|
+
}
|
|
205
|
+
const issues = approved.length > 0 ? [] : ['No reviewed workstream reports are ready to render.'];
|
|
206
|
+
return { gate: 'final_render', passed: issues.length === 0, issues, details: { approved_workstreams: approved, rejected_workstreams: rejected } };
|
|
207
|
+
}
|
|
208
|
+
/** Dispatch one gate by name (upstream `check_gate` shape). */
|
|
209
|
+
export async function checkGate(workspace, gate, options = {}) {
|
|
210
|
+
if (gate === 'goal_approval')
|
|
211
|
+
return checkGoalApproval(workspace, options.goalId);
|
|
212
|
+
if (gate === 'workstream_completion')
|
|
213
|
+
return checkWorkstreamCompletion(workspace, options.workstreamId);
|
|
214
|
+
if (gate === 'final_render')
|
|
215
|
+
return checkFinalRender(workspace);
|
|
216
|
+
throw new VeryMathError(`Unsupported gate: ${String(gate)}`, 'VERYMATH_IO');
|
|
217
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/** One bilingual term entry (upstream `math-glossary` contract). */
|
|
2
|
+
export interface GlossaryTerm {
|
|
3
|
+
/** Unique id: lowercased `en`, with an `__N` suffix on alias rows. */
|
|
4
|
+
readonly term_id: string;
|
|
5
|
+
/** English term as written in the source. */
|
|
6
|
+
readonly en: string;
|
|
7
|
+
/** Chinese translation; on alias rows this is the alias. */
|
|
8
|
+
readonly cn: string;
|
|
9
|
+
/** Optional 1-based contiguous position after sorting. */
|
|
10
|
+
readonly idx?: number;
|
|
11
|
+
/** Optional part of speech in Chinese (名词 / 动词 / …). */
|
|
12
|
+
readonly pos?: string;
|
|
13
|
+
/** Optional subfields, multi-value (代数拓扑, 拓扑学…). */
|
|
14
|
+
readonly field?: readonly string[];
|
|
15
|
+
/** Optional source reference label. */
|
|
16
|
+
readonly source?: string;
|
|
17
|
+
/** Optional bilingual example sentences. */
|
|
18
|
+
readonly examples?: readonly {
|
|
19
|
+
readonly en: string;
|
|
20
|
+
readonly cn: string;
|
|
21
|
+
}[];
|
|
22
|
+
/** ISO date (YYYY-MM-DD). */
|
|
23
|
+
readonly created_at: string;
|
|
24
|
+
/** ISO date (YYYY-MM-DD). */
|
|
25
|
+
readonly updated_at: string;
|
|
26
|
+
}
|
|
27
|
+
/** Whether a value parses as a complete validated glossary document. */
|
|
28
|
+
export declare function parseGlossary(value: unknown): GlossaryTerm[];
|
|
29
|
+
/**
|
|
30
|
+
* Sort terms by (en, cn) using stable code-point order and reassign
|
|
31
|
+
* contiguous 1-based `idx` values, the upstream write-path invariant.
|
|
32
|
+
* @param terms - terms in any order; the input is not mutated.
|
|
33
|
+
* @returns a new sorted array with `idx` reassigned.
|
|
34
|
+
*/
|
|
35
|
+
export declare function sortGlossary(terms: readonly GlossaryTerm[]): GlossaryTerm[];
|
|
36
|
+
/** Validate the cross-entry invariants of a stored glossary document. */
|
|
37
|
+
export declare function validateGlossaryInvariants(terms: readonly GlossaryTerm[]): void;
|
|
38
|
+
/** One glossary query hit. */
|
|
39
|
+
export interface GlossaryHit {
|
|
40
|
+
readonly term: GlossaryTerm;
|
|
41
|
+
/** Which field matched: en (exact), en-prefix, cn, field, or term_id. */
|
|
42
|
+
readonly matchedBy: 'en' | 'en-prefix' | 'cn' | 'field' | 'term_id';
|
|
43
|
+
}
|
|
44
|
+
/** Options for {@link queryGlossary}. */
|
|
45
|
+
export interface GlossaryQueryOptions {
|
|
46
|
+
/** Maximum hits returned (default 20). */
|
|
47
|
+
readonly limit?: number;
|
|
48
|
+
/** Restrict candidates to terms whose `field` array contains this subfield exactly (upstream usage-guide disambiguation strategy 2). */
|
|
49
|
+
readonly field?: string;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Query a parsed glossary: exact en/cn match first, then prefix, substring,
|
|
53
|
+
* and subfield hits. `total` is the deduplicated candidate count before the
|
|
54
|
+
* limit cut, so callers can detect truncation.
|
|
55
|
+
* @param terms - validated glossary terms.
|
|
56
|
+
* @param query - an English/Chinese term, a term_id, or a subfield name.
|
|
57
|
+
* @param options - limit and optional subfield disambiguation filter; a bare
|
|
58
|
+
* number is accepted as the limit for backwards compatibility.
|
|
59
|
+
*/
|
|
60
|
+
export declare function queryGlossary(terms: readonly GlossaryTerm[], query: string, options?: GlossaryQueryOptions | number): {
|
|
61
|
+
hits: GlossaryHit[];
|
|
62
|
+
total: number;
|
|
63
|
+
};
|
|
64
|
+
/** One term upsert request for {@link upsertTerms}. */
|
|
65
|
+
export interface TermUpsert {
|
|
66
|
+
/** English term. */
|
|
67
|
+
readonly en: string;
|
|
68
|
+
/** Chinese translation (or alias). */
|
|
69
|
+
readonly cn: string;
|
|
70
|
+
/** Optional part of speech in Chinese. */
|
|
71
|
+
readonly pos?: string;
|
|
72
|
+
/** Optional subfields. */
|
|
73
|
+
readonly field?: readonly string[];
|
|
74
|
+
/** Optional source label. */
|
|
75
|
+
readonly source?: string;
|
|
76
|
+
/** Optional bilingual example. */
|
|
77
|
+
readonly example?: {
|
|
78
|
+
readonly en: string;
|
|
79
|
+
readonly cn: string;
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
/** Result of one upsert batch. */
|
|
83
|
+
export interface UpsertResult {
|
|
84
|
+
/** New terms that did not exist before (by term_id). */
|
|
85
|
+
readonly added: readonly string[];
|
|
86
|
+
/** Existing terms whose cn/pos/field/source/examples were overwritten. */
|
|
87
|
+
readonly updated: readonly string[];
|
|
88
|
+
/** The complete re-sorted document ready to write (idx reassigned, today's dates on changed rows). */
|
|
89
|
+
readonly document: GlossaryTerm[];
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Merge upsert requests into an existing glossary per the upstream contract:
|
|
93
|
+
* term_id is the lowercased en for the primary translation and `en__N` for
|
|
94
|
+
* additional alias rows of the same en; an existing term with the same
|
|
95
|
+
* (term_id) is updated in place; the merged document is re-sorted by
|
|
96
|
+
* (en, cn) with contiguous idx. The input document is never mutated.
|
|
97
|
+
* @param terms - current glossary terms (any order).
|
|
98
|
+
* @param upserts - terms to add or update.
|
|
99
|
+
* @throws VeryMathError when the merged document breaks an invariant.
|
|
100
|
+
*/
|
|
101
|
+
export declare function upsertTerms(terms: readonly GlossaryTerm[], upserts: readonly TermUpsert[]): UpsertResult;
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bilingual glossary data model aligned with the upstream VeryMath
|
|
3
|
+
* `math-glossary` contract (glossary.schema.json v1): an array of term
|
|
4
|
+
* entries sorted by (en, cn) with contiguous 1-based `idx` numbering,
|
|
5
|
+
* plus the cross-entry invariants the upstream contract requires.
|
|
6
|
+
* @module @louisultra/dsh-verymath/core
|
|
7
|
+
*/
|
|
8
|
+
import { VeryMathError } from "./error.js";
|
|
9
|
+
/** Parse a loose value into a glossary term entry, or return a problem description. */
|
|
10
|
+
function coerceTerm(value) {
|
|
11
|
+
if (typeof value !== 'object' || value === null)
|
|
12
|
+
return { problem: `entry is ${describe(value)}, expected an object` };
|
|
13
|
+
const record = value;
|
|
14
|
+
const problems = [];
|
|
15
|
+
for (const field of ['term_id', 'en', 'cn', 'created_at', 'updated_at']) {
|
|
16
|
+
if (typeof record[field] !== 'string' || record[field].length === 0) {
|
|
17
|
+
problems.push(`${field} must be a non-empty string`);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
if (problems.length > 0)
|
|
21
|
+
return { problem: problems.join('; ') };
|
|
22
|
+
// Build the complete entry in one pass: GlossaryTerm fields are readonly,
|
|
23
|
+
// so optional fields are included up front instead of assigned afterwards.
|
|
24
|
+
const fields = Array.isArray(record.field)
|
|
25
|
+
? record.field.filter((entry) => typeof entry === 'string' && entry.length > 0)
|
|
26
|
+
: [];
|
|
27
|
+
const examples = Array.isArray(record.examples)
|
|
28
|
+
? record.examples.flatMap((entry) => {
|
|
29
|
+
if (typeof entry !== 'object' || entry === null)
|
|
30
|
+
return [];
|
|
31
|
+
const example = entry;
|
|
32
|
+
if (typeof example.en !== 'string' || typeof example.cn !== 'string')
|
|
33
|
+
return [];
|
|
34
|
+
return [{ en: example.en, cn: example.cn }];
|
|
35
|
+
})
|
|
36
|
+
: [];
|
|
37
|
+
const term = {
|
|
38
|
+
term_id: record.term_id,
|
|
39
|
+
en: record.en,
|
|
40
|
+
cn: record.cn,
|
|
41
|
+
...(typeof record.idx === 'number' ? { idx: record.idx } : {}),
|
|
42
|
+
...(typeof record.pos === 'string' && record.pos.length > 0 ? { pos: record.pos } : {}),
|
|
43
|
+
...(typeof record.source === 'string' && record.source.length > 0 ? { source: record.source } : {}),
|
|
44
|
+
...(fields.length > 0 ? { field: fields } : {}),
|
|
45
|
+
...(examples.length > 0 ? { examples } : {}),
|
|
46
|
+
created_at: record.created_at,
|
|
47
|
+
updated_at: record.updated_at,
|
|
48
|
+
};
|
|
49
|
+
return { term };
|
|
50
|
+
}
|
|
51
|
+
function describe(value) {
|
|
52
|
+
if (value === null)
|
|
53
|
+
return 'null';
|
|
54
|
+
if (Array.isArray(value))
|
|
55
|
+
return 'an array';
|
|
56
|
+
return typeof value;
|
|
57
|
+
}
|
|
58
|
+
const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
|
|
59
|
+
/** Whether a value parses as a complete validated glossary document. */
|
|
60
|
+
export function parseGlossary(value) {
|
|
61
|
+
if (!Array.isArray(value)) {
|
|
62
|
+
throw new VeryMathError(`glossary document must be an array, got ${describe(value)}`, 'VERYMATH_GLOSSARY_INVALID');
|
|
63
|
+
}
|
|
64
|
+
const terms = [];
|
|
65
|
+
for (const [index, entry] of value.entries()) {
|
|
66
|
+
const result = coerceTerm(entry);
|
|
67
|
+
if ('problem' in result) {
|
|
68
|
+
throw new VeryMathError(`glossary entry ${index}: ${result.problem}`, 'VERYMATH_GLOSSARY_INVALID');
|
|
69
|
+
}
|
|
70
|
+
terms.push(result.term);
|
|
71
|
+
}
|
|
72
|
+
return terms;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Sort terms by (en, cn) using stable code-point order and reassign
|
|
76
|
+
* contiguous 1-based `idx` values, the upstream write-path invariant.
|
|
77
|
+
* @param terms - terms in any order; the input is not mutated.
|
|
78
|
+
* @returns a new sorted array with `idx` reassigned.
|
|
79
|
+
*/
|
|
80
|
+
export function sortGlossary(terms) {
|
|
81
|
+
const sorted = [...terms].sort((left, right) => compareCodePoints(left.en, right.en) || compareCodePoints(left.cn, right.cn));
|
|
82
|
+
return sorted.map((term, index) => ({ ...term, idx: index + 1 }));
|
|
83
|
+
}
|
|
84
|
+
function compareCodePoints(left, right) {
|
|
85
|
+
if (left < right)
|
|
86
|
+
return -1;
|
|
87
|
+
if (left > right)
|
|
88
|
+
return 1;
|
|
89
|
+
return 0;
|
|
90
|
+
}
|
|
91
|
+
/** Validate the cross-entry invariants of a stored glossary document. */
|
|
92
|
+
export function validateGlossaryInvariants(terms) {
|
|
93
|
+
const seen = new Map();
|
|
94
|
+
for (const term of terms) {
|
|
95
|
+
seen.set(term.term_id, (seen.get(term.term_id) ?? 0) + 1);
|
|
96
|
+
for (const field of ['created_at', 'updated_at']) {
|
|
97
|
+
if (!ISO_DATE.test(term[field])) {
|
|
98
|
+
throw new VeryMathError(`term ${term.term_id}: ${field} must be YYYY-MM-DD`, 'VERYMATH_GLOSSARY_INVALID');
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
const duplicates = [...seen.entries()].filter(([, count]) => count > 1).map(([id]) => id);
|
|
103
|
+
if (duplicates.length > 0) {
|
|
104
|
+
throw new VeryMathError(`duplicate term_id values: ${duplicates.join(', ')}`, 'VERYMATH_GLOSSARY_INVALID');
|
|
105
|
+
}
|
|
106
|
+
const ids = terms.map(term => term.idx).filter(index => index !== undefined);
|
|
107
|
+
if (ids.length > 0) {
|
|
108
|
+
const expected = terms.map((_, index) => index + 1);
|
|
109
|
+
const actual = ids;
|
|
110
|
+
const contiguous = actual.length === terms.length && actual.every((value, index) => value === expected[index]);
|
|
111
|
+
if (!contiguous) {
|
|
112
|
+
throw new VeryMathError('idx numbering must be contiguous 1-based over the sorted document', 'VERYMATH_GLOSSARY_INVALID');
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Query a parsed glossary: exact en/cn match first, then prefix, substring,
|
|
118
|
+
* and subfield hits. `total` is the deduplicated candidate count before the
|
|
119
|
+
* limit cut, so callers can detect truncation.
|
|
120
|
+
* @param terms - validated glossary terms.
|
|
121
|
+
* @param query - an English/Chinese term, a term_id, or a subfield name.
|
|
122
|
+
* @param options - limit and optional subfield disambiguation filter; a bare
|
|
123
|
+
* number is accepted as the limit for backwards compatibility.
|
|
124
|
+
*/
|
|
125
|
+
export function queryGlossary(terms, query, options = {}) {
|
|
126
|
+
const opts = typeof options === 'number' ? { limit: options } : options;
|
|
127
|
+
const limit = opts.limit ?? 20;
|
|
128
|
+
const fieldFilter = opts.field?.trim();
|
|
129
|
+
const candidates = fieldFilter !== undefined && fieldFilter.length > 0
|
|
130
|
+
? terms.filter(term => term.field?.includes(fieldFilter) === true)
|
|
131
|
+
: terms;
|
|
132
|
+
const needle = query.trim();
|
|
133
|
+
if (needle.length === 0)
|
|
134
|
+
return { hits: [], total: 0 };
|
|
135
|
+
const lower = needle.toLowerCase();
|
|
136
|
+
const hits = [];
|
|
137
|
+
const matched = new Set();
|
|
138
|
+
let total = 0;
|
|
139
|
+
const push = (term, matchedBy) => {
|
|
140
|
+
if (matched.has(term.term_id))
|
|
141
|
+
return;
|
|
142
|
+
matched.add(term.term_id);
|
|
143
|
+
total += 1;
|
|
144
|
+
if (hits.length < limit)
|
|
145
|
+
hits.push({ term, matchedBy });
|
|
146
|
+
};
|
|
147
|
+
for (const term of candidates) {
|
|
148
|
+
if (term.en.toLowerCase() === lower || term.cn === needle)
|
|
149
|
+
push(term, 'en');
|
|
150
|
+
else if (term.term_id.toLowerCase() === lower)
|
|
151
|
+
push(term, 'term_id');
|
|
152
|
+
}
|
|
153
|
+
for (const term of candidates) {
|
|
154
|
+
if (term.en.toLowerCase().startsWith(lower))
|
|
155
|
+
push(term, 'en-prefix');
|
|
156
|
+
}
|
|
157
|
+
for (const term of candidates) {
|
|
158
|
+
if (term.cn.includes(needle))
|
|
159
|
+
push(term, 'cn');
|
|
160
|
+
}
|
|
161
|
+
for (const term of candidates) {
|
|
162
|
+
if (term.field?.some(entry => entry === needle || entry.includes(needle)))
|
|
163
|
+
push(term, 'field');
|
|
164
|
+
}
|
|
165
|
+
return { hits, total };
|
|
166
|
+
}
|
|
167
|
+
const UPSERT_DATE = /^\d{4}-\d{2}-\d{2}$/;
|
|
168
|
+
/** Today as an ISO date (upsert stamps updated_at/created_at). */
|
|
169
|
+
function todayIso() {
|
|
170
|
+
const now = new Date();
|
|
171
|
+
const month = String(now.getMonth() + 1).padStart(2, '0');
|
|
172
|
+
const day = String(now.getDate()).padStart(2, '0');
|
|
173
|
+
return `${now.getFullYear()}-${month}-${day}`;
|
|
174
|
+
}
|
|
175
|
+
/** Optional-field merge: keep the request value, else keep the existing one. */
|
|
176
|
+
function keepOr(request, existing) {
|
|
177
|
+
return request !== undefined ? request : existing;
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Merge upsert requests into an existing glossary per the upstream contract:
|
|
181
|
+
* term_id is the lowercased en for the primary translation and `en__N` for
|
|
182
|
+
* additional alias rows of the same en; an existing term with the same
|
|
183
|
+
* (term_id) is updated in place; the merged document is re-sorted by
|
|
184
|
+
* (en, cn) with contiguous idx. The input document is never mutated.
|
|
185
|
+
* @param terms - current glossary terms (any order).
|
|
186
|
+
* @param upserts - terms to add or update.
|
|
187
|
+
* @throws VeryMathError when the merged document breaks an invariant.
|
|
188
|
+
*/
|
|
189
|
+
export function upsertTerms(terms, upserts) {
|
|
190
|
+
const today = todayIso();
|
|
191
|
+
for (const date of [today]) {
|
|
192
|
+
if (!UPSERT_DATE.test(date)) {
|
|
193
|
+
throw new VeryMathError('system date is not ISO; refusing to stamp terms', 'VERYMATH_GLOSSARY_INVALID');
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
const byId = new Map(terms.map(term => [term.term_id, { ...term }]));
|
|
197
|
+
const added = [];
|
|
198
|
+
const updated = [];
|
|
199
|
+
for (const request of upserts) {
|
|
200
|
+
const en = request.en.trim();
|
|
201
|
+
const cn = request.cn.trim();
|
|
202
|
+
if (en.length === 0 || cn.length === 0) {
|
|
203
|
+
throw new VeryMathError('upsert requires non-empty en and cn', 'VERYMATH_GLOSSARY_INVALID');
|
|
204
|
+
}
|
|
205
|
+
const termId = en.toLowerCase();
|
|
206
|
+
const existing = byId.get(termId);
|
|
207
|
+
const field = request.field !== undefined && request.field.length > 0 ? [...request.field] : undefined;
|
|
208
|
+
const examples = request.example !== undefined ? [{ ...request.example }] : undefined;
|
|
209
|
+
if (existing !== undefined) {
|
|
210
|
+
const pos = keepOr(request.pos, existing.pos);
|
|
211
|
+
const mergedField = keepOr(field, existing.field);
|
|
212
|
+
const source = keepOr(request.source, existing.source);
|
|
213
|
+
const mergedExamples = keepOr(examples, existing.examples);
|
|
214
|
+
byId.set(termId, {
|
|
215
|
+
...existing,
|
|
216
|
+
cn,
|
|
217
|
+
...(pos !== undefined ? { pos } : {}),
|
|
218
|
+
...(mergedField !== undefined ? { field: mergedField } : {}),
|
|
219
|
+
...(source !== undefined ? { source } : {}),
|
|
220
|
+
...(mergedExamples !== undefined ? { examples: mergedExamples } : {}),
|
|
221
|
+
updated_at: today,
|
|
222
|
+
});
|
|
223
|
+
updated.push(termId);
|
|
224
|
+
}
|
|
225
|
+
else {
|
|
226
|
+
byId.set(termId, {
|
|
227
|
+
term_id: termId,
|
|
228
|
+
en,
|
|
229
|
+
cn,
|
|
230
|
+
...(request.pos !== undefined ? { pos: request.pos } : {}),
|
|
231
|
+
...(field !== undefined ? { field } : {}),
|
|
232
|
+
...(request.source !== undefined ? { source: request.source } : {}),
|
|
233
|
+
...(examples !== undefined ? { examples } : {}),
|
|
234
|
+
created_at: today,
|
|
235
|
+
updated_at: today,
|
|
236
|
+
});
|
|
237
|
+
added.push(termId);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
const document = sortGlossary([...byId.values()]);
|
|
241
|
+
validateGlossaryInvariants(document);
|
|
242
|
+
return { added, updated, document };
|
|
243
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import type { PaperEntity, PaperStructure } from './paper.ts';
|
|
2
|
+
/** A structure artifact may arrive as one file or as multiple batch files. */
|
|
3
|
+
export type StructureInput = PaperStructure | readonly PaperStructure[];
|
|
4
|
+
/** Merge report summarizing what the merge changed. */
|
|
5
|
+
export interface MergeReport {
|
|
6
|
+
/** Total entities after merging. */
|
|
7
|
+
readonly totalEntities: number;
|
|
8
|
+
/** Number of duplicate-label entities that were merged away (first occurrence wins). */
|
|
9
|
+
readonly mergedDuplicates: number;
|
|
10
|
+
/** Dependency edges whose target label is not in the merged set (excluded from graph math). */
|
|
11
|
+
readonly danglingEdges: readonly string[];
|
|
12
|
+
/** Number of reverse edges rebuilt from forward dependencies. */
|
|
13
|
+
readonly rebuiltCitedBy: number;
|
|
14
|
+
/** Shared hubs detected after the merge (upstream shared_node rule). */
|
|
15
|
+
readonly sharedNodes: readonly string[];
|
|
16
|
+
}
|
|
17
|
+
/** Per-entity topology metrics aligned with upstream compute_topology.py. */
|
|
18
|
+
export interface EntityTopology {
|
|
19
|
+
readonly label: string;
|
|
20
|
+
readonly type: PaperEntity['type'];
|
|
21
|
+
/** Number of distinct merged entities depending on this one. */
|
|
22
|
+
readonly inDegree: number;
|
|
23
|
+
/** dependencies + uncertain_dependencies count (known labels only). */
|
|
24
|
+
readonly outDegree: number;
|
|
25
|
+
/** Upstream shared-node rule: in-degree ≥ 2 and at least one citing THEOREM. */
|
|
26
|
+
readonly sharedNode: boolean;
|
|
27
|
+
/** Whether any main theorem transitively depends on this entity. */
|
|
28
|
+
readonly supportsMainTheorem: boolean;
|
|
29
|
+
/** Uncertain dependency labels with the `[UNCERTAIN: …]` suffix stripped. */
|
|
30
|
+
readonly uncertainDependencies: readonly string[];
|
|
31
|
+
}
|
|
32
|
+
/** One cycle found in the dependency graph. */
|
|
33
|
+
export interface DependencyCycle {
|
|
34
|
+
readonly labels: readonly string[];
|
|
35
|
+
}
|
|
36
|
+
/** Topology result for a whole artifact. */
|
|
37
|
+
export interface GraphTopology {
|
|
38
|
+
readonly metrics: readonly EntityTopology[];
|
|
39
|
+
readonly cycles: readonly DependencyCycle[];
|
|
40
|
+
/** Bottom-up reproduction order: dependency-free labels first, level by level (Kahn layers). */
|
|
41
|
+
readonly bottomUpLevels: readonly (readonly string[])[];
|
|
42
|
+
/** Top-down order from main theorems along dependency edges (BFS). */
|
|
43
|
+
readonly topDownOrder: readonly string[];
|
|
44
|
+
/** Longest dependency chain (by node count), earliest label first. */
|
|
45
|
+
readonly longestChain: readonly string[];
|
|
46
|
+
/** Labels with no known dependency and no dependent (orphan results). */
|
|
47
|
+
readonly isolated: readonly string[];
|
|
48
|
+
/** Whether the artifact exceeds the upstream full-render threshold (> 40 entities). */
|
|
49
|
+
readonly degradedRendering: boolean;
|
|
50
|
+
}
|
|
51
|
+
/** Type guard: `Array.isArray` cannot narrow `readonly T[]` unions, so this
|
|
52
|
+
* predicate provides reliable narrowing for both branches. */
|
|
53
|
+
export declare function isSingleStructure(input: StructureInput): input is PaperStructure;
|
|
54
|
+
/** Strip the upstream `[UNCERTAIN: reason]` suffix from a dependency label. */
|
|
55
|
+
export declare function stripUncertain(dependency: string): string;
|
|
56
|
+
/**
|
|
57
|
+
* Unique entities across one or more batch artifacts, keyed by label
|
|
58
|
+
* (first occurrence wins, duplicates counted). Order follows input order.
|
|
59
|
+
* @param input - one artifact or a list of batch artifacts.
|
|
60
|
+
*/
|
|
61
|
+
export declare function collectEntities(input: StructureInput): {
|
|
62
|
+
entities: PaperEntity[];
|
|
63
|
+
duplicates: number;
|
|
64
|
+
};
|
|
65
|
+
/**
|
|
66
|
+
* Merge batch artifacts per the upstream Skill-2 protocol: dedupe by label,
|
|
67
|
+
* rebuild the reverse index (`cited_by`) from forward `dependencies` and
|
|
68
|
+
* cleaned `uncertain_dependencies`, and compute `shared_node` (in-degree ≥ 2
|
|
69
|
+
* with at least one citing THEOREM). Input artifacts are never mutated; the
|
|
70
|
+
* returned entities are rebuilt copies.
|
|
71
|
+
* @param input - one artifact or a list of batch artifacts.
|
|
72
|
+
* @returns rebuilt entities plus a merge report.
|
|
73
|
+
*/
|
|
74
|
+
export declare function mergeBatches(input: StructureInput): {
|
|
75
|
+
entities: PaperEntity[];
|
|
76
|
+
report: MergeReport;
|
|
77
|
+
};
|
|
78
|
+
/**
|
|
79
|
+
* Compute the full topology of a (possibly batched) artifact: per-entity
|
|
80
|
+
* metrics, cycles, both reading directions, longest chain, and orphans.
|
|
81
|
+
* @param input - one artifact or merged batches.
|
|
82
|
+
* @param mainTheoremLabels - explicit theorem roots; defaults to the artifact's `main_theorems`.
|
|
83
|
+
*/
|
|
84
|
+
export declare function computeTopology(input: StructureInput, mainTheoremLabels?: readonly string[]): GraphTopology;
|
|
85
|
+
/** Clean one statement into a safe ≤50-char Mermaid display text (upstream §3.2):
|
|
86
|
+
* strip $ delimiters and render commands but keep the inner content (e.g.
|
|
87
|
+
* \mathbb{R}^d → R^d), then sanitize and truncate. */
|
|
88
|
+
export declare function mermaidDisplayText(label: string, statement: string): string;
|
|
89
|
+
/**
|
|
90
|
+
* Render a full or degraded Mermaid dependency graph (upstream §3/§4/§6):
|
|
91
|
+
* subgraph layering, UNCERTAIN/EXTERNAL dashed edges, shared/auto markers,
|
|
92
|
+
* and the >40-node degradation to depth-2 THEOREM-rooted subgraphs.
|
|
93
|
+
* @param structure - the structure artifact holding the entities.
|
|
94
|
+
* @param options - force full rendering even above the degradation threshold.
|
|
95
|
+
*/
|
|
96
|
+
export declare function renderMermaid(structure: PaperStructure, options?: {
|
|
97
|
+
readonly forceFull?: boolean;
|
|
98
|
+
}): string;
|
|
99
|
+
/** Throw a structured error when a structure artifact cannot be processed. */
|
|
100
|
+
export declare function requireStructure(value: unknown): PaperStructure;
|
|
101
|
+
/** Transitive dependency closure of one entity plus its reading path. */
|
|
102
|
+
export interface FocusResult {
|
|
103
|
+
readonly label: string;
|
|
104
|
+
/** All labels transitively required by the focus entity (including itself), topologically ordered bottom-up. */
|
|
105
|
+
readonly closure: readonly string[];
|
|
106
|
+
/** BFS layers from the focus entity down to its foundations (level 0 = the focus label). */
|
|
107
|
+
readonly levels: readonly (readonly string[])[];
|
|
108
|
+
/** Whether the focus label resolved to a known entity. */
|
|
109
|
+
readonly found: boolean;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Compute the transitive dependency closure and layered reading path for one
|
|
113
|
+
* entity (upstream skill_pathway_proof §5 reading-path generation, which the
|
|
114
|
+
* skill currently delegates to unreliable model-side BFS).
|
|
115
|
+
* @param input - one artifact or merged batches.
|
|
116
|
+
* @param label - the focus entity label.
|
|
117
|
+
*/
|
|
118
|
+
export declare function focusClosure(input: StructureInput, label: string): FocusResult;
|