@louisultra/dsh-verymath 0.3.3 → 0.4.0

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.
@@ -145,10 +145,15 @@ export function queryGlossary(terms, query, options = {}) {
145
145
  hits.push({ term, matchedBy });
146
146
  };
147
147
  for (const term of candidates) {
148
- if (term.en.toLowerCase() === lower || term.cn === needle)
148
+ // An exact Chinese hit is a Chinese match, not an English one: labelling it
149
+ // `en` made the hit contradict the query the caller sent (querying 流形
150
+ // returned matchedBy 'en').
151
+ if (term.en.toLowerCase() === lower)
149
152
  push(term, 'en');
150
153
  else if (term.term_id.toLowerCase() === lower)
151
154
  push(term, 'term_id');
155
+ else if (term.cn === needle)
156
+ push(term, 'cn');
152
157
  }
153
158
  for (const term of candidates) {
154
159
  if (term.en.toLowerCase().startsWith(lower))
@@ -177,54 +182,113 @@ function keepOr(request, existing) {
177
182
  return request !== undefined ? request : existing;
178
183
  }
179
184
  /**
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
+ * Merge upsert requests into an existing glossary per the upstream contract.
186
+ *
187
+ * Identity is resolved in this order, which is also what the tool description
188
+ * tells the model:
189
+ *
190
+ * 1. An explicit `term_id` selects that row (the correction path). It must
191
+ * exist, and its `en` must match the request's `en` case-insensitively:
192
+ * this function never renames a term or moves a row to another English term.
193
+ * 2. Otherwise the exact `(en case-insensitive, cn exact)` pair selects the row
194
+ * that already holds that translation, so re-adding a term is idempotent. If
195
+ * several rows hold that pair the request is rejected as ambiguous rather
196
+ * than silently picking one.
197
+ * 3. Otherwise a new row is created. Its id continues the upstream alias
198
+ * sequence for that English term (the lowercased `en`, then `en__1`, …) and
199
+ * skips ids any other row already uses. This is what keeps two translations
200
+ * of the same English term as two rows, as `glossary-schema.md` requires,
201
+ * instead of overwriting the existing translation.
202
+ *
203
+ * The merged document is re-sorted by `(en, cn)` with contiguous `idx`, and the
204
+ * input document is never mutated. Every request is validated by the same
205
+ * rules, so a batch either applies completely or throws.
206
+ *
207
+ * `en` comparison uses `toLowerCase()`, matching how ids are derived; upstream
208
+ * Python uses `casefold()`, so exotic multi-character foldings (e.g. `ß` → `ss`)
209
+ * are not treated as equal here. Glossaries are built from one or the other
210
+ * path, and within a single path the comparison is self-consistent.
211
+ *
185
212
  * @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.
213
+ * @param upserts - terms to add or correct.
214
+ * @throws VeryMathError when the input document already breaks an invariant,
215
+ * when a request names an unknown or blank `term_id`, when the `term_id`
216
+ * belongs to a different English term, when an address is ambiguous, or when
217
+ * a correction would duplicate another row's `(en, cn)` pair.
188
218
  */
189
219
  export function upsertTerms(terms, upserts) {
190
220
  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
- }
221
+ if (!UPSERT_DATE.test(today)) {
222
+ throw new VeryMathError('system date is not ISO; refusing to stamp terms', 'VERYMATH_GLOSSARY_INVALID');
195
223
  }
224
+ // Validate before indexing: building the Map first silently drops a row when
225
+ // the input carries a duplicate term_id, which then makes the closing
226
+ // invariant check unable to see the loss it was supposed to report.
227
+ validateGlossaryInvariants(terms);
196
228
  const byId = new Map(terms.map(term => [term.term_id, { ...term }]));
229
+ // Exact (en case-insensitive, cn exact) -> term_ids carrying that translation.
230
+ // A list, not a single id: a document can legally hold the same pair twice, and
231
+ // that has to be reported as ambiguous instead of resolved by luck.
232
+ const pairIndex = new Map();
233
+ const indexPair = (term) => {
234
+ const key = pairKey(term.en, term.cn);
235
+ const ids = pairIndex.get(key);
236
+ if (ids === undefined)
237
+ pairIndex.set(key, [term.term_id]);
238
+ else
239
+ ids.push(term.term_id);
240
+ };
241
+ for (const term of byId.values())
242
+ indexPair(term);
197
243
  const added = [];
198
244
  const updated = [];
245
+ // A row created by this batch and then touched again by a later request in the
246
+ // same batch is reported as added only: it did not exist before, so counting it
247
+ // as updated too would make one row look like two changes.
248
+ const recordUpdate = (termId) => {
249
+ if (added.includes(termId))
250
+ return;
251
+ if (!updated.includes(termId))
252
+ updated.push(termId);
253
+ };
199
254
  for (const request of upserts) {
200
255
  const en = request.en.trim();
201
256
  const cn = request.cn.trim();
202
257
  if (en.length === 0 || cn.length === 0) {
203
258
  throw new VeryMathError('upsert requires non-empty en and cn', 'VERYMATH_GLOSSARY_INVALID');
204
259
  }
205
- const termId = en.toLowerCase();
206
- const existing = byId.get(termId);
260
+ const enKey = en.toLowerCase();
207
261
  const field = request.field !== undefined && request.field.length > 0 ? [...request.field] : undefined;
208
262
  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);
263
+ const key = pairKey(en, cn);
264
+ let termId;
265
+ if (request.term_id !== undefined) {
266
+ // A blank id is a malformed request, not "no id": silently adding would
267
+ // hide the caller's mistake and produce the very overwrite this exists to
268
+ // prevent.
269
+ if (request.term_id.trim().length === 0) {
270
+ throw new VeryMathError('upsert term_id must not be blank; omit term_id to add a translation', 'VERYMATH_GLOSSARY_INVALID');
271
+ }
272
+ const target = byId.get(request.term_id);
273
+ if (target === undefined) {
274
+ throw new VeryMathError(`upsert: no term with term_id ${JSON.stringify(request.term_id)}; query the glossary for the id, or omit term_id to add the translation`, 'VERYMATH_GLOSSARY_INVALID');
275
+ }
276
+ if (target.en.toLowerCase() !== enKey) {
277
+ throw new VeryMathError(`upsert: term_id ${JSON.stringify(request.term_id)} is the English term ${JSON.stringify(target.en)}, not ${JSON.stringify(en)}; renaming or moving a term is not supported — add the new term instead`, 'VERYMATH_GLOSSARY_INVALID');
278
+ }
279
+ termId = target.term_id;
224
280
  }
225
281
  else {
226
- byId.set(termId, {
227
- term_id: termId,
282
+ const candidates = pairIndex.get(key) ?? [];
283
+ if (candidates.length > 1) {
284
+ throw new VeryMathError(`upsert: ${JSON.stringify(en)} already has ${candidates.length} rows with the translation ${JSON.stringify(cn)} (${candidates.join(', ')}); pass term_id to choose one`, 'VERYMATH_GLOSSARY_INVALID');
285
+ }
286
+ termId = candidates[0];
287
+ }
288
+ if (termId === undefined) {
289
+ const newId = nextTermId(byId, en);
290
+ const created = {
291
+ term_id: newId,
228
292
  en,
229
293
  cn,
230
294
  ...(request.pos !== undefined ? { pos: request.pos } : {}),
@@ -233,11 +297,130 @@ export function upsertTerms(terms, upserts) {
233
297
  ...(examples !== undefined ? { examples } : {}),
234
298
  created_at: today,
235
299
  updated_at: today,
236
- });
237
- added.push(termId);
300
+ };
301
+ byId.set(newId, created);
302
+ indexPair(created);
303
+ added.push(newId);
304
+ continue;
305
+ }
306
+ const existing = byId.get(termId);
307
+ if (existing === undefined)
308
+ continue;
309
+ const previousKey = pairKey(existing.en, existing.cn);
310
+ if (previousKey !== key) {
311
+ // Re-point the pair index, but never let two rows end up with one pair.
312
+ const owner = (pairIndex.get(key) ?? []).find(id => id !== termId);
313
+ if (owner !== undefined) {
314
+ throw new VeryMathError(`upsert: ${JSON.stringify(en)} / ${JSON.stringify(cn)} is already held by ${owner}; pass that term_id instead of rewriting ${termId}`, 'VERYMATH_GLOSSARY_INVALID');
315
+ }
316
+ const previous = pairIndex.get(previousKey);
317
+ if (previous !== undefined) {
318
+ const remaining = previous.filter(id => id !== termId);
319
+ if (remaining.length === 0)
320
+ pairIndex.delete(previousKey);
321
+ else
322
+ pairIndex.set(previousKey, remaining);
323
+ }
324
+ indexPair({ ...existing, cn });
238
325
  }
326
+ const pos = keepOr(request.pos, existing.pos);
327
+ const mergedField = keepOr(field, existing.field);
328
+ const source = keepOr(request.source, existing.source);
329
+ const mergedExamples = keepOr(examples, existing.examples);
330
+ byId.set(termId, {
331
+ ...existing,
332
+ // `en` is deliberately not rewritten: a correction fixes the translation,
333
+ // and the stored spelling of the source term is not this function's to
334
+ // change.
335
+ cn,
336
+ ...(pos !== undefined ? { pos } : {}),
337
+ ...(mergedField !== undefined ? { field: mergedField } : {}),
338
+ ...(source !== undefined ? { source } : {}),
339
+ ...(mergedExamples !== undefined ? { examples: mergedExamples } : {}),
340
+ updated_at: today,
341
+ });
342
+ recordUpdate(termId);
239
343
  }
240
344
  const document = sortGlossary([...byId.values()]);
241
345
  validateGlossaryInvariants(document);
242
346
  return { added, updated, document };
243
347
  }
348
+ /**
349
+ * Exact `(en, cn)` identity key. `en` is compared case-insensitively and `cn`
350
+ * exactly; the pair is JSON-encoded rather than joined with a separator because
351
+ * a separator can appear inside either string (JSON permits `\u0000`), which
352
+ * would let two different pairs share one key and overwrite each other.
353
+ */
354
+ function pairKey(en, cn) {
355
+ return JSON.stringify([en.toLowerCase(), cn]);
356
+ }
357
+ /**
358
+ * Longest numeric suffix this allocator will parse or emit. Real alias ids are
359
+ * tiny; the bound exists only so a corrupt or hostile document cannot turn a
360
+ * decimal parse into an expensive BigInt conversion. Parsing and emitting share
361
+ * the bound on purpose — a generated id the parser later refuses to read back
362
+ * would be invisible to the next allocation.
363
+ */
364
+ const MAX_SUFFIX_DIGITS = 64;
365
+ /**
366
+ * Allocate the alias-aware `term_id` for a new row, mirroring upstream
367
+ * `glossary_build.py`: continue from the highest suffix already observed for
368
+ * this English term rather than filling historical gaps.
369
+ *
370
+ * Upstream does not restart the search at the bare id: it reads an existing
371
+ * explicit `group__1` as "this group is at index 1" and continues from 2. So a
372
+ * document that kept `group__1` but lost the primary row gets `group__2` next —
373
+ * re-using `group` there would silently hand the "first occurrence" identity to
374
+ * a later translation. Candidates already used by any other row (including a
375
+ * custom id for a different English term) are skipped.
376
+ *
377
+ * The counter is a `BigInt` on purpose. With a `number`, an id such as
378
+ * `group__9007199254740992` makes `occurrence + 1 === occurrence`, so the loop
379
+ * stops advancing and spins forever — and this function is synchronous, so it
380
+ * would hang the host event loop rather than throw.
381
+ * @param byId - current rows, keyed by term_id.
382
+ * @param en - English term of the row being created.
383
+ */
384
+ function nextTermId(byId, en) {
385
+ const base = en.toLowerCase();
386
+ const used = new Set();
387
+ let occurrence = 0n;
388
+ for (const id of byId.keys()) {
389
+ const lowered = id.toLowerCase();
390
+ used.add(lowered);
391
+ if (lowered === base) {
392
+ if (occurrence < 1n)
393
+ occurrence = 1n;
394
+ continue;
395
+ }
396
+ if (!lowered.startsWith(`${base}__`))
397
+ continue;
398
+ const suffix = lowered.slice(base.length + 2);
399
+ // A non-numeric suffix is a custom id (the upstream schema allows those), not
400
+ // part of this English term's alias sequence.
401
+ if (!/^\d+$/.test(suffix))
402
+ continue;
403
+ // A numeric suffix this long cannot be a real counter, and **ignoring** it
404
+ // would hand the next translation the bare id — silently reviving the
405
+ // "first occurrence" identity this rule exists to preserve. Refuse instead of
406
+ // pretending the document has no suffix to continue from.
407
+ if (suffix.length > MAX_SUFFIX_DIGITS) {
408
+ throw new VeryMathError(`term_id ${JSON.stringify(id)} carries a ${suffix.length}-digit numeric suffix; refusing to allocate a further alias id for ${JSON.stringify(en)}`, 'VERYMATH_GLOSSARY_INVALID');
409
+ }
410
+ const next = BigInt(suffix) + 1n;
411
+ if (next > occurrence)
412
+ occurrence = next;
413
+ }
414
+ // Terminates: `occurrence` strictly increases and `used` is finite, so at most
415
+ // |used| candidates can collide.
416
+ for (;;) {
417
+ // Never emit an id the loop above would itself refuse to read back.
418
+ if (occurrence !== 0n && String(occurrence).length > MAX_SUFFIX_DIGITS) {
419
+ throw new VeryMathError(`cannot allocate a further alias id for ${JSON.stringify(en)}: the suffix would exceed ${MAX_SUFFIX_DIGITS} digits`, 'VERYMATH_GLOSSARY_INVALID');
420
+ }
421
+ const candidate = occurrence === 0n ? base : `${base}__${occurrence}`;
422
+ if (!used.has(candidate))
423
+ return candidate;
424
+ occurrence += 1n;
425
+ }
426
+ }
@@ -1,4 +1,4 @@
1
- import type { PaperEntity, PaperStructure } from './paper.ts';
1
+ import type { MainTheorem, PaperEntity, PaperStructure } from './paper.ts';
2
2
  /** A structure artifact may arrive as one file or as multiple batch files. */
3
3
  export type StructureInput = PaperStructure | readonly PaperStructure[];
4
4
  /** Merge report summarizing what the merge changed. */
@@ -62,6 +62,23 @@ export declare function collectEntities(input: StructureInput): {
62
62
  entities: PaperEntity[];
63
63
  duplicates: number;
64
64
  };
65
+ /**
66
+ * Main theorems across one or more batch artifacts, deduped by label (first
67
+ * occurrence wins). Batch merging unions `entities` only, so the metadata the
68
+ * reading directions are rooted at has to be collected explicitly — without
69
+ * this, a batched artifact reported an empty top-down order and no entity
70
+ * supported any main theorem.
71
+ * @param input - one artifact or a list of batch artifacts.
72
+ */
73
+ export declare function collectMainTheorems(input: StructureInput): MainTheorem[];
74
+ /**
75
+ * Fold one or more batch artifacts into a single structure holding every merged
76
+ * entity and every main theorem. `renderMermaid` takes one structure, so without
77
+ * this the rendered graph only ever contained the first batch while the counts
78
+ * came from the merge.
79
+ * @param input - one artifact or a list of batch artifacts.
80
+ */
81
+ export declare function mergeStructures(input: StructureInput): PaperStructure;
65
82
  /**
66
83
  * Merge batch artifacts per the upstream Skill-2 protocol: dedupe by label,
67
84
  * rebuild the reverse index (`cited_by`) from forward `dependencies` and
package/lib/core/graph.js CHANGED
@@ -41,6 +41,41 @@ export function collectEntities(input) {
41
41
  }
42
42
  return { entities: [...unique.values()], duplicates };
43
43
  }
44
+ /**
45
+ * Main theorems across one or more batch artifacts, deduped by label (first
46
+ * occurrence wins). Batch merging unions `entities` only, so the metadata the
47
+ * reading directions are rooted at has to be collected explicitly — without
48
+ * this, a batched artifact reported an empty top-down order and no entity
49
+ * supported any main theorem.
50
+ * @param input - one artifact or a list of batch artifacts.
51
+ */
52
+ export function collectMainTheorems(input) {
53
+ const unique = new Map();
54
+ for (const document of documentsOf(input)) {
55
+ for (const theorem of document.main_theorems ?? []) {
56
+ if (!unique.has(theorem.label))
57
+ unique.set(theorem.label, theorem);
58
+ }
59
+ }
60
+ return [...unique.values()];
61
+ }
62
+ /**
63
+ * Fold one or more batch artifacts into a single structure holding every merged
64
+ * entity and every main theorem. `renderMermaid` takes one structure, so without
65
+ * this the rendered graph only ever contained the first batch while the counts
66
+ * came from the merge.
67
+ * @param input - one artifact or a list of batch artifacts.
68
+ */
69
+ export function mergeStructures(input) {
70
+ const documents = documentsOf(input);
71
+ const primary = documents[0];
72
+ const { entities } = mergeBatches(input);
73
+ return {
74
+ ...(primary ?? { paper: { title: 'Merged structure', authors: [] } }),
75
+ entities,
76
+ main_theorems: collectMainTheorems(input),
77
+ };
78
+ }
44
79
  /**
45
80
  * Merge batch artifacts per the upstream Skill-2 protocol: dedupe by label,
46
81
  * rebuild the reverse index (`cited_by`) from forward `dependencies` and
@@ -134,8 +169,7 @@ function findCycles(labels, edges) {
134
169
  */
135
170
  export function computeTopology(input, mainTheoremLabels) {
136
171
  const { entities } = mergeBatches(input);
137
- const artifact = isSingleStructure(input) ? input : undefined;
138
- const theorems = artifact?.main_theorems ?? [];
172
+ const theorems = collectMainTheorems(input);
139
173
  const theoremLabels = mainTheoremLabels ?? theorems.map(theorem => theorem.label);
140
174
  const byLabel = new Map(entities.map(entity => [entity.label, entity]));
141
175
  const dependenciesOf = (entity) => [
@@ -194,10 +228,14 @@ export function computeTopology(input, mainTheoremLabels) {
194
228
  if (stuck.length > 0)
195
229
  bottomUpLevels.push([...stuck].sort());
196
230
  }
197
- // Top-down BFS from main theorems along dependency edges.
231
+ // Top-down BFS from main theorems along dependency edges. Seeds are taken as
232
+ // given, not filtered by `byLabel`: the compact v4.2 form may record a main
233
+ // theorem only in `main_theorems` with no matching entity, and filtering it out
234
+ // made the top-down direction contradict `focusClosure` (which resolves such a
235
+ // theorem fine). A seed with no entity simply has no forward edges.
198
236
  const topDown = [];
199
237
  const seen = new Set();
200
- const bfsQueue = [...theoremLabels.filter((label) => byLabel.has(label))];
238
+ const bfsQueue = [...theoremLabels];
201
239
  while (bfsQueue.length > 0) {
202
240
  const label = bfsQueue.shift();
203
241
  if (label === undefined || seen.has(label))
@@ -412,8 +450,7 @@ export function requireStructure(value) {
412
450
  */
413
451
  export function focusClosure(input, label) {
414
452
  const { entities } = mergeBatches(input);
415
- const artifact = isSingleStructure(input) ? input : undefined;
416
- const theorems = artifact?.main_theorems ?? [];
453
+ const theorems = collectMainTheorems(input);
417
454
  // Labels resolve against the merged namespace: entities plus main_theorems
418
455
  // (upstream top-down reading paths start at main_theorems, which the
419
456
  // compact v4.2 form may omit from entities[]). Main theorems absent from
@@ -8,17 +8,17 @@
8
8
  import { Context, Service } from '@deepseek-ai/cordis';
9
9
  import z from '@deepseek-ai/schemastery';
10
10
  import { type GlossaryHit, type GlossaryQueryOptions, type GlossaryTerm } from './glossary.ts';
11
- export { VeryMathError, isVeryMathError } from './error.ts';
11
+ export { VeryMathError, isVeryMathError, isErrnoCode } from './error.ts';
12
12
  export { bundledSkillsDir } from './paths.ts';
13
13
  export { VeryMathSkillProvider } from './skills.ts';
14
14
  export { parseGlossary, queryGlossary, sortGlossary, upsertTerms, validateGlossaryInvariants } from './glossary.ts';
15
15
  export type { GlossaryHit, GlossaryQueryOptions, GlossaryTerm, TermUpsert, UpsertResult } from './glossary.ts';
16
- export { parsePaperStructure, dependencySummary } from './paper.ts';
16
+ export { parsePaperStructure, parsePaperBatch, dependencySummary } from './paper.ts';
17
17
  export { checkGate, checkGoalApproval, checkWorkstreamCompletion, checkFinalRender, loadGoals, listWorkstreams, hasSection, } from './gates.ts';
18
18
  export type { GateResult } from './gates.ts';
19
19
  export { loadManifest, searchSageRefs, scoreRow, termsFor, findExcerpt, readCorpusDoc, readCorpusDocWindow, resolveCorpusRoot, defaultCorpusRoot, docPath, } from './sage.ts';
20
20
  export type { SageRefRow, SageRefHit } from './sage.ts';
21
- export { mergeBatches, collectEntities, computeTopology, renderMermaid, focusClosure, mermaidDisplayText, stripUncertain, isSingleStructure, requireStructure, } from './graph.ts';
21
+ export { mergeBatches, mergeStructures, collectEntities, collectMainTheorems, computeTopology, renderMermaid, focusClosure, mermaidDisplayText, stripUncertain, isSingleStructure, requireStructure, } from './graph.ts';
22
22
  export type { StructureInput, MergeReport, EntityTopology, DependencyCycle, GraphTopology, FocusResult, } from './graph.ts';
23
23
  export type { PaperStructure, PaperMeta, PaperSection, PaperEntity, PaperTable, MainTheorem, ProofMethod, ProofFramework, CompletenessCheck, RelatedWorkEntry, } from './paper.ts';
24
24
  declare module '@deepseek-ai/cordis' {
@@ -60,6 +60,7 @@ export declare class VeryMathRuntime extends Service {
60
60
  /** Resolved service config with every default applied. */
61
61
  readonly config: Required<VeryMathRuntimeConfig>;
62
62
  private readonly glossaryCache;
63
+ private readonly glossaryWrites;
63
64
  private pythonProbe;
64
65
  constructor(ctx: Context, config?: VeryMathRuntimeConfig);
65
66
  /**
@@ -78,6 +79,24 @@ export declare class VeryMathRuntime extends Service {
78
79
  loadGlossary(path: string, signal?: AbortSignal): Promise<GlossaryLibrary>;
79
80
  /** Forget any cached glossary for `path` so a later load re-reads from disk. */
80
81
  invalidateGlossary(path: string): void;
82
+ /**
83
+ * Re-read a glossary from disk, discarding any cached snapshot. Callers that
84
+ * are about to rewrite the document must use this rather than
85
+ * {@link loadGlossary}: the query cache is only invalidated by this package's
86
+ * own writes, so a document edited by the user (or by the bundled
87
+ * `glossary_web.py`) would otherwise be overwritten from a stale snapshot.
88
+ * @param path - absolute or workspace-relative path of `glossary.json`.
89
+ * @param signal - cancels the read.
90
+ */
91
+ reloadGlossary(path: string, signal?: AbortSignal): Promise<GlossaryLibrary>;
92
+ /**
93
+ * Serialize read-modify-write cycles on one glossary document. Two concurrent
94
+ * upserts on the same file would otherwise both read one snapshot and the
95
+ * later write would silently drop the earlier update.
96
+ * @param path - glossary document path; the lock key is the normalized path.
97
+ * @param task - the whole read-modify-write, run after any in-flight task.
98
+ */
99
+ withGlossaryWrite<T>(path: string, task: () => Promise<T>): Promise<T>;
81
100
  /** Forget every cached glossary (used when a build script's output path is unknown). */
82
101
  invalidateAllGlossaries(): void;
83
102
  /**
package/lib/core/index.js CHANGED
@@ -10,18 +10,18 @@ import z from '@deepseek-ai/schemastery';
10
10
  import { spawn } from 'node:child_process';
11
11
  import { readFile } from 'node:fs/promises';
12
12
  import { normalize } from 'node:path';
13
- import { VeryMathError } from "./error.js";
13
+ import { isErrnoCode, VeryMathError } from "./error.js";
14
14
  import { parseGlossary, queryGlossary, validateGlossaryInvariants } from "./glossary.js";
15
15
  import { bundledSkillsDir } from "./paths.js";
16
16
  import { VeryMathSkillProvider } from "./skills.js";
17
- export { VeryMathError, isVeryMathError } from "./error.js";
17
+ export { VeryMathError, isVeryMathError, isErrnoCode } from "./error.js";
18
18
  export { bundledSkillsDir } from "./paths.js";
19
19
  export { VeryMathSkillProvider } from "./skills.js";
20
20
  export { parseGlossary, queryGlossary, sortGlossary, upsertTerms, validateGlossaryInvariants } from "./glossary.js";
21
- export { parsePaperStructure, dependencySummary } from "./paper.js";
21
+ export { parsePaperStructure, parsePaperBatch, dependencySummary } from "./paper.js";
22
22
  export { checkGate, checkGoalApproval, checkWorkstreamCompletion, checkFinalRender, loadGoals, listWorkstreams, hasSection, } from "./gates.js";
23
23
  export { loadManifest, searchSageRefs, scoreRow, termsFor, findExcerpt, readCorpusDoc, readCorpusDocWindow, resolveCorpusRoot, defaultCorpusRoot, docPath, } from "./sage.js";
24
- export { mergeBatches, collectEntities, computeTopology, renderMermaid, focusClosure, mermaidDisplayText, stripUncertain, isSingleStructure, requireStructure, } from "./graph.js";
24
+ export { mergeBatches, mergeStructures, collectEntities, collectMainTheorems, computeTopology, renderMermaid, focusClosure, mermaidDisplayText, stripUncertain, isSingleStructure, requireStructure, } from "./graph.js";
25
25
  /**
26
26
  * The VeryMath access service, registered as `ctx.verymath`. Owns glossary
27
27
  * parsing/querying, Python discovery, and bundled-skill registration.
@@ -36,6 +36,7 @@ export class VeryMathRuntime extends Service {
36
36
  /** Resolved service config with every default applied. */
37
37
  config;
38
38
  glossaryCache = new Map();
39
+ glossaryWrites = new Map();
39
40
  pythonProbe;
40
41
  constructor(ctx, config = {}) {
41
42
  super(ctx, 'verymath');
@@ -76,7 +77,15 @@ export class VeryMathRuntime extends Service {
76
77
  raw = await readFile(key, { encoding: 'utf8', ...(signal !== undefined ? { signal } : {}) });
77
78
  }
78
79
  catch (error) {
79
- throw new VeryMathError(`cannot read glossary at ${key}: ${error instanceof Error ? error.message : String(error)}`, 'VERYMATH_GLOSSARY_UNAVAILABLE', { cause: error });
80
+ // Only a genuinely absent file means "there is no glossary yet". Treating
81
+ // every read failure that way let an EACCES/EIO/abort turn into "start from
82
+ // an empty glossary", and the next write then replaced the real document.
83
+ if (isErrnoCode(error, 'ENOENT')) {
84
+ throw new VeryMathError(`cannot read glossary at ${key}: ${error instanceof Error ? error.message : String(error)}`, 'VERYMATH_GLOSSARY_UNAVAILABLE', { cause: error });
85
+ }
86
+ if (error instanceof Error && error.name === 'AbortError')
87
+ throw error;
88
+ throw new VeryMathError(`cannot read glossary at ${key}: ${error instanceof Error ? error.message : String(error)}`, 'VERYMATH_IO', { cause: error });
80
89
  }
81
90
  let parsed;
82
91
  try {
@@ -94,6 +103,41 @@ export class VeryMathRuntime extends Service {
94
103
  invalidateGlossary(path) {
95
104
  this.glossaryCache.delete(normalize(path));
96
105
  }
106
+ /**
107
+ * Re-read a glossary from disk, discarding any cached snapshot. Callers that
108
+ * are about to rewrite the document must use this rather than
109
+ * {@link loadGlossary}: the query cache is only invalidated by this package's
110
+ * own writes, so a document edited by the user (or by the bundled
111
+ * `glossary_web.py`) would otherwise be overwritten from a stale snapshot.
112
+ * @param path - absolute or workspace-relative path of `glossary.json`.
113
+ * @param signal - cancels the read.
114
+ */
115
+ reloadGlossary(path, signal) {
116
+ this.invalidateGlossary(path);
117
+ return this.loadGlossary(path, signal);
118
+ }
119
+ /**
120
+ * Serialize read-modify-write cycles on one glossary document. Two concurrent
121
+ * upserts on the same file would otherwise both read one snapshot and the
122
+ * later write would silently drop the earlier update.
123
+ * @param path - glossary document path; the lock key is the normalized path.
124
+ * @param task - the whole read-modify-write, run after any in-flight task.
125
+ */
126
+ async withGlossaryWrite(path, task) {
127
+ const key = normalize(path);
128
+ const previous = this.glossaryWrites.get(key) ?? Promise.resolve();
129
+ // `then(task, task)` so one failed writer does not wedge the queue.
130
+ const run = previous.then(task, task);
131
+ const chained = run.then(() => undefined, () => undefined);
132
+ this.glossaryWrites.set(key, chained);
133
+ try {
134
+ return await run;
135
+ }
136
+ finally {
137
+ if (this.glossaryWrites.get(key) === chained)
138
+ this.glossaryWrites.delete(key);
139
+ }
140
+ }
97
141
  /** Forget every cached glossary (used when a build script's output path is unknown). */
98
142
  invalidateAllGlossaries() {
99
143
  this.glossaryCache.clear();
@@ -145,12 +145,26 @@ export interface PaperStructure {
145
145
  }
146
146
  /**
147
147
  * Parse and structurally validate one paper-structure artifact: paper
148
- * metadata must be present, entities must use recognized kinds, and
149
- * dependency labels must reference known entities or main theorems.
148
+ * metadata must be present, entities must use recognized kinds, and (unless
149
+ * asked to defer it) dependency labels must reference known entities or main
150
+ * theorems.
150
151
  * @param value - the parsed JSON value of a `<slug>_structure.json`.
152
+ * @param options - `deferDependencyCheck` validates shape only, for one batch
153
+ * artifact whose dependencies may legitimately point into another artifact.
151
154
  * @returns the validated structure.
152
155
  */
153
- export declare function parsePaperStructure(value: unknown): PaperStructure;
156
+ export declare function parsePaperStructure(value: unknown, options?: {
157
+ readonly deferDependencyCheck?: boolean;
158
+ }): PaperStructure;
159
+ /**
160
+ * Parse several batch artifacts of one paper and validate dependency labels
161
+ * against the **merged** label set. Validating each file on its own rejects the
162
+ * upstream batch protocol itself: a later batch legitimately cites entities that
163
+ * an earlier batch defined.
164
+ * @param values - the parsed JSON values of the batch artifacts.
165
+ * @returns the validated structures, in input order.
166
+ */
167
+ export declare function parsePaperBatch(values: readonly unknown[]): PaperStructure[];
154
168
  /**
155
169
  * Compute a compact dependency summary: per-entity dependent counts and the
156
170
  * entities no other entity depends on (roots of the dependency forest).
package/lib/core/paper.js CHANGED
@@ -15,12 +15,15 @@ function isRecord(value) {
15
15
  }
16
16
  /**
17
17
  * Parse and structurally validate one paper-structure artifact: paper
18
- * metadata must be present, entities must use recognized kinds, and
19
- * dependency labels must reference known entities or main theorems.
18
+ * metadata must be present, entities must use recognized kinds, and (unless
19
+ * asked to defer it) dependency labels must reference known entities or main
20
+ * theorems.
20
21
  * @param value - the parsed JSON value of a `<slug>_structure.json`.
22
+ * @param options - `deferDependencyCheck` validates shape only, for one batch
23
+ * artifact whose dependencies may legitimately point into another artifact.
21
24
  * @returns the validated structure.
22
25
  */
23
- export function parsePaperStructure(value) {
26
+ export function parsePaperStructure(value, options = {}) {
24
27
  if (!isRecord(value)) {
25
28
  throw new VeryMathError('paper structure must be a JSON object', 'VERYMATH_PAPER_INVALID');
26
29
  }
@@ -35,23 +38,51 @@ export function parsePaperStructure(value) {
35
38
  // upstream v4.2 compact form and are handled with `?? []` everywhere.
36
39
  const structure = value;
37
40
  const entities = structure.entities ?? [];
38
- const labels = new Set();
39
41
  for (const entity of entities) {
40
42
  if (!ENTITY_KINDS.includes(entity.type)) {
41
43
  throw new VeryMathError(`entity ${entity.label}: unknown type ${String(entity.type)}`, 'VERYMATH_PAPER_INVALID');
42
44
  }
43
- labels.add(entity.label);
44
45
  }
45
- for (const theorem of structure.main_theorems ?? [])
46
- labels.add(theorem.label);
47
- for (const entity of entities) {
48
- for (const dependency of entity.dependencies ?? []) {
49
- if (!labels.has(dependency)) {
50
- throw new VeryMathError(`entity ${entity.label} depends on unknown label ${dependency}`, 'VERYMATH_PAPER_INVALID');
46
+ if (options.deferDependencyCheck !== true) {
47
+ requireKnownDependencyLabels([structure], 'entity');
48
+ }
49
+ return structure;
50
+ }
51
+ /**
52
+ * Parse several batch artifacts of one paper and validate dependency labels
53
+ * against the **merged** label set. Validating each file on its own rejects the
54
+ * upstream batch protocol itself: a later batch legitimately cites entities that
55
+ * an earlier batch defined.
56
+ * @param values - the parsed JSON values of the batch artifacts.
57
+ * @returns the validated structures, in input order.
58
+ */
59
+ export function parsePaperBatch(values) {
60
+ const structures = values.map(value => parsePaperStructure(value, { deferDependencyCheck: true }));
61
+ requireKnownDependencyLabels(structures, 'entity');
62
+ return structures;
63
+ }
64
+ /**
65
+ * Throw when an entity depends on a label no artifact defines. Runs once over
66
+ * the merged namespace, which is what makes cross-batch edges legal while still
67
+ * rejecting genuinely dangling references.
68
+ */
69
+ function requireKnownDependencyLabels(structures, subject) {
70
+ const labels = new Set();
71
+ for (const structure of structures) {
72
+ for (const entity of structure.entities ?? [])
73
+ labels.add(entity.label);
74
+ for (const theorem of structure.main_theorems ?? [])
75
+ labels.add(theorem.label);
76
+ }
77
+ for (const structure of structures) {
78
+ for (const entity of structure.entities ?? []) {
79
+ for (const dependency of entity.dependencies ?? []) {
80
+ if (!labels.has(dependency)) {
81
+ throw new VeryMathError(`${subject} ${entity.label} depends on unknown label ${dependency}`, 'VERYMATH_PAPER_INVALID');
82
+ }
51
83
  }
52
84
  }
53
85
  }
54
- return structure;
55
86
  }
56
87
  /**
57
88
  * Compute a compact dependency summary: per-entity dependent counts and the