@louisultra/dsh-verymath 0.3.2 → 0.3.4

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 (34) hide show
  1. package/CHANGELOG.md +170 -0
  2. package/README.md +37 -6
  3. package/README_EN.md +37 -6
  4. package/UPSTREAM.json +1 -1
  5. package/docs/examples/README.md +5 -5
  6. package/lib/core/error.d.ts +7 -0
  7. package/lib/core/error.js +9 -0
  8. package/lib/core/glossary.d.ts +43 -9
  9. package/lib/core/glossary.js +216 -33
  10. package/lib/core/graph.d.ts +18 -1
  11. package/lib/core/graph.js +43 -6
  12. package/lib/core/index.d.ts +22 -3
  13. package/lib/core/index.js +49 -5
  14. package/lib/core/paper.d.ts +17 -3
  15. package/lib/core/paper.js +43 -12
  16. package/lib/index.d.ts +20 -0
  17. package/lib/index.js +20 -0
  18. package/lib/tool/index.d.ts +23 -0
  19. package/lib/tool/index.js +211 -65
  20. package/package.json +25 -24
  21. package/skills/math-glossary/SKILL.md +1 -0
  22. package/skills/after-ocr/tests/test_scripts.py +0 -84
  23. package/skills/lean-formalization/lean-runtime/tests/fixtures/after_bad.lean +0 -4
  24. package/skills/lean-formalization/lean-runtime/tests/fixtures/after_statement_changed.lean +0 -4
  25. package/skills/lean-formalization/lean-runtime/tests/fixtures/before.lean +0 -4
  26. package/skills/lean-formalization/lean-runtime/tests/fixtures/failure.lean +0 -7
  27. package/skills/lean-formalization/lean-runtime/tests/test_check_lean_project.py +0 -59
  28. package/skills/lean-formalization/lean-runtime/tests/test_cli.py +0 -377
  29. package/skills/lean-formalization/lean-runtime/tests/test_common_config.py +0 -84
  30. package/skills/lean-formalization/lean-runtime/tests/test_configure_lean.py +0 -138
  31. package/skills/lean-formalization/lean-runtime/tests/test_detect_sorry.py +0 -24
  32. package/skills/lean-formalization/lean-runtime/tests/test_direct_task.py +0 -69
  33. package/skills/lean-formalization/lean-runtime/tests/test_numina_runtime.py +0 -168
  34. package/skills/lean-formalization/lean-runtime/tests/test_validate_patch.py +0 -29
package/lib/index.d.ts ADDED
@@ -0,0 +1,20 @@
1
+ /**
2
+ * VeryMath capability plugin for DSH — package entry.
3
+ *
4
+ * The bundle mounts two modules through `cordis.patch.yml`:
5
+ * `./core` (the `ctx.verymath` service: glossary, paper, graph, gates, Sage)
6
+ * and `./tool` (the 14 model-facing tools). This module re-exports both so an
7
+ * `import '@louisultra/dsh-verymath'` gets the same surface as the subpaths.
8
+ *
9
+ * Without this module the package root declared in `package.json` (`main`,
10
+ * `types` and `exports["."]` → `lib/index.js`) is emitted by no build and
11
+ * importing the package by name fails, even though DSH itself loads the
12
+ * `./core` and `./tool` subpaths and therefore never noticed.
13
+ *
14
+ * Upstream: VeryMath AI4Math repositories (MIT). See NOTICE.md and
15
+ * UPSTREAM.json for per-repository provenance.
16
+ *
17
+ * @module @louisultra/dsh-verymath
18
+ */
19
+ export * as core from './core/index.ts';
20
+ export * as tool from './tool/index.ts';
package/lib/index.js ADDED
@@ -0,0 +1,20 @@
1
+ /**
2
+ * VeryMath capability plugin for DSH — package entry.
3
+ *
4
+ * The bundle mounts two modules through `cordis.patch.yml`:
5
+ * `./core` (the `ctx.verymath` service: glossary, paper, graph, gates, Sage)
6
+ * and `./tool` (the 14 model-facing tools). This module re-exports both so an
7
+ * `import '@louisultra/dsh-verymath'` gets the same surface as the subpaths.
8
+ *
9
+ * Without this module the package root declared in `package.json` (`main`,
10
+ * `types` and `exports["."]` → `lib/index.js`) is emitted by no build and
11
+ * importing the package by name fails, even though DSH itself loads the
12
+ * `./core` and `./tool` subpaths and therefore never noticed.
13
+ *
14
+ * Upstream: VeryMath AI4Math repositories (MIT). See NOTICE.md and
15
+ * UPSTREAM.json for per-repository provenance.
16
+ *
17
+ * @module @louisultra/dsh-verymath
18
+ */
19
+ export * as core from "./core/index.js";
20
+ export * as tool from "./tool/index.js";
@@ -17,5 +17,28 @@ export interface Config {
17
17
  readonly glossaryHome?: string;
18
18
  }
19
19
  export declare const Config: z<Config>;
20
+ /**
21
+ * Search path for the SageMath probe only. `sage` is normally installed as a
22
+ * *named* conda environment (`conda create -n sage sage=10.9`), so the base-env
23
+ * directories above are not where it lives; this adds `<root>/envs/<name>/bin`
24
+ * for each known distribution root. Kept separate from the generic search path
25
+ * so TeX and other lookups do not start probing unrelated environment trees.
26
+ */
27
+ export declare function sageSearchDirs(): string[];
28
+ /**
29
+ * Resolve the `sage` executable: an explicit `VERYMATH_SAGE` path wins, then the
30
+ * SageMath search path (PATH, TeX/conda base dirs, named conda environments).
31
+ * An override that is not executable is ignored rather than reported as found.
32
+ */
33
+ export declare function resolveSageExecutable(): string | undefined;
34
+ /**
35
+ * Resolve an executable name to an absolute path. Resolving in-process avoids
36
+ * `which`/`where`, which are not both available and which cannot see the TeX
37
+ * fallback directories above. On Windows the `PATHEXT` suffixes are tried.
38
+ * @param name - bare executable name, or a path containing a separator.
39
+ * @param searchDirs - directories probed for a bare name (defaults to PATH plus fallbacks).
40
+ * @returns the resolved absolute path, or undefined when nothing is executable.
41
+ */
42
+ export declare function resolveExecutable(name: string, searchDirs?: readonly string[]): string | undefined;
20
43
  /** Register the VeryMath glossary and paper tools. */
21
44
  export declare const apply: (ctx: Context, config?: Config) => void;
package/lib/tool/index.js CHANGED
@@ -1,9 +1,11 @@
1
1
  import z from '@deepseek-ai/schemastery';
2
2
  import { defineTool } from '@deepseek-ai/dsh-tools';
3
3
  import { spawn } from 'node:child_process';
4
- import { isAbsolute, resolve } from 'node:path';
4
+ import { accessSync, constants, readdirSync } from 'node:fs';
5
+ import { homedir } from 'node:os';
6
+ import { delimiter, isAbsolute, join, resolve } from 'node:path';
5
7
  import { VeryMathError, isVeryMathError } from '@louisultra/dsh-verymath/core';
6
- import { bundledSkillsDir, checkGate, computeTopology, dependencySummary, findExcerpt, focusClosure, loadManifest, mergeBatches, parsePaperStructure, readCorpusDocWindow, renderMermaid, resolveCorpusRoot, searchSageRefs, termsFor, upsertTerms } from '@louisultra/dsh-verymath/core';
8
+ import { bundledSkillsDir, checkGate, computeTopology, dependencySummary, findExcerpt, focusClosure, loadManifest, mergeBatches, mergeStructures, parsePaperBatch, parsePaperStructure, readCorpusDocWindow, renderMermaid, resolveCorpusRoot, searchSageRefs, termsFor, upsertTerms } from '@louisultra/dsh-verymath/core';
7
9
  export const name = 'tool-verymath';
8
10
  export const inject = ['tools', 'verymath', 'fs'];
9
11
  export const Config = z.object({
@@ -95,40 +97,149 @@ function probeCommand(executable, args, timeoutMs = 5_000) {
95
97
  }
96
98
  const stdout = [];
97
99
  let settled = false;
100
+ // Cleared on settle: an uncleared timer kept the event loop alive for the
101
+ // full timeout after the probe had already answered (up to 5s of dead wait
102
+ // per probe call in short-lived runs).
103
+ let timer;
98
104
  const settle = (value) => {
99
105
  if (!settled) {
100
106
  settled = true;
107
+ if (timer !== undefined)
108
+ clearTimeout(timer);
101
109
  resolvePromise(value);
102
110
  }
103
111
  };
104
112
  child.stdout?.on('data', (chunk) => stdout.push(chunk));
105
113
  child.on('error', () => settle(undefined));
106
114
  child.on('close', (code) => settle({ exitCode: code ?? -1, stdout: Buffer.concat(stdout).toString() }));
107
- setTimeout(() => {
115
+ timer = setTimeout(() => {
108
116
  child.kill();
109
117
  settle(undefined);
110
118
  }, timeoutMs);
111
119
  });
112
120
  }
113
121
  /**
114
- * Probe the math-beamer TeX toolchain: latexmk and xelatex binaries (PATH +
115
- * `--version` smoke) and the forest/ctex LaTeX packages (`kpsewhich <name>.sty`).
116
- * Nothing is installed, compiled, or downloaded; each probe is independent so a
117
- * partial toolchain reports per-piece detail (mirrors the osqp/sage probe pattern).
122
+ * Directories a TeX distribution installs into without adding them to the
123
+ * inherited PATH. Desktop applications launched from Finder or the Start menu
124
+ * do not read the login shell profile, so MacTeX's `/Library/TeX/texbin` is
125
+ * commonly invisible to a bare `spawn(name)` even when the toolchain is
126
+ * installed. Nothing here is required: an empty result just means PATH decides.
118
127
  */
119
- async function probeBeamerToolchain() {
120
- const binaries = [
121
- { name: 'latexmk' },
122
- { name: 'xelatex' },
123
- ];
124
- const styles = [
125
- { name: 'forest' },
126
- { name: 'ctex', note: 'required by Chinese/bilingual templates only' },
128
+ function texBinFallbackDirs() {
129
+ return process.platform === 'darwin' ? ['/Library/TeX/texbin'] : [];
130
+ }
131
+ /**
132
+ * Directories conda-style installs put `python3`/`sage` in but rarely add to the
133
+ * PATH a desktop app inherits: a macOS app launched from Finder reads no login
134
+ * shell profile, so a `sage` installed under `~/miniforge3` is invisible even
135
+ * though the user "has SageMath installed". Derived from the home directory, so
136
+ * nothing here is machine-specific.
137
+ */
138
+ function condaBinFallbackDirs() {
139
+ const home = homedir();
140
+ return ['miniforge3', 'mambaforge', 'miniconda3', 'anaconda3', 'micromamba']
141
+ .map(name => join(home, name, 'bin'));
142
+ }
143
+ /** Conda distribution roots this package knows about, including its own docs' layout. */
144
+ function condaRoots() {
145
+ const home = homedir();
146
+ return [
147
+ join(home, '.verymath', 'miniforge'),
148
+ join(home, 'miniforge3'),
149
+ join(home, 'mambaforge'),
150
+ join(home, 'miniconda3'),
151
+ join(home, 'anaconda3'),
127
152
  ];
128
- const binaryProbes = await Promise.all(binaries.map(async ({ name }) => {
129
- const which = await probeCommand('/usr/bin/which', [name]).catch(() => undefined);
130
- const resolved = which !== undefined && which.exitCode === 0 ? which.stdout.trim().split('\n')[0] : undefined;
131
- const executable = resolved !== undefined && resolved.length > 0 ? resolved : undefined;
153
+ }
154
+ /** Executable search path: the inherited PATH first, then platform fallbacks. */
155
+ function executableSearchDirs() {
156
+ const fromEnv = (process.env.PATH ?? '').split(delimiter).filter((dir) => dir.length > 0);
157
+ return [...new Set([...fromEnv, ...texBinFallbackDirs(), ...condaBinFallbackDirs()])];
158
+ }
159
+ /**
160
+ * Search path for the SageMath probe only. `sage` is normally installed as a
161
+ * *named* conda environment (`conda create -n sage sage=10.9`), so the base-env
162
+ * directories above are not where it lives; this adds `<root>/envs/<name>/bin`
163
+ * for each known distribution root. Kept separate from the generic search path
164
+ * so TeX and other lookups do not start probing unrelated environment trees.
165
+ */
166
+ export function sageSearchDirs() {
167
+ const dirs = [...executableSearchDirs()];
168
+ for (const root of condaRoots()) {
169
+ const envsDir = join(root, 'envs');
170
+ let names;
171
+ try {
172
+ names = readdirSync(envsDir).sort((left, right) => left.localeCompare(right));
173
+ }
174
+ catch {
175
+ continue;
176
+ }
177
+ for (const name of names)
178
+ dirs.push(join(envsDir, name, 'bin'));
179
+ }
180
+ return [...new Set(dirs)];
181
+ }
182
+ /**
183
+ * Resolve the `sage` executable: an explicit `VERYMATH_SAGE` path wins, then the
184
+ * SageMath search path (PATH, TeX/conda base dirs, named conda environments).
185
+ * An override that is not executable is ignored rather than reported as found.
186
+ */
187
+ export function resolveSageExecutable() {
188
+ const override = process.env.VERYMATH_SAGE;
189
+ if (override !== undefined && override.trim().length > 0) {
190
+ const resolved = resolveExecutable(override.trim(), []);
191
+ if (resolved !== undefined)
192
+ return resolved;
193
+ }
194
+ return resolveExecutable('sage', sageSearchDirs());
195
+ }
196
+ /** Whether `candidate` exists and the current user may execute it. */
197
+ function isExecutableFile(candidate) {
198
+ try {
199
+ accessSync(candidate, constants.X_OK);
200
+ return true;
201
+ }
202
+ catch {
203
+ return false;
204
+ }
205
+ }
206
+ /**
207
+ * Resolve an executable name to an absolute path. Resolving in-process avoids
208
+ * `which`/`where`, which are not both available and which cannot see the TeX
209
+ * fallback directories above. On Windows the `PATHEXT` suffixes are tried.
210
+ * @param name - bare executable name, or a path containing a separator.
211
+ * @param searchDirs - directories probed for a bare name (defaults to PATH plus fallbacks).
212
+ * @returns the resolved absolute path, or undefined when nothing is executable.
213
+ */
214
+ export function resolveExecutable(name, searchDirs = executableSearchDirs()) {
215
+ if (isAbsolute(name) || name.includes('/') || name.includes('\\')) {
216
+ return isExecutableFile(name) ? name : undefined;
217
+ }
218
+ const extensions = process.platform === 'win32'
219
+ ? ['', ...(process.env.PATHEXT ?? '.COM;.EXE;.BAT;.CMD').split(';').filter((ext) => ext.length > 0)]
220
+ : [''];
221
+ for (const dir of searchDirs) {
222
+ for (const extension of extensions) {
223
+ const candidate = join(dir, name + extension);
224
+ if (isExecutableFile(candidate))
225
+ return candidate;
226
+ }
227
+ }
228
+ return undefined;
229
+ }
230
+ /**
231
+ * Probe the math-beamer TeX toolchain: latexmk and xelatex binaries (resolved on
232
+ * PATH, then in the distribution's own bin directory, followed by a `--version`
233
+ * smoke) and the forest/ctex LaTeX packages (`kpsewhich <name>.sty`, via the
234
+ * `kpsewhich` found the same way). Nothing is installed, compiled, or
235
+ * downloaded; each probe is independent so a partial toolchain reports per-piece
236
+ * detail (mirrors the osqp/sage probe pattern).
237
+ */
238
+ async function probeBeamerToolchain() {
239
+ const binaries = ['latexmk', 'xelatex'];
240
+ const styles = ['forest', 'ctex'];
241
+ const binaryProbes = await Promise.all(binaries.map(async (name) => {
242
+ const executable = resolveExecutable(name);
132
243
  if (executable === undefined)
133
244
  return { name, kind: 'binary', available: false };
134
245
  const smoke = await probeCommand(executable, ['--version']).catch(() => undefined);
@@ -136,8 +247,13 @@ async function probeBeamerToolchain() {
136
247
  ? { name, kind: 'binary', available: true, executable }
137
248
  : { name, kind: 'binary', available: false, executable };
138
249
  }));
139
- const styleProbes = await Promise.all(styles.map(async ({ name }) => {
140
- const probe = await probeCommand('/Library/TeX/texbin/kpsewhich', [`${name}.sty`]).catch(() => undefined);
250
+ // kpsewhich ships with the distribution, so it lives in the same bin directory
251
+ // as the binaries and needs the same fallback lookup rather than a fixed path.
252
+ const kpsewhich = resolveExecutable('kpsewhich');
253
+ const styleProbes = await Promise.all(styles.map(async (name) => {
254
+ if (kpsewhich === undefined)
255
+ return { name, kind: 'style', available: false };
256
+ const probe = await probeCommand(kpsewhich, [`${name}.sty`]).catch(() => undefined);
141
257
  const resolved = probe !== undefined && probe.exitCode === 0 ? probe.stdout.trim().split('\n')[0] : undefined;
142
258
  return resolved !== undefined && resolved.length > 0
143
259
  ? { name, kind: 'style', available: true, executable: resolved }
@@ -247,7 +363,8 @@ export const apply = (ctx, config = {}) => {
247
363
  render: renderGlossaryBuild,
248
364
  },
249
365
  async execute(args) {
250
- const result = await ctx.verymath.runGlossaryScript(args.script, args.args ?? []);
366
+ const scriptArgs = args.args ?? [];
367
+ const result = await ctx.verymath.runGlossaryScript(args.script, scriptArgs);
251
368
  const output = [result.stderr.trim(), result.stdout.trim()].filter(part => part.length > 0).join('\n');
252
369
  // Upstream contract: exit 3 = partial success (JSON written, Excel pending because
253
370
  // openpyxl is missing — report honestly, never claim full completion); exit 2 = the
@@ -255,15 +372,12 @@ export const apply = (ctx, config = {}) => {
255
372
  if (result.exitCode !== 0 && result.exitCode !== 2 && result.exitCode !== 3) {
256
373
  throw new VeryMathError(`glossary script ${args.script} exited ${result.exitCode}: ${output.slice(0, 2000) || '(no output)'}`, 'VERYMATH_IO');
257
374
  }
258
- // A successful build may have rewritten the glossary on disk; drop stale
259
- // cached entries so follow-up queries observe the new document.
260
- const scriptArgs = args.args ?? [];
261
- const outputFlagIndex = scriptArgs.indexOf('--output');
262
- const outputPath = outputFlagIndex >= 0 ? scriptArgs[outputFlagIndex + 1] : undefined;
263
- if (outputPath !== undefined)
264
- ctx.verymath.invalidateGlossary(outputPath);
265
- else
266
- ctx.verymath.invalidateAllGlossaries();
375
+ // A build/export/backup script may rewrite any glossary file, and it writes
376
+ // wherever its own arguments and cwd say. A targeted invalidation keyed on
377
+ // the raw `--output` argument does not match the resolved absolute cache key
378
+ // and misses duplicated/relative/`--output=x` spellings, so drop the whole
379
+ // cache instead of trying to be clever about which file changed.
380
+ ctx.verymath.invalidateAllGlossaries();
267
381
  return {
268
382
  script: args.script,
269
383
  args: scriptArgs,
@@ -276,7 +390,7 @@ export const apply = (ctx, config = {}) => {
276
390
  }));
277
391
  ctx.tools.register(defineTool({
278
392
  name: 'verymath_glossary_upsert',
279
- description: 'Add or update terms in a VeryMath bilingual glossary JSON document, preserving the contract invariants automatically: term_id derives from the lowercased English term, the document is re-sorted by (en, cn) with contiguous idx, and updated terms get today\'s date stamps. Use this when reading papers or translating and you encounter a term worth saving — do not hand-edit glossary.json. Existing entries are updated when the term_id matches; unspecified optional fields are preserved.',
393
+ description: 'Add terms to or correct terms in a VeryMath bilingual glossary JSON document, preserving the contract invariants automatically: term_id follows the upstream alias convention (lowercased English term, or `<en>__N` for an additional translation of the same term), the document is re-sorted by (en, cn) with contiguous idx, and changed terms get today\'s date stamps. Use this when reading papers or translating and you encounter a term worth saving — do not hand-edit glossary.json. Two different intents are distinguished: (a) omit term_id to ADD — re-adding the same (en, cn) pair is idempotent, and a DIFFERENT Chinese translation for an existing English term becomes a separate alias row (`<en>__N`) instead of overwriting the existing translation; (b) pass term_id (from a previous query) to CORRECT that specific row\'s Chinese translation and optional fields. The English term must match the row\'s English term (case-insensitively): renaming or moving a term to another English term is not supported — add it as a new term instead. Unspecified optional fields are preserved on update.',
280
394
  parameters: {
281
395
  terms: {
282
396
  type: 'array',
@@ -287,6 +401,7 @@ export const apply = (ctx, config = {}) => {
287
401
  properties: {
288
402
  en: { type: 'string', required: true },
289
403
  cn: { type: 'string', required: true },
404
+ term_id: { type: 'string', description: 'Existing term_id to correct in place: sets that row\'s Chinese translation and any optional fields given. The English term must match the row (case-insensitive); renaming is not supported. Omit to add; a different translation for an existing English term is then stored as an alias row instead of overwriting.' },
290
405
  pos: { type: 'string' },
291
406
  field: { type: 'array', items: { type: 'string' } },
292
407
  source: { type: 'string' },
@@ -333,15 +448,13 @@ export const apply = (ctx, config = {}) => {
333
448
  throw new VeryMathError('verymath_glossary_upsert requires the fs service', 'VERYMATH_IO');
334
449
  }
335
450
  const target = await fs.resolve(path, { signal: exec.signal });
336
- // Read the current document if it exists; an absent file starts a new glossary.
337
- let current;
338
- try {
339
- current = await ctx.verymath.loadGlossary(path, exec.signal);
340
- }
341
- catch (error) {
342
- if (!(isVeryMathError(error) && error.code === 'VERYMATH_GLOSSARY_UNAVAILABLE'))
343
- throw error;
344
- }
451
+ // The lock key and the read path must both be the document's canonical
452
+ // identity, not the model-supplied spelling: a relative path, a symlink and
453
+ // `..` segments all name the same file, and locking on the raw string let two
454
+ // concurrent upserts of one document run in parallel. `fs.processPath`
455
+ // returns the host path derived from the resolved target (realpath-based),
456
+ // which is exactly the identity the write below uses.
457
+ const canonicalPath = fs.processPath(target);
345
458
  const requests = (args.terms ?? []).map((request) => {
346
459
  const example = request.example;
347
460
  const validExample = example !== undefined && typeof example.en === 'string' && typeof example.cn === 'string'
@@ -350,23 +463,49 @@ export const apply = (ctx, config = {}) => {
350
463
  return {
351
464
  en: request.en ?? '',
352
465
  cn: request.cn ?? '',
466
+ ...(request.term_id !== undefined ? { term_id: request.term_id } : {}),
353
467
  ...(request.pos !== undefined ? { pos: request.pos } : {}),
354
468
  ...(request.field !== undefined ? { field: request.field } : {}),
355
469
  ...(request.source !== undefined ? { source: request.source } : {}),
356
470
  ...(validExample !== undefined ? { example: validExample } : {}),
357
471
  };
358
472
  });
359
- const result = upsertTerms(current?.terms ?? [], requests);
360
- // Write through ctx.fs so the session sandbox policy governs the write.
361
- const sandboxPolicy = ctx.get('sandboxPolicy')?.resolve(exec.agent !== undefined ? { session: exec.agent.session } : {});
362
- await fs.writeText(target, JSON.stringify(result.document, null, 2) + '\n', undefined, exec.signal, sandboxPolicy);
363
- ctx.verymath.invalidateGlossary(path);
364
- return {
365
- glossary: path,
366
- added: [...result.added],
367
- updated: [...result.updated],
368
- totalTerms: result.document.length,
369
- };
473
+ // Whole read-modify-write inside one per-document lock: concurrent upserts on
474
+ // the same file would otherwise both start from the same snapshot and the
475
+ // later write would drop the earlier one. Scope: this runtime only — an
476
+ // external editor, a Python script or another DSH process does not take it.
477
+ return ctx.verymath.withGlossaryWrite(canonicalPath, async () => {
478
+ // Read the document from disk, not from the query cache: the cache is
479
+ // only invalidated by this package's own writes, so a document edited by
480
+ // the user (or by the bundled glossary_web.py) would be overwritten from
481
+ // a stale snapshot. Only a genuinely absent file starts a new glossary —
482
+ // a permission, I/O or cancellation failure must surface instead of
483
+ // turning this write into "replace the file with just these terms".
484
+ let current;
485
+ try {
486
+ current = await ctx.verymath.reloadGlossary(canonicalPath, exec.signal);
487
+ }
488
+ catch (error) {
489
+ if (!(isVeryMathError(error) && error.code === 'VERYMATH_GLOSSARY_UNAVAILABLE'))
490
+ throw error;
491
+ }
492
+ const result = upsertTerms(current?.terms ?? [], requests);
493
+ // Write through ctx.fs so the session sandbox policy governs the write.
494
+ const sandboxPolicy = ctx.get('sandboxPolicy')?.resolve(exec.agent !== undefined ? { session: exec.agent.session } : {});
495
+ await fs.writeText(target, JSON.stringify(result.document, null, 2) + '\n', undefined, exec.signal, sandboxPolicy);
496
+ // Queries cache by the path string they were given, and one document can be
497
+ // reached through several strings (relative, absolute, symlink alias).
498
+ // Dropping only the keys this call happens to know about leaves an earlier
499
+ // alias entry serving the old document indefinitely, so clear the lot — the
500
+ // cache holds a handful of documents and an upsert is a deliberate write.
501
+ ctx.verymath.invalidateAllGlossaries();
502
+ return {
503
+ glossary: path,
504
+ added: [...result.added],
505
+ updated: [...result.updated],
506
+ totalTerms: result.document.length,
507
+ };
508
+ });
370
509
  },
371
510
  }));
372
511
  ctx.tools.register(defineTool({
@@ -617,7 +756,7 @@ export const apply = (ctx, config = {}) => {
617
756
  }));
618
757
  ctx.tools.register(defineTool({
619
758
  name: 'verymath_sage_check',
620
- description: 'Check SageMath availability (the sage binary / SAGE_PYTHON / conda env chain) AND the local SageMath documentation corpus (default ~/.verymath/sagemath-corpus, set VERYMATH_SAGE_CORPUS to override). SageMath itself must be installed by the user (conda-forge sage=10.9 recommended; Windows requires WSL). The corpus is SageMath official documentation (CC BY-SA 3.0), distributed separately from this MIT package.',
759
+ description: 'Check SageMath availability (the `sage` binary, resolved from `VERYMATH_SAGE` when set, then PATH, then the supported conda roots including named environments such as the `~/.verymath/miniforge/envs/<name>/bin` layout this package documents) AND the local SageMath documentation corpus (default ~/.verymath/sagemath-corpus, set VERYMATH_SAGE_CORPUS to override). SageMath itself must be installed by the user (conda-forge sage=10.9 recommended; Windows requires WSL). The corpus is SageMath official documentation (CC BY-SA 3.0), distributed separately from this MIT package.',
621
760
  parameters: {},
622
761
  output: {
623
762
  schema: {
@@ -643,12 +782,15 @@ export const apply = (ctx, config = {}) => {
643
782
  },
644
783
  },
645
784
  async execute() {
646
- const sageBinaryAvailable = await new Promise((resolvePromise) => {
647
- const probe = spawn('sage', ['--version'], { stdio: 'ignore' });
648
- probe.on('error', () => resolvePromise(false));
649
- probe.on('close', (code) => resolvePromise(code === 0));
650
- setTimeout(() => { probe.kill(); resolvePromise(false); }, 5_000);
651
- });
785
+ // Resolved through the same in-process PATH scan as the TeX probe: a bare
786
+ // `spawn('sage')` missed conda installs whenever the host app did not
787
+ // inherit the login shell PATH, and reported SageMath missing on a machine
788
+ // that has it.
789
+ const sageExecutable = resolveSageExecutable();
790
+ const smoke = sageExecutable === undefined
791
+ ? undefined
792
+ : await probeCommand(sageExecutable, ['--version'], 10_000).catch(() => undefined);
793
+ const sageBinaryAvailable = smoke !== undefined && smoke.exitCode === 0;
652
794
  try {
653
795
  const root = await resolveCorpusRoot();
654
796
  const rows = await loadManifest(root);
@@ -1027,18 +1169,20 @@ export const apply = (ctx, config = {}) => {
1027
1169
  throw new VeryMathError('verymath_paper_graph requires the fs service', 'VERYMATH_IO');
1028
1170
  }
1029
1171
  const cwd = exec.agent?.session.header.cwd;
1030
- const documents = await Promise.all(paths.map(async (path) => {
1172
+ const parsedDocuments = await Promise.all(paths.map(async (path) => {
1031
1173
  const absolute = toWorkspacePath(path, cwd);
1032
1174
  const raw = await fs.readText(await fs.resolve(absolute, { signal: exec.signal }), exec.signal);
1033
- let parsed;
1034
1175
  try {
1035
- parsed = JSON.parse(raw);
1176
+ return JSON.parse(raw);
1036
1177
  }
1037
1178
  catch (error) {
1038
1179
  throw new VeryMathError(`paper structure at ${absolute} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`, 'VERYMATH_PAPER_INVALID', { cause: error });
1039
1180
  }
1040
- return parsePaperStructure(parsed);
1041
1181
  }));
1182
+ // Batch artifacts are validated as a group: a later batch may legitimately
1183
+ // depend on a label an earlier batch defined, so per-file dependency checks
1184
+ // rejected the upstream batch protocol before the merge could run.
1185
+ const documents = parsePaperBatch(parsedDocuments);
1042
1186
  const primary = documents[0];
1043
1187
  if (primary === undefined) {
1044
1188
  throw new VeryMathError('no structure artifact paths resolved', 'VERYMATH_PAPER_INVALID');
@@ -1048,8 +1192,10 @@ export const apply = (ctx, config = {}) => {
1048
1192
  const topology = computeTopology(input);
1049
1193
  const focus = args.focus !== undefined ? focusClosure(input, args.focus) : undefined;
1050
1194
  const shouldRender = args.render ?? true;
1051
- const mermaid = shouldRender && primary !== undefined
1052
- ? renderMermaid(primary, { ...(args.forceFull === true ? { forceFull: true } : {}) })
1195
+ // Render the merged structure, not the first artifact: with batches, the
1196
+ // graph silently showed only batch one while the counts described all of them.
1197
+ const mermaid = shouldRender
1198
+ ? renderMermaid(mergeStructures(input), { ...(args.forceFull === true ? { forceFull: true } : {}) })
1053
1199
  : undefined;
1054
1200
  return {
1055
1201
  title: primary.paper.title,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@louisultra/dsh-verymath",
3
- "version": "0.3.2",
3
+ "version": "0.3.4",
4
4
  "description": "VeryMath capabilities for DSH: 16 bundled math skills and 14 tools covering paper reading, bilingual glossary, writing, Beamer, optimization, computation, Lean formalization, research workflows, Sage doc lookup and MATLAB. Community plugin for issue ECNU/EduWork#152.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -25,7 +25,9 @@
25
25
  "LICENSE",
26
26
  "NOTICE.md",
27
27
  "UPSTREAM.json",
28
- "CHANGELOG.md"
28
+ "CHANGELOG.md",
29
+ "!**/tests",
30
+ "!**/test"
29
31
  ],
30
32
  "dsh": {
31
33
  "bundle": {
@@ -38,34 +40,33 @@
38
40
  "test": "vitest run",
39
41
  "test:runtime": "node scripts/probe-runtime.mjs",
40
42
  "check": "npm run typecheck && npm run build && npm test && npm run test:runtime",
41
- "test:upstream": "python3 -m unittest discover -s ../research/AI4Math-MathTool/skills/math-glossary/tests"
43
+ "test:upstream": "python3 -m unittest discover -s ../../research/AI4Math-MathTool/skills/math-glossary/tests"
42
44
  },
43
45
  "engines": {
44
- "node": ">=24.18.0"
46
+ "node": ">=24.22.1"
45
47
  },
46
48
  "peerDependencies": {
47
- "@deepseek-ai/cordis": "^4.0.4",
48
- "@deepseek-ai/dsh-fs": ">=0.2.0-rc.1 <0.3.0-0",
49
- "@deepseek-ai/dsh-llm": ">=0.2.0-rc.1 <0.3.0-0",
50
- "@deepseek-ai/dsh-skill": ">=0.2.0-rc.1 <0.3.0-0",
51
- "@deepseek-ai/dsh-tools": ">=0.2.0-rc.1 <0.3.0-0",
52
- "@deepseek-ai/schemastery": "^3.18.4"
49
+ "@deepseek-ai/cordis": ">=4.0.5 <4.2.0",
50
+ "@deepseek-ai/dsh-fs": ">=0.2.1-rc.5 <0.3.0-0 || 0.2.2-rc.1",
51
+ "@deepseek-ai/dsh-llm": ">=0.2.1-rc.5 <0.3.0-0 || 0.2.2-rc.1",
52
+ "@deepseek-ai/dsh-skill": ">=0.2.1-rc.5 <0.3.0-0 || 0.2.2-rc.1",
53
+ "@deepseek-ai/dsh-tools": ">=0.2.1-rc.5 <0.3.0-0 || 0.2.2-rc.1",
54
+ "@deepseek-ai/schemastery": ">=3.18.5 <3.19.0 || 3.19.0"
53
55
  },
54
56
  "devDependencies": {
55
- "@deepseek-ai/cordis": "4.0.4",
56
- "@deepseek-ai/cordis-plugin-include": "1.0.9",
57
- "@deepseek-ai/cordis-plugin-loader": "1.0.5",
58
- "@deepseek-ai/dsh-fs": "0.2.0-rc.2",
59
- "@deepseek-ai/dsh-fs-local": "0.2.0-rc.2",
60
- "@deepseek-ai/dsh-llm": "0.2.0-rc.2",
61
- "@deepseek-ai/dsh-skill": "0.2.0-rc.2",
62
- "@deepseek-ai/dsh-system-prompt": "0.2.0-rc.2",
63
- "@deepseek-ai/dsh-tools": "0.2.0-rc.2",
64
- "@deepseek-ai/schemastery": "3.18.4",
65
- "@types/js-yaml": "^4.0.9",
66
- "@types/node": "^24.19.2",
67
- "typescript": "^6.0.3",
68
- "vitest": "^4.1.8"
57
+ "@deepseek-ai/cordis": "4.1.0",
58
+ "@deepseek-ai/dsh-fs": "0.2.2-rc.1",
59
+ "@deepseek-ai/dsh-fs-local": "0.2.2-rc.1",
60
+ "@deepseek-ai/dsh-llm": "0.2.2-rc.1",
61
+ "@deepseek-ai/dsh-skill": "0.2.2-rc.1",
62
+ "@deepseek-ai/dsh-system-prompt": "0.2.2-rc.1",
63
+ "@deepseek-ai/dsh-tool-executor-native": "0.2.2-rc.1",
64
+ "@deepseek-ai/dsh-tools": "0.2.2-rc.1",
65
+ "@deepseek-ai/schemastery": "3.19.0",
66
+ "@types/js-yaml": "4.0.9",
67
+ "@types/node": "24.19.2",
68
+ "typescript": "6.0.3",
69
+ "vitest": "4.1.8"
69
70
  },
70
71
  "keywords": [
71
72
  "dsh",
@@ -28,6 +28,7 @@ description: "术语库构建与管理 skill。当用户需要从专业词汇文
28
28
  3. **`glossary_web.py`(Flask Web 管理界面)是长驻服务**,不通过 `verymath_glossary_build` 运行;仅在用户明确要求时用 shell 启动,并遵守下文 loopback 安全边界。
29
29
  4. 本 skill 目录即脚本根目录(`scripts/`、`references/` 相对于本 SKILL.md 解析);把产物写到用户工作区(如 `glossary/glossary.json`),不要写回 skill 目录。
30
30
  5. 翻译 agent 查词约定、冲突裁决、备份与日志规范见下文原流程,行为不变。
31
+ 6. **新增别名的与纠正译名的区分**:同一英文术语已有译名、现在要再加一种译法(多义/不同子领域)时,**不要带 `term_id`**——工具会新增 `en__N` 别名行,原有译名保留。要改掉已有译名时,**先 `verymath_glossary_query` 查到该行的 `term_id`,再带 `term_id` 提交**;未知 `term_id`、英文不匹配、或会把两行变成同一 `(en, cn)` 的请求会被拒绝,不会写盘。
31
32
 
32
33
  ## 数据模型
33
34