@louisultra/dsh-verymath 0.3.3 → 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.
@@ -17,6 +17,20 @@ 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;
20
34
  /**
21
35
  * Resolve an executable name to an absolute path. Resolving in-process avoids
22
36
  * `which`/`where`, which are not both available and which cannot see the TeX
package/lib/tool/index.js CHANGED
@@ -1,10 +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 { accessSync, constants } from 'node:fs';
4
+ import { accessSync, constants, readdirSync } from 'node:fs';
5
+ import { homedir } from 'node:os';
5
6
  import { delimiter, isAbsolute, join, resolve } from 'node:path';
6
7
  import { VeryMathError, isVeryMathError } from '@louisultra/dsh-verymath/core';
7
- 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';
8
9
  export const name = 'tool-verymath';
9
10
  export const inject = ['tools', 'verymath', 'fs'];
10
11
  export const Config = z.object({
@@ -96,16 +97,22 @@ function probeCommand(executable, args, timeoutMs = 5_000) {
96
97
  }
97
98
  const stdout = [];
98
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;
99
104
  const settle = (value) => {
100
105
  if (!settled) {
101
106
  settled = true;
107
+ if (timer !== undefined)
108
+ clearTimeout(timer);
102
109
  resolvePromise(value);
103
110
  }
104
111
  };
105
112
  child.stdout?.on('data', (chunk) => stdout.push(chunk));
106
113
  child.on('error', () => settle(undefined));
107
114
  child.on('close', (code) => settle({ exitCode: code ?? -1, stdout: Buffer.concat(stdout).toString() }));
108
- setTimeout(() => {
115
+ timer = setTimeout(() => {
109
116
  child.kill();
110
117
  settle(undefined);
111
118
  }, timeoutMs);
@@ -121,10 +128,70 @@ function probeCommand(executable, args, timeoutMs = 5_000) {
121
128
  function texBinFallbackDirs() {
122
129
  return process.platform === 'darwin' ? ['/Library/TeX/texbin'] : [];
123
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'),
152
+ ];
153
+ }
124
154
  /** Executable search path: the inherited PATH first, then platform fallbacks. */
125
155
  function executableSearchDirs() {
126
156
  const fromEnv = (process.env.PATH ?? '').split(delimiter).filter((dir) => dir.length > 0);
127
- return [...new Set([...fromEnv, ...texBinFallbackDirs()])];
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());
128
195
  }
129
196
  /** Whether `candidate` exists and the current user may execute it. */
130
197
  function isExecutableFile(candidate) {
@@ -296,7 +363,8 @@ export const apply = (ctx, config = {}) => {
296
363
  render: renderGlossaryBuild,
297
364
  },
298
365
  async execute(args) {
299
- 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);
300
368
  const output = [result.stderr.trim(), result.stdout.trim()].filter(part => part.length > 0).join('\n');
301
369
  // Upstream contract: exit 3 = partial success (JSON written, Excel pending because
302
370
  // openpyxl is missing — report honestly, never claim full completion); exit 2 = the
@@ -304,15 +372,12 @@ export const apply = (ctx, config = {}) => {
304
372
  if (result.exitCode !== 0 && result.exitCode !== 2 && result.exitCode !== 3) {
305
373
  throw new VeryMathError(`glossary script ${args.script} exited ${result.exitCode}: ${output.slice(0, 2000) || '(no output)'}`, 'VERYMATH_IO');
306
374
  }
307
- // A successful build may have rewritten the glossary on disk; drop stale
308
- // cached entries so follow-up queries observe the new document.
309
- const scriptArgs = args.args ?? [];
310
- const outputFlagIndex = scriptArgs.indexOf('--output');
311
- const outputPath = outputFlagIndex >= 0 ? scriptArgs[outputFlagIndex + 1] : undefined;
312
- if (outputPath !== undefined)
313
- ctx.verymath.invalidateGlossary(outputPath);
314
- else
315
- 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();
316
381
  return {
317
382
  script: args.script,
318
383
  args: scriptArgs,
@@ -325,7 +390,7 @@ export const apply = (ctx, config = {}) => {
325
390
  }));
326
391
  ctx.tools.register(defineTool({
327
392
  name: 'verymath_glossary_upsert',
328
- 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.',
329
394
  parameters: {
330
395
  terms: {
331
396
  type: 'array',
@@ -336,6 +401,7 @@ export const apply = (ctx, config = {}) => {
336
401
  properties: {
337
402
  en: { type: 'string', required: true },
338
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.' },
339
405
  pos: { type: 'string' },
340
406
  field: { type: 'array', items: { type: 'string' } },
341
407
  source: { type: 'string' },
@@ -382,15 +448,13 @@ export const apply = (ctx, config = {}) => {
382
448
  throw new VeryMathError('verymath_glossary_upsert requires the fs service', 'VERYMATH_IO');
383
449
  }
384
450
  const target = await fs.resolve(path, { signal: exec.signal });
385
- // Read the current document if it exists; an absent file starts a new glossary.
386
- let current;
387
- try {
388
- current = await ctx.verymath.loadGlossary(path, exec.signal);
389
- }
390
- catch (error) {
391
- if (!(isVeryMathError(error) && error.code === 'VERYMATH_GLOSSARY_UNAVAILABLE'))
392
- throw error;
393
- }
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);
394
458
  const requests = (args.terms ?? []).map((request) => {
395
459
  const example = request.example;
396
460
  const validExample = example !== undefined && typeof example.en === 'string' && typeof example.cn === 'string'
@@ -399,23 +463,49 @@ export const apply = (ctx, config = {}) => {
399
463
  return {
400
464
  en: request.en ?? '',
401
465
  cn: request.cn ?? '',
466
+ ...(request.term_id !== undefined ? { term_id: request.term_id } : {}),
402
467
  ...(request.pos !== undefined ? { pos: request.pos } : {}),
403
468
  ...(request.field !== undefined ? { field: request.field } : {}),
404
469
  ...(request.source !== undefined ? { source: request.source } : {}),
405
470
  ...(validExample !== undefined ? { example: validExample } : {}),
406
471
  };
407
472
  });
408
- const result = upsertTerms(current?.terms ?? [], requests);
409
- // Write through ctx.fs so the session sandbox policy governs the write.
410
- const sandboxPolicy = ctx.get('sandboxPolicy')?.resolve(exec.agent !== undefined ? { session: exec.agent.session } : {});
411
- await fs.writeText(target, JSON.stringify(result.document, null, 2) + '\n', undefined, exec.signal, sandboxPolicy);
412
- ctx.verymath.invalidateGlossary(path);
413
- return {
414
- glossary: path,
415
- added: [...result.added],
416
- updated: [...result.updated],
417
- totalTerms: result.document.length,
418
- };
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
+ });
419
509
  },
420
510
  }));
421
511
  ctx.tools.register(defineTool({
@@ -666,7 +756,7 @@ export const apply = (ctx, config = {}) => {
666
756
  }));
667
757
  ctx.tools.register(defineTool({
668
758
  name: 'verymath_sage_check',
669
- 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.',
670
760
  parameters: {},
671
761
  output: {
672
762
  schema: {
@@ -692,12 +782,15 @@ export const apply = (ctx, config = {}) => {
692
782
  },
693
783
  },
694
784
  async execute() {
695
- const sageBinaryAvailable = await new Promise((resolvePromise) => {
696
- const probe = spawn('sage', ['--version'], { stdio: 'ignore' });
697
- probe.on('error', () => resolvePromise(false));
698
- probe.on('close', (code) => resolvePromise(code === 0));
699
- setTimeout(() => { probe.kill(); resolvePromise(false); }, 5_000);
700
- });
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;
701
794
  try {
702
795
  const root = await resolveCorpusRoot();
703
796
  const rows = await loadManifest(root);
@@ -1076,18 +1169,20 @@ export const apply = (ctx, config = {}) => {
1076
1169
  throw new VeryMathError('verymath_paper_graph requires the fs service', 'VERYMATH_IO');
1077
1170
  }
1078
1171
  const cwd = exec.agent?.session.header.cwd;
1079
- const documents = await Promise.all(paths.map(async (path) => {
1172
+ const parsedDocuments = await Promise.all(paths.map(async (path) => {
1080
1173
  const absolute = toWorkspacePath(path, cwd);
1081
1174
  const raw = await fs.readText(await fs.resolve(absolute, { signal: exec.signal }), exec.signal);
1082
- let parsed;
1083
1175
  try {
1084
- parsed = JSON.parse(raw);
1176
+ return JSON.parse(raw);
1085
1177
  }
1086
1178
  catch (error) {
1087
1179
  throw new VeryMathError(`paper structure at ${absolute} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`, 'VERYMATH_PAPER_INVALID', { cause: error });
1088
1180
  }
1089
- return parsePaperStructure(parsed);
1090
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);
1091
1186
  const primary = documents[0];
1092
1187
  if (primary === undefined) {
1093
1188
  throw new VeryMathError('no structure artifact paths resolved', 'VERYMATH_PAPER_INVALID');
@@ -1097,8 +1192,10 @@ export const apply = (ctx, config = {}) => {
1097
1192
  const topology = computeTopology(input);
1098
1193
  const focus = args.focus !== undefined ? focusClosure(input, args.focus) : undefined;
1099
1194
  const shouldRender = args.render ?? true;
1100
- const mermaid = shouldRender && primary !== undefined
1101
- ? 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 } : {}) })
1102
1199
  : undefined;
1103
1200
  return {
1104
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.3",
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",
@@ -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