@equationalapplications/core-llm-wiki 9.5.3 → 9.6.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.
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { BaseRepository, WikiGraphNodeOwnershipConflict, serializeSourcePointer, parseStoredSourcePointer, parseJsonObject, parseJsonArray, liveAtSql, reanchorRebuildFingerprint, __privateAdd, warnChangedDefaultsOnce, EdgeRepository, MetadataRepository, EmbeddingService, VectorRemovalRepository, VectorRemovalService, SearchService, TemporalService, JobManager, PromptService, resolveGrounding, IngestionService, MaintenanceService, ImportExportService, RetrievalService, SourceStoreService, WriteService, __privateGet, __privateSet, createLegacySourceTypeIndex, writeNormalizeStamp, CURRENT_SCHEMA_VERSION, detectSchemaVersion, MIGRATIONS, runSourceRefNormalize, emitDiagnostic, normalizeSourceRef, normalizeSourceHash, resolveLibrarianStrategy, entitySummaryMetaKey, WikiSourceRefHashCollision, DiagnosticBuffer, validateManifest, WikiDraftNotFound, generateId, emptyManifest, resolveNodeType, WikiStrictOntologyViolation, validateInlineEdges, resolveEdgeDefinitions, typeSatisfies, normalizeTitleKey, edgeTripleAllowed, MAX_EMBED_ATTEMPTS, UsageMeter, isWikiSearchUnavailableError, WikiBusyError, WikiInvalidReadOptions, isLiveAt, packFactsByBudget, factTokenCost, probePendingWork, WikiMigrationRequiredError, setupDatabase, UnavailableIndexStrategy, createdAtValue, isUsableDate, validateSourcePointerValue, assertEntityId, assertEpochMs, passageFtsTriggerNames, FTS5_STATE_KEY, fts5LedgerDropSql, passageFtsTablesDdl, passageFtsTriggersDdl, fts5TablesDdl, fts5PendingIndexesDdl, fts5TriggersDdl, writeRebuildStart, FTS5_RETIRED_COUNTER_KEY, retiredTableName, FTS5_RETIRED_TABLES_KEY, isRetiredTableName, idReindexChunkSql, readRebuildProgress, FTS5_DRAIN_CHUNK, FTS5_RECLAIM_MERGE_PAGES, windowHiSql, windowChunkSql, FTS5_REBUILD_WM_KEY, sweepHiSql, sweepChunkSql, FTS5_SWEEP_CURSOR_KEY, drainHiSql, drainChunkSql, FTS5_REBUILD_SNAPSHOT_KEY, idDrainChunkSql, entityDrainHiSql, entityDrainChunkSql, fts5TriggerNames, extractSqliteCode, WikiTransactionError } from './chunk-QIS2SGUM.mjs';
2
- export { CheckpointIncompleteError, DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, EMBED_CHARS_CEILING, EraseStepError, HEAL_ANCHORS_PER_CANDIDATE, HEAL_BATCH_SIZE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, HEAL_RECHECK_MS, HOOK_TIMEOUT_MARKER, ONTOLOGY_BACKFILL_BATCH_SIZE, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_RECHECK_MS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, PromptService, PrunePartialFailureError, WikiBusyError, WikiDraftNotFound, WikiDuplicateHashError, WikiExternalDeletionError, WikiGraphNodeOwnershipConflict, WikiIngestEmptyError, WikiInvalidReadOptions, WikiMigrationRequiredError, WikiParseError, WikiSearchUnavailableError, WikiSourceRefHashCollision, WikiStrictOntologyViolation, WikiSupersedeError, WikiTransactionError, chunkText, configureRandomSource, isWikiSearchUnavailableError, parseEmbedding, safeSlice, validUsage, validateManifest } from './chunk-QIS2SGUM.mjs';
1
+ import { BaseRepository, WikiGraphNodeOwnershipConflict, serializeSourcePointer, parseStoredSourcePointer, parseJsonObject, parseJsonArray, liveAtSql, reanchorRebuildFingerprint, __privateAdd, warnChangedDefaultsOnce, EdgeRepository, MetadataRepository, EmbeddingService, VectorRemovalRepository, VectorRemovalService, SearchService, TemporalService, JobManager, PromptService, resolveGrounding, IngestionService, MaintenanceService, ImportExportService, RetrievalService, SourceStoreService, WriteService, __privateGet, __privateSet, createLegacySourceTypeIndex, writeNormalizeStamp, CURRENT_SCHEMA_VERSION, detectSchemaVersion, MIGRATIONS, runSourceRefNormalize, emitDiagnostic, normalizeSourceRef, normalizeSourceHash, resolveLibrarianStrategy, entitySummaryMetaKey, WikiSourceRefHashCollision, DiagnosticBuffer, validateManifest, isReservedAbstainSlug, ONTOLOGY_ABSTAIN_SENTINEL, WikiDraftNotFound, generateId, emptyManifest, resolveNodeType, WikiStrictOntologyViolation, validateInlineEdges, resolveEdgeDefinitions, typeSatisfies, normalizeTitleKey, edgeTripleAllowed, MAX_EMBED_ATTEMPTS, UsageMeter, isWikiSearchUnavailableError, WikiBusyError, WikiInvalidReadOptions, isLiveAt, packFactsByBudget, factTokenCost, probePendingWork, WikiMigrationRequiredError, setupDatabase, UnavailableIndexStrategy, createdAtValue, isUsableDate, validateSourcePointerValue, assertEntityId, assertEpochMs, passageFtsTriggerNames, FTS5_STATE_KEY, fts5LedgerDropSql, passageFtsTablesDdl, passageFtsTriggersDdl, fts5TablesDdl, fts5PendingIndexesDdl, fts5TriggersDdl, writeRebuildStart, FTS5_RETIRED_COUNTER_KEY, retiredTableName, FTS5_RETIRED_TABLES_KEY, isRetiredTableName, idReindexChunkSql, readRebuildProgress, FTS5_DRAIN_CHUNK, FTS5_RECLAIM_MERGE_PAGES, windowHiSql, windowChunkSql, FTS5_REBUILD_WM_KEY, sweepHiSql, sweepChunkSql, FTS5_SWEEP_CURSOR_KEY, drainHiSql, drainChunkSql, FTS5_REBUILD_SNAPSHOT_KEY, idDrainChunkSql, entityDrainHiSql, entityDrainChunkSql, fts5TriggerNames, extractSqliteCode, WikiTransactionError } from './chunk-TZMLWQ3G.mjs';
2
+ export { CLASSIFIER_MAX_CHOICES, CheckpointIncompleteError, DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DEFAULT_TYPING_MIN_CONFIDENCE, EMBED_CHARS_CEILING, EraseStepError, HEAL_ANCHORS_PER_CANDIDATE, HEAL_BATCH_SIZE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, HEAL_RECHECK_MS, HOOK_TIMEOUT_MARKER, ONTOLOGY_ABSTAIN_SENTINEL, ONTOLOGY_BACKFILL_BATCH_SIZE, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_RECHECK_MS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, PromptService, PrunePartialFailureError, WikiBusyError, WikiDraftNotFound, WikiDuplicateHashError, WikiExternalDeletionError, WikiGraphNodeOwnershipConflict, WikiIngestEmptyError, WikiInvalidReadOptions, WikiMigrationRequiredError, WikiParseError, WikiSearchUnavailableError, WikiSourceRefHashCollision, WikiStrictOntologyViolation, WikiSupersedeError, WikiTransactionError, chunkText, configureRandomSource, isReservedAbstainSlug, isWikiSearchUnavailableError, parseEmbedding, resolveSystemOneTyping, resolveTypingMinConfidence, safeSlice, validUsage, validateManifest, warnOnce } from './chunk-TZMLWQ3G.mjs';
3
3
  import { deriveTrustTier, isStaleAfter, appendRelatedSection, buildConceptDocument, buildLogMd, buildEntityIndexMd, buildRootIndexMd, isAllowedOkfPath, parseRootIndexMd, parseEntityIndexMd, parseConcept, splitRelatedSection, extractMarkdownLinks, parseLogMd, parseEventIdComment, createEventIdDeriver, latestVerified, formatSourcesJson, appendEventIdComment, parseVerifiedFlexible, parseCitationsList } from '@equationalapplications/core-okf';
4
4
  import MiniSearch from 'minisearch';
5
5
 
@@ -3378,6 +3378,14 @@ async function createIndexStrategy(db, prefix, metadataRepo, preferred, opts = {
3378
3378
  }
3379
3379
  }
3380
3380
 
3381
+ // src/utils/config/ontologyJobDefaults.ts
3382
+ var DEFAULT_ONTOLOGY_JOB_BATCH_SIZE = 50;
3383
+ function resolveOntologyJobDefaults(ontology) {
3384
+ const raw = ontology?.schedulerBatchSize;
3385
+ const batchSize = typeof raw === "number" && Number.isInteger(raw) && raw >= 1 ? raw : DEFAULT_ONTOLOGY_JOB_BATCH_SIZE;
3386
+ return { batchSize };
3387
+ }
3388
+
3381
3389
  // src/services/MaintenanceScheduler.ts
3382
3390
  var MaintenanceScheduler = class {
3383
3391
  constructor(db, options, maintenanceService, metadataRepo, eventRepo, entryRepo, jobManager, vectorRemovalService, vectorRemovalRepo) {
@@ -3390,6 +3398,8 @@ var MaintenanceScheduler = class {
3390
3398
  this.jobManager = jobManager;
3391
3399
  this.vectorRemovalService = vectorRemovalService;
3392
3400
  this.vectorRemovalRepo = vectorRemovalRepo;
3401
+ /** Batch size for scheduler-driven ontology passes; resolved once (spec §8). */
3402
+ this.schedulerBatchSize = resolveOntologyJobDefaults(this.options.config?.ontology).batchSize;
3393
3403
  }
3394
3404
  /**
3395
3405
  * Entities with **any** pending work only, sorted by `pendingEvents` desc
@@ -3422,14 +3432,16 @@ var MaintenanceScheduler = class {
3422
3432
  const healDue = eventCount - healCheckpoint >= autoHealThreshold;
3423
3433
  const reembedPending = canEmbed && await this.entryRepo.countReembedPending(entityId, MAX_EMBED_ATTEMPTS) > 0;
3424
3434
  const owedCount = owed.get(entityId) ?? 0;
3425
- if (pendingEvents > 0 || healDue || reembedPending || owedCount > 0) {
3435
+ const ontologyBackfillPending = await this.maintenanceService.pendingOntologyBackfill(entityId);
3436
+ if (pendingEvents > 0 || healDue || reembedPending || owedCount > 0 || ontologyBackfillPending > 0) {
3426
3437
  out.push({
3427
3438
  entityId,
3428
3439
  pendingEvents,
3429
3440
  pendingTokensEstimate: Math.ceil(chars / 4),
3430
3441
  healDue,
3431
3442
  reembedPending,
3432
- ...owedCount > 0 ? { pendingExternalDeletions: owedCount } : {}
3443
+ ...owedCount > 0 ? { pendingExternalDeletions: owedCount } : {},
3444
+ ...ontologyBackfillPending > 0 ? { pendingOntologyBackfill: ontologyBackfillPending } : {}
3433
3445
  });
3434
3446
  }
3435
3447
  }
@@ -3456,15 +3468,16 @@ var MaintenanceScheduler = class {
3456
3468
  const meter = new UsageMeter(opts.tokenBudget);
3457
3469
  const budget = opts.tokenBudget;
3458
3470
  const deadline = opts.deadlineMs !== void 0 ? Date.now() + Math.max(0, opts.deadlineMs) : Infinity;
3459
- const jobs = new Set(opts.jobs ?? ["librarian", "heal", "reembed", "externalDeletions"]);
3471
+ const jobs = new Set(opts.jobs ?? ["librarian", "heal", "reembed", "externalDeletions", "ontologyBackfill"]);
3460
3472
  const externalDeletions = await this.runExternalDeletions(opts.entityIds, jobs.has("externalDeletions"), deadline);
3461
- const pending = (await this.getPending(opts.entityIds)).filter((p) => p.pendingEvents > 0 || p.healDue || p.reembedPending);
3473
+ const pending = (await this.getPending(opts.entityIds)).filter((p) => p.pendingEvents > 0 || p.healDue || p.reembedPending || (p.pendingOntologyBackfill ?? 0) > 0);
3462
3474
  const states = pending.map((p) => ({
3463
3475
  p,
3464
- report: { entityId: p.entityId, librarianPasses: 0, factsWritten: 0, healPasses: 0, reembedded: false },
3476
+ report: { entityId: p.entityId, librarianPasses: 0, factsWritten: 0, healPasses: 0, reembedded: false, ontologyBackfillPasses: 0, typed: 0 },
3465
3477
  librarian: jobs.has("librarian") && p.pendingEvents > 0,
3466
3478
  heal: jobs.has("heal") && p.healDue,
3467
- reembed: jobs.has("reembed") && p.reembedPending
3479
+ reembed: jobs.has("reembed") && p.reembedPending,
3480
+ ontology: jobs.has("ontologyBackfill") && (p.pendingOntologyBackfill ?? 0) > 0
3468
3481
  }));
3469
3482
  let stopped = { reason: "complete" };
3470
3483
  let tooSmall = null;
@@ -3484,12 +3497,12 @@ var MaintenanceScheduler = class {
3484
3497
  var _a;
3485
3498
  ((_a = st.report).searchUnavailable ?? (_a.searchUnavailable = [])).push(job);
3486
3499
  };
3487
- const openJobs = () => states.reduce((n, s) => n + +s.librarian + +s.heal + +s.reembed, 0);
3500
+ const openJobs = () => states.reduce((n, s) => n + +s.librarian + +s.heal + +s.reembed + +s.ontology, 0);
3488
3501
  rounds: for (; ; ) {
3489
3502
  let progressed = false;
3490
3503
  const openAtStart = openJobs();
3491
3504
  for (const st of states) {
3492
- if (!st.librarian && !st.heal && !st.reembed) continue;
3505
+ if (!st.librarian && !st.heal && !st.reembed && !st.ontology) continue;
3493
3506
  if (Date.now() >= deadline) {
3494
3507
  stopped = { reason: "deadline" };
3495
3508
  break rounds;
@@ -3581,6 +3594,42 @@ var MaintenanceScheduler = class {
3581
3594
  else throw err;
3582
3595
  }
3583
3596
  }
3597
+ if (st.ontology) {
3598
+ if (Date.now() >= deadline) {
3599
+ stopped = { reason: "deadline" };
3600
+ break rounds;
3601
+ }
3602
+ st.ontology = false;
3603
+ if (this.jobManager.isBlocked("ontologyBackfill", entityId)) {
3604
+ markBusy(st, "ontologyBackfill");
3605
+ this.maintenanceService.noteOntologyBackfillHeld(entityId);
3606
+ progressed = true;
3607
+ continue;
3608
+ }
3609
+ this.jobManager.acquireLock("ontologyBackfill", entityId);
3610
+ let r;
3611
+ try {
3612
+ r = await this.maintenanceService.doRunOntologyBackfill(entityId, {
3613
+ meter,
3614
+ batchSize: this.schedulerBatchSize
3615
+ });
3616
+ } finally {
3617
+ this.jobManager.releaseLock("ontologyBackfill", entityId);
3618
+ }
3619
+ st.report.ontologyBackfillPasses++;
3620
+ st.report.typed += r.typed;
3621
+ progressed = true;
3622
+ if (r.budgetStop) {
3623
+ if (classify("ontologyBackfill", entityId, r.budgetStop.requiredEstimate) === "exhausted") {
3624
+ stopped = exhaustedStop();
3625
+ break rounds;
3626
+ }
3627
+ continue;
3628
+ }
3629
+ if (r.remaining === 0 || r.typed === 0) {
3630
+ continue;
3631
+ }
3632
+ }
3584
3633
  }
3585
3634
  if (!progressed && openJobs() === openAtStart) break;
3586
3635
  }
@@ -3705,7 +3754,8 @@ var OntologyService = class {
3705
3754
  return buildOntologyPromptAppendix(mode, manifestJson);
3706
3755
  }
3707
3756
  async mergeEmergentUpdates(entityId, updates, tx) {
3708
- const merged = await this.metadataRepo.mergeManifestUpdates(entityId, updates, tx);
3757
+ const filtered = updates.node_types ? { ...updates, node_types: updates.node_types.filter((nt) => !isReservedAbstainSlug(nt.type)) } : updates;
3758
+ const merged = await this.metadataRepo.mergeManifestUpdates(entityId, filtered, tx);
3709
3759
  this.invalidateCache(entityId);
3710
3760
  return merged;
3711
3761
  }
@@ -5300,6 +5350,13 @@ var WikiMemory = class {
5300
5350
  }
5301
5351
  for (const entry of entries) {
5302
5352
  validateManifest(entry.manifest);
5353
+ for (const nodeType of entry.manifest.node_types ?? []) {
5354
+ if (isReservedAbstainSlug(nodeType.type)) {
5355
+ throw new Error(
5356
+ `Invalid node type '${nodeType.type}': '${ONTOLOGY_ABSTAIN_SENTINEL}' is reserved for classifier abstention and cannot be declared in a manifest`
5357
+ );
5358
+ }
5359
+ }
5303
5360
  }
5304
5361
  const written = [];
5305
5362
  const skipped = [];
@@ -6413,6 +6470,6 @@ function createWiki(db, options) {
6413
6470
  return new WikiMemory(db, options);
6414
6471
  }
6415
6472
 
6416
- export { DEFAULT_LIBRARIAN_SYNTHESIS_PROMPT, DEFAULT_SETUP_BUDGET_MS, WikiMemory, buildOntologyPromptAppendix, createWiki, formatContext, formatGraphContext, formatMemoryDump, formatOkfBundle, hydrateLibrarianPrompt, mapLibrarianOptionsToReadOptions, parseOkfBundle, validateLibrarianPromptTemplate };
6473
+ export { DEFAULT_LIBRARIAN_SYNTHESIS_PROMPT, DEFAULT_ONTOLOGY_JOB_BATCH_SIZE, DEFAULT_SETUP_BUDGET_MS, WikiMemory, buildOntologyPromptAppendix, createWiki, formatContext, formatGraphContext, formatMemoryDump, formatOkfBundle, hydrateLibrarianPrompt, mapLibrarianOptionsToReadOptions, parseOkfBundle, resolveOntologyJobDefaults, validateLibrarianPromptTemplate };
6417
6474
  //# sourceMappingURL=index.mjs.map
6418
6475
  //# sourceMappingURL=index.mjs.map