@equationalapplications/core-llm-wiki 9.16.2 → 9.18.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/testing.js CHANGED
@@ -819,7 +819,7 @@ var MESSAGE = {
819
819
  guidance_resolver_failed: "The per-entity guidance resolver failed; its value was not used for this pass.",
820
820
  source_pointer_unresolved: "A stored librarian fact carries no source pointer because the model answer could not yield one, or the librarian merged such an unattributed candidate into this fact in place (its derived_events list was not extended).",
821
821
  source_pointer_invalid: "Import met a malformed source pointer value and stored a null pointer.",
822
- source_event_gone: "A librarian candidate was dropped at apply time because the event it came from no longer exists (deleted outside the engine while the pass ran).",
822
+ source_event_gone: "A librarian candidate was dropped at apply time because the event it came from was no longer available: deleted (detail.reason gone) or forgotten with forget({ eventId }) (detail.reason forgotten) outside this instance while the pass ran.",
823
823
  derived_events_invalid: "Import met a malformed derived_events value and stored null.",
824
824
  source_store_source_too_large: "A source document exceeded the per-document size cap and was not stored.",
825
825
  source_store_budget_exceeded: "Storing a source document would exceed the store UTF-16 code-unit budget and it was not stored.",
@@ -1942,7 +1942,7 @@ var ImportExportService = class {
1942
1942
  const [factsRaw, tasks, events, edges, summaryValue] = await Promise.all([
1943
1943
  opts?.includeBlobs ? this.entryRepo.findAllByEntityIdWithBlobs(entityId, void 0, incl) : this.entryRepo.findAllByEntityId(entityId, void 0, incl),
1944
1944
  this.taskRepo.findAllByEntityId(entityId, void 0, incl),
1945
- this.eventRepo.getByEntityId(entityId, opts?.maxEvents),
1945
+ this.eventRepo.getByEntityId(entityId, opts?.maxEvents, incl),
1946
1946
  this.edgeRepo.getByEntityId(entityId),
1947
1947
  this.metadataRepo.getMeta(entitySummaryMetaKey(entityId))
1948
1948
  ]);
@@ -2273,10 +2273,14 @@ var ImportExportService = class {
2273
2273
  summary: event.summary,
2274
2274
  related_entry_id: event.related_entry_id ?? null,
2275
2275
  created_at: stamp.createdAt,
2276
- occurred_at: stamp.occurredAt
2276
+ occurred_at: stamp.occurredAt,
2277
+ forgotten_at: event.forgotten_at ?? null
2277
2278
  },
2278
2279
  tx
2279
2280
  );
2281
+ if (!inserted && event.forgotten_at != null) {
2282
+ await this.eventRepo.markForgotten(entityId, event.id, event.forgotten_at, tx);
2283
+ }
2280
2284
  if (!inserted || stamp.reason === null) continue;
2281
2285
  if (stamp.reason === "future") clampedEvents++;
2282
2286
  else restamped[stamp.reason]++;
@@ -3238,100 +3242,618 @@ async function callClassify(options, ctx, request) {
3238
3242
  return response;
3239
3243
  }
3240
3244
 
3241
- // src/services/IngestionService.ts
3242
- var LLM_PASS_DIAGNOSTIC_CODES = ["ingest_chunk_failed", "fact_rejected", "fact_deduplicated"];
3243
- function dedupDiagnostic(entityId, sourceRef, locator) {
3244
- return {
3245
- entityId,
3246
- operation: "ingest",
3247
- trigger: "call",
3248
- code: "fact_deduplicated",
3249
- detail: locator ? { sourceRef, chunkIndex: locator.chunkIndex, itemIndex: locator.itemIndex, reason: "exact_title" } : { sourceRef, reason: "exact_title" }
3250
- };
3245
+ // src/utils/engineDefaults.ts
3246
+ var DEFAULT_LIBRARIAN_STRATEGY = "ops";
3247
+ var DEFAULT_MAINTENANCE_MODE = "deferred";
3248
+ function resolveLibrarianStrategy(config) {
3249
+ return config?.librarian?.strategy ?? DEFAULT_LIBRARIAN_STRATEGY;
3251
3250
  }
3252
- function zeroChunkResult(duplicateOf) {
3253
- const result = {
3254
- truncated: false,
3255
- chunks: 0,
3256
- ingestedChunks: 0,
3257
- failedChunks: 0
3258
- };
3259
- if (duplicateOf !== void 0) result.duplicateOf = duplicateOf;
3260
- return result;
3251
+ function resolveMaintenanceMode(config) {
3252
+ return config?.maintenance ?? DEFAULT_MAINTENANCE_MODE;
3261
3253
  }
3262
- var IngestionService = class {
3263
- constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, metadataRepo, edgeRepo, searchService, jobManager, embeddingService, promptService, ontologyService, vectorRemoval) {
3264
- this.db = db;
3265
- this.prefix = prefix;
3266
- this.options = options;
3267
- this.entryRepo = entryRepo;
3268
- this.sourceRefIndexRepo = sourceRefIndexRepo;
3269
- this.metadataRepo = metadataRepo;
3270
- this.edgeRepo = edgeRepo;
3271
- this.searchService = searchService;
3272
- this.jobManager = jobManager;
3273
- this.embeddingService = embeddingService;
3274
- this.ontologyService = ontologyService;
3275
- this.vectorRemoval = vectorRemoval;
3276
- this.promptService = promptService ?? new PromptService(this.options.config?.prompts, resolveGrounding(this.options.config?.grounding));
3254
+ var warnedDefaults = /* @__PURE__ */ new Set();
3255
+ function warnOnce(message) {
3256
+ if (warnedDefaults.has(message)) return;
3257
+ warnedDefaults.add(message);
3258
+ console.warn(message);
3259
+ }
3260
+ function formatConfigValue(value) {
3261
+ try {
3262
+ const json = JSON.stringify(value);
3263
+ return json ?? String(value);
3264
+ } catch {
3265
+ return `[unserializable: ${typeof value}]`;
3277
3266
  }
3278
- async ingestDocument(entityId, params, opts) {
3279
- const sourceRef = normalizeSourceRef(params.sourceRef);
3280
- if (!sourceRef) throw new Error("Invalid sourceRef");
3281
- const sourceHash = normalizeSourceHash(params.sourceHash);
3282
- if (!sourceHash) throw new Error("Invalid sourceHash (must be 64-char hex string)");
3283
- const maxChunkLength = params.maxChunkLength ?? this.options.config?.maxChunkLength ?? resolveDefaultChunkLength(resolveContextBudget(this.options.config));
3284
- const rawOverlap = params.chunkOverlap ?? this.options.config?.chunkOverlap ?? DEFAULT_CHUNK_OVERLAP;
3285
- const chunkOverlap = Math.min(
3286
- Number.isFinite(rawOverlap) && rawOverlap >= 0 ? Math.floor(rawOverlap) : DEFAULT_CHUNK_OVERLAP,
3287
- maxChunkLength - 1
3267
+ }
3268
+ var isTypingMode = (v) => v === "auto" || v === "llm";
3269
+ var isConfidenceFloor = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1;
3270
+ function resolveSystemOneTyping(config, classifierCallOption) {
3271
+ const systemOne = config?.systemOne;
3272
+ const legacy = config?.ontology?.backfillClassifier;
3273
+ const systemOneValid = isTypingMode(systemOne?.typing);
3274
+ const legacyValid = isTypingMode(legacy);
3275
+ if (systemOne?.typing !== void 0 && !systemOneValid) {
3276
+ warnOnce(
3277
+ `[core-llm-wiki] systemOne: \`systemOne.typing\` is ${formatConfigValue(systemOne.typing)}, which is not 'auto' or 'llm'. The key is treated as unset; the default ('llm') applies.`
3288
3278
  );
3289
- const rawConcurrency = params.chunkConcurrency ?? this.options.config?.chunkConcurrency ?? 1;
3290
- const chunkConcurrency = Number.isFinite(rawConcurrency) && rawConcurrency >= 1 ? Math.floor(rawConcurrency) : 1;
3291
- if (typeof params.documentChunk !== "string") {
3292
- throw new Error(`documentChunk must be a string, received ${typeof params.documentChunk}`);
3293
- }
3294
- const releaseIngestLocks = await this.jobManager.acquireIngestLocks(entityId, sourceRef, sourceHash);
3295
- try {
3296
- const onDuplicateHash = opts?.onDuplicateHash ?? "ingest";
3297
- if (onDuplicateHash !== "ingest") {
3298
- const canonical = await this.sourceRefIndexRepo.findActiveByEntityAndHash(entityId, sourceHash);
3299
- if (canonical !== null && canonical !== sourceRef) {
3300
- if (onDuplicateHash === "throw") {
3301
- throw new WikiDuplicateHashError({ canonical, sourceHash, entityId });
3302
- }
3303
- return zeroChunkResult(canonical);
3304
- }
3305
- }
3306
- const { chunks: chunks2, truncated } = chunkText(params.documentChunk, maxChunkLength, chunkOverlap);
3307
- if (chunks2.length === 0) return zeroChunkResult();
3308
- const ontologyContext = await this.ontologyService?.buildWritePromptContext(entityId, { engaged: false }) ?? null;
3309
- const { guidance, diagnostic } = PromptService.resolveGuidance(this.options.config, entityId);
3310
- if (diagnostic) {
3311
- emitDiagnostic(this.options, {
3312
- code: diagnostic.code,
3313
- operation: "ingest",
3314
- trigger: "call",
3315
- entityId,
3316
- detail: diagnostic.detail
3317
- });
3279
+ }
3280
+ if (legacy !== void 0 && !legacyValid) {
3281
+ warnOnce(
3282
+ `[core-llm-wiki] systemOne: \`ontology.backfillClassifier\` is ${formatConfigValue(legacy)}, which is not 'auto' or 'llm'. The key is treated as unset; the default ('llm') applies.`
3283
+ );
3284
+ }
3285
+ if (systemOneValid && legacyValid && systemOne.typing !== legacy) {
3286
+ warnOnce(
3287
+ `[core-llm-wiki] systemOne: \`systemOne.typing\` (${systemOne.typing}) and \`ontology.backfillClassifier\` (${legacy}) disagree; \`systemOne.typing\` wins. Remove the legacy key to silence this warning.`
3288
+ );
3289
+ }
3290
+ return classifierCallOption ?? (systemOneValid ? systemOne.typing : void 0) ?? (legacyValid ? legacy : void 0) ?? "llm";
3291
+ }
3292
+ function resolveSystemOneEdges(config) {
3293
+ const edges = config?.systemOne?.edges;
3294
+ if (edges !== void 0 && !isTypingMode(edges)) {
3295
+ warnOnce(
3296
+ `[core-llm-wiki] systemOne: \`systemOne.edges\` is ${formatConfigValue(edges)}, which is not 'auto' or 'llm'. The key is treated as unset; the default ('llm') applies.`
3297
+ );
3298
+ return "llm";
3299
+ }
3300
+ return edges ?? "llm";
3301
+ }
3302
+ function resolveSystemOneResolve(config) {
3303
+ const resolve = config?.systemOne?.resolve;
3304
+ if (resolve !== void 0 && !isTypingMode(resolve)) {
3305
+ warnOnce(
3306
+ `[core-llm-wiki] systemOne: \`systemOne.resolve\` is ${formatConfigValue(resolve)}, which is not 'auto' or 'llm'. The key is treated as unset; the default ('llm') applies.`
3307
+ );
3308
+ return "llm";
3309
+ }
3310
+ return resolve ?? "llm";
3311
+ }
3312
+ var DEFAULT_SHORTLIST_K = 10;
3313
+ function resolveShortlistK(config) {
3314
+ const k = config?.ontology?.shortlistK;
3315
+ if (k === void 0) return DEFAULT_SHORTLIST_K;
3316
+ if (typeof k !== "number" || !Number.isInteger(k) || k < 1) {
3317
+ throw new Error(
3318
+ `[core-llm-wiki] \`ontology.shortlistK\` is ${formatConfigValue(k)}, which is not a finite integer >= 1.`
3319
+ );
3320
+ }
3321
+ return k;
3322
+ }
3323
+ var DEFAULT_TYPING_MIN_CONFIDENCE = 0.5;
3324
+ function resolveTypingMinConfidence(config) {
3325
+ const systemOneFloor = config?.systemOne?.minConfidence?.typing;
3326
+ const legacyFloor = config?.ontology?.classifyMinConfidence;
3327
+ const systemOneValid = isConfidenceFloor(systemOneFloor);
3328
+ const legacyValid = isConfidenceFloor(legacyFloor);
3329
+ if (systemOneFloor !== void 0 && !systemOneValid) {
3330
+ warnOnce(
3331
+ `[core-llm-wiki] systemOne: \`systemOne.minConfidence.typing\` is ${formatConfigValue(systemOneFloor)}, which is not a finite number in [0, 1]. The key is treated as unset and the chain continues.`
3332
+ );
3333
+ }
3334
+ if (legacyFloor !== void 0 && !legacyValid) {
3335
+ warnOnce(
3336
+ `[core-llm-wiki] systemOne: \`ontology.classifyMinConfidence\` is ${formatConfigValue(legacyFloor)}, which is not a finite number in [0, 1]. The key is treated as unset and the chain continues.`
3337
+ );
3338
+ }
3339
+ return (systemOneValid ? systemOneFloor : void 0) ?? (legacyValid ? legacyFloor : void 0) ?? DEFAULT_TYPING_MIN_CONFIDENCE;
3340
+ }
3341
+ var isEdgesFloor = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0.5 && v <= 1;
3342
+ function resolveEdgesMinConfidence(config) {
3343
+ if (resolveSystemOneEdges(config) !== "auto") return void 0;
3344
+ const floor = config?.systemOne?.minConfidence?.edges;
3345
+ if (isEdgesFloor(floor)) return floor;
3346
+ warnOnce(
3347
+ floor === void 0 ? "[core-llm-wiki] systemOne: `systemOne.minConfidence.edges` is required when `systemOne.edges` is 'auto'. The edge screen is off for this site; edges stay on the generative path." : `[core-llm-wiki] systemOne: \`systemOne.minConfidence.edges\` is ${formatConfigValue(floor)}, which is not a finite number in [0.5, 1]. The edge screen is off for this site; edges stay on the generative path.`
3348
+ );
3349
+ return void 0;
3350
+ }
3351
+ function resolveResolveMinConfidence(config) {
3352
+ if (resolveSystemOneResolve(config) !== "auto") return void 0;
3353
+ const floor = config?.systemOne?.minConfidence?.resolve;
3354
+ if (isEdgesFloor(floor)) return floor;
3355
+ warnOnce(
3356
+ floor === void 0 ? "[core-llm-wiki] systemOne: `systemOne.minConfidence.resolve` is required when `systemOne.resolve` is 'auto'. A wrong NOOP drops a live fact, so there is no default floor. The resolution screen is off; resolution stays on the generative path." : `[core-llm-wiki] systemOne: \`systemOne.minConfidence.resolve\` is ${formatConfigValue(floor)}, which is not a finite number in [0.5, 1]. A wrong NOOP drops a live fact, so the resolution screen is off; resolution stays on the generative path.`
3357
+ );
3358
+ return void 0;
3359
+ }
3360
+ function resolveSystemOneHealScreen(config) {
3361
+ const healScreen = config?.systemOne?.healScreen;
3362
+ if (healScreen !== void 0 && !isTypingMode(healScreen)) {
3363
+ warnOnce(
3364
+ `[core-llm-wiki] systemOne: \`systemOne.healScreen\` is ${formatConfigValue(healScreen)}, which is not 'auto' or 'llm'. The key is treated as unset; the default ('llm') applies.`
3365
+ );
3366
+ return "llm";
3367
+ }
3368
+ return healScreen ?? "llm";
3369
+ }
3370
+ function resolveSystemOneTypeOnWrite(config) {
3371
+ const typeOnWrite = config?.systemOne?.typeOnWrite;
3372
+ if (typeOnWrite !== void 0 && !isTypingMode(typeOnWrite)) {
3373
+ warnOnce(
3374
+ `[core-llm-wiki] systemOne: \`systemOne.typeOnWrite\` is ${formatConfigValue(typeOnWrite)}, which is not 'auto' or 'llm'. The key is treated as unset; the default ('llm') applies.`
3375
+ );
3376
+ return "llm";
3377
+ }
3378
+ return typeOnWrite ?? "llm";
3379
+ }
3380
+ function resolveSystemOneTypeOnIngest(config) {
3381
+ const typeOnIngest = config?.systemOne?.typeOnIngest;
3382
+ if (typeOnIngest !== void 0 && !isTypingMode(typeOnIngest)) {
3383
+ warnOnce(
3384
+ `[core-llm-wiki] systemOne: \`systemOne.typeOnIngest\` is ${formatConfigValue(typeOnIngest)}, which is not 'auto' or 'llm'. The key is treated as unset; the default ('llm') applies.`
3385
+ );
3386
+ return "llm";
3387
+ }
3388
+ return typeOnIngest ?? "llm";
3389
+ }
3390
+ function resolveHealScreenMinConfidence(config) {
3391
+ if (resolveSystemOneHealScreen(config) !== "auto") return void 0;
3392
+ const floor = config?.systemOne?.minConfidence?.healScreen;
3393
+ if (isEdgesFloor(floor)) return floor;
3394
+ warnOnce(
3395
+ floor === void 0 ? "[core-llm-wiki] systemOne: `systemOne.minConfidence.healScreen` is required when `systemOne.healScreen` is 'auto'. The heal screen is off for this site; heal stays ungated." : `[core-llm-wiki] systemOne: \`systemOne.minConfidence.healScreen\` is ${formatConfigValue(floor)}, which is not a finite number in [0.5, 1]. The heal screen is off for this site; heal stays ungated.`
3396
+ );
3397
+ return void 0;
3398
+ }
3399
+
3400
+ // src/utils/classifier.ts
3401
+ var isUnit = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1;
3402
+ function validateClassifierAnswer(response, key, question) {
3403
+ try {
3404
+ if (response === null || typeof response !== "object") return { ok: false, reason: "malformed" };
3405
+ const answers = response.answers;
3406
+ if (answers === null || typeof answers !== "object") return { ok: false, reason: "missing_answer" };
3407
+ if (!Object.prototype.hasOwnProperty.call(answers, key)) return { ok: false, reason: "missing_answer" };
3408
+ const raw = answers[key];
3409
+ if (raw === null || typeof raw !== "object") return { ok: false, reason: "missing_answer" };
3410
+ const a = raw;
3411
+ if (a.kind !== question.kind) return { ok: false, reason: "kind_mismatch" };
3412
+ if (question.kind === "choice") {
3413
+ if (typeof a.choice !== "string" || !question.options.includes(a.choice)) return { ok: false, reason: "choice_not_offered" };
3414
+ if (!isUnit(a.confidence)) return { ok: false, reason: "invalid_probability" };
3415
+ const probs = a.probabilities;
3416
+ if (probs === null || typeof probs !== "object" || Array.isArray(probs)) return { ok: false, reason: "invalid_probability" };
3417
+ const probabilities = {};
3418
+ for (const [k, v] of Object.entries(probs)) {
3419
+ if (!isUnit(v)) return { ok: false, reason: "invalid_probability" };
3420
+ probabilities[k] = v;
3318
3421
  }
3319
- const ingestGrounding = this.promptService.groundingFor("ingest");
3320
- const chunkResults = await withConcurrency(
3321
- chunks2.map((chunk, chunkIndex) => async () => {
3322
- const { systemPrompt, userPrompt } = this.promptService.buildIngestPrompt(
3323
- chunk,
3324
- params.promptOverride,
3325
- ontologyContext,
3326
- guidance
3327
- );
3328
- try {
3329
- const responseText = await callLlm(this.options, { operation: "ingest", entityId, trigger: "call" }, { systemPrompt, userPrompt });
3330
- const result2 = parseJsonResponse(responseText);
3331
- const rawFacts = Array.isArray(result2.facts) ? result2.facts : [];
3332
- const facts = [];
3333
- const itemIndexes = [];
3334
- const rejected = [];
3422
+ return { ok: true, answer: { kind: "choice", choice: a.choice, confidence: a.confidence, probabilities } };
3423
+ }
3424
+ if (question.kind === "binary") {
3425
+ if (!isUnit(a.probability)) return { ok: false, reason: "invalid_probability" };
3426
+ return { ok: true, answer: { kind: "binary", probability: a.probability } };
3427
+ }
3428
+ const maxScore = question.levels.length - 1;
3429
+ if (typeof a.score !== "number" || !Number.isFinite(a.score) || a.score < 0 || a.score > maxScore) {
3430
+ return { ok: false, reason: "score_out_of_range" };
3431
+ }
3432
+ if (!isUnit(a.confidence)) return { ok: false, reason: "invalid_probability" };
3433
+ if (!Array.isArray(a.probabilities) || !a.probabilities.every(isUnit)) return { ok: false, reason: "invalid_probability" };
3434
+ return { ok: true, answer: { kind: "score", score: a.score, confidence: a.confidence, probabilities: a.probabilities.slice() } };
3435
+ } catch {
3436
+ return { ok: false, reason: "malformed" };
3437
+ }
3438
+ }
3439
+ function classifierStateForFact(fact) {
3440
+ const parts = [fact.title, fact.body];
3441
+ if (Array.isArray(fact.tags) && fact.tags.length > 0) parts.push(`Tags: ${fact.tags.join(", ")}`);
3442
+ return parts.join("\n\n");
3443
+ }
3444
+
3445
+ // src/services/BoundedLlmCall.ts
3446
+ var DEFAULT_BATCH_SIZE = 10;
3447
+ var ESTIMATED_OUTPUT_TOKENS_PER_ITEM = 150;
3448
+ var OUTPUT_BUDGET_FRACTION = 0.8;
3449
+ var TRUNCATION_PATTERNS = [
3450
+ /truncat/i,
3451
+ /token limit/i,
3452
+ /max(imum)?[ _-]?tokens?/i,
3453
+ /output limit/i,
3454
+ /length limit/i,
3455
+ /finish[_ ]?reason/i
3456
+ ];
3457
+ var EXCEEDS_LIMIT_PATTERN = /exceed[a-z]*[^.]{0,40}\b(model|context)?[ _-]?limit/i;
3458
+ var RATE_LIMIT_PATTERN = /\b(?:status|http|code|error)[^\d]{0,10}429\b|\b429[ _-]?too[ _-]?many[ _-]?requests\b|\b(rate[ _-]?limit|too many requests|(tokens?|requests?)[ _-]?per[ _-]?(minute|min)\b|retry[ _-]?after|quota exceeded)\b/i;
3459
+ var CONTEXT_OVERFLOW_PATTERNS = [
3460
+ /maximum context length/i,
3461
+ /context[_ ]?length[_ ]?exceeded/i,
3462
+ /prompt is too long/i,
3463
+ /input (token count|is too long)/i,
3464
+ /exceeds? the (available )?context( size)?/i,
3465
+ // Tail requires a context-window clause (context|maximum), NOT bare `token`:
3466
+ // a 429 body like "input exceeds the tokens-per-minute limit" must NOT
3467
+ // classify as input overflow (it would split the batch and stamp a cooldown).
3468
+ /(input|prompt).{0,40}exceed(s|ed)? .{0,30}(context|maximum)/i,
3469
+ /context limit/i,
3470
+ // llama.rn (RNLlamaJSI.cpp): prompt >= n_ctx with ctx_shift off
3471
+ /\bcontext is full\b/i,
3472
+ /too long for (the )?requested model/i,
3473
+ // vLLM dual-match wording (errata E2 ruling): the regex ENFORCES the dual-match —
3474
+ // "max_tokens ... too large" PLUS a context clause; a bare message is NOT overflow
3475
+ /max[_ ]?tokens?.{0,40}too large.{0,80}context/i
3476
+ ];
3477
+ function isContextOverflowError(err) {
3478
+ const message = getErrorMessage(err);
3479
+ if (message === void 0) return false;
3480
+ if (RATE_LIMIT_PATTERN.test(message)) return false;
3481
+ return CONTEXT_OVERFLOW_PATTERNS.some((p) => p.test(message));
3482
+ }
3483
+ function getErrorMessage(err) {
3484
+ try {
3485
+ return err instanceof Error ? err.message : String(err ?? "");
3486
+ } catch {
3487
+ return void 0;
3488
+ }
3489
+ }
3490
+ function isTruncationError(err) {
3491
+ const message = getErrorMessage(err);
3492
+ if (message === void 0) return false;
3493
+ if (RATE_LIMIT_PATTERN.test(message)) return false;
3494
+ if (EXCEEDS_LIMIT_PATTERN.test(message)) return false;
3495
+ return TRUNCATION_PATTERNS.some((pattern) => pattern.test(message));
3496
+ }
3497
+ function isConfigError(err) {
3498
+ const message = getErrorMessage(err);
3499
+ if (message === void 0) return false;
3500
+ if (RATE_LIMIT_PATTERN.test(message)) return false;
3501
+ return EXCEEDS_LIMIT_PATTERN.test(message);
3502
+ }
3503
+ function initialBatchSize(maxOutputTokens) {
3504
+ if (!maxOutputTokens || !Number.isFinite(maxOutputTokens) || maxOutputTokens <= 0) {
3505
+ return DEFAULT_BATCH_SIZE;
3506
+ }
3507
+ const estimate = Math.floor(
3508
+ maxOutputTokens * OUTPUT_BUDGET_FRACTION / ESTIMATED_OUTPUT_TOKENS_PER_ITEM
3509
+ );
3510
+ return Math.max(DEFAULT_BATCH_SIZE, estimate);
3511
+ }
3512
+ var promptLength = (prompts) => prompts.systemPrompt.length + prompts.userPrompt.length;
3513
+ async function runBatched(args) {
3514
+ const { items, buildPrompt, call, parse, maxPromptChars, maxOutputTokens, onSkip, supportsEscalation } = args;
3515
+ const results = [];
3516
+ const skipped = [];
3517
+ let batches = 0;
3518
+ const settled = /* @__PURE__ */ new Set();
3519
+ let budgetStop;
3520
+ let batchSize = initialBatchSize(maxOutputTokens);
3521
+ const trim = async (candidate) => {
3522
+ const whole = await buildPrompt(candidate);
3523
+ if (candidate.length <= 1 || promptLength(whole) <= maxPromptChars) {
3524
+ return { batch: candidate, prompts: whole };
3525
+ }
3526
+ let low = 2;
3527
+ let high = candidate.length - 1;
3528
+ let best;
3529
+ let bestPrompts;
3530
+ while (low <= high) {
3531
+ const mid = Math.floor((low + high) / 2);
3532
+ const batch = candidate.slice(0, mid);
3533
+ const prompts = await buildPrompt(batch);
3534
+ if (promptLength(prompts) <= maxPromptChars) {
3535
+ best = batch;
3536
+ bestPrompts = prompts;
3537
+ low = mid + 1;
3538
+ } else {
3539
+ high = mid - 1;
3540
+ }
3541
+ }
3542
+ if (best && bestPrompts) return { batch: best, prompts: bestPrompts };
3543
+ const single = candidate.slice(0, 1);
3544
+ return { batch: single, prompts: await buildPrompt(single) };
3545
+ };
3546
+ const onFailure = async (batch, err, attemptLevel, fromCall) => {
3547
+ if (batch.length === 1) {
3548
+ if (fromCall && (isContextOverflowError(err) ? supportsEscalation : isTruncationError(err)) && attemptLevel < 3) {
3549
+ await attempt(batch, void 0, attemptLevel + 1);
3550
+ } else {
3551
+ const reason = fromCall && !isTruncationError(err) && !isConfigError(err) && !isContextOverflowError(err) ? "call_error" : "non_convergent";
3552
+ skipped.push({ item: batch[0], reason });
3553
+ settled.add(batch[0]);
3554
+ onSkip?.(batch[0], err);
3555
+ }
3556
+ return;
3557
+ }
3558
+ if (fromCall && !isTruncationError(err) && !isContextOverflowError(err)) throw err;
3559
+ const mid = Math.ceil(batch.length / 2);
3560
+ if (mid < batchSize) batchSize = mid;
3561
+ let i = 0;
3562
+ while (i < batch.length && !budgetStop) {
3563
+ const size = Math.min(batchSize, batch.length - i);
3564
+ const trimmed = await trim(batch.slice(i, i + size));
3565
+ await attempt(trimmed.batch, trimmed.prompts);
3566
+ i += trimmed.batch.length;
3567
+ }
3568
+ };
3569
+ const attempt = async (batch, prebuilt, attemptLevel = 0) => {
3570
+ if (budgetStop) return;
3571
+ if (batch.length === 0) return;
3572
+ const prompts = prebuilt && attemptLevel === 0 ? prebuilt : await buildPrompt(batch, attemptLevel);
3573
+ batches++;
3574
+ let responseText;
3575
+ try {
3576
+ responseText = await call(prompts);
3577
+ } catch (err) {
3578
+ if (err instanceof WikiBudgetExhausted) {
3579
+ budgetStop = { requiredEstimate: err.requiredEstimate };
3580
+ return;
3581
+ }
3582
+ await onFailure(batch, err, attemptLevel, true);
3583
+ return;
3584
+ }
3585
+ let result;
3586
+ try {
3587
+ result = parse(responseText, batch, prompts);
3588
+ } catch (err) {
3589
+ await onFailure(batch, err, attemptLevel, false);
3590
+ return;
3591
+ }
3592
+ results.push(result);
3593
+ for (const item of batch) settled.add(item);
3594
+ };
3595
+ let index = 0;
3596
+ while (index < items.length && !budgetStop) {
3597
+ const { batch, prompts } = await trim(items.slice(index, index + batchSize));
3598
+ index += batch.length;
3599
+ await attempt(batch, prompts, 0);
3600
+ }
3601
+ const unattempted = budgetStop ? items.filter((item) => !settled.has(item)) : [];
3602
+ return { results, skipped, batches, unattempted, ...budgetStop ? { budgetStop } : {} };
3603
+ }
3604
+
3605
+ // src/services/typing/typeOnWrite.ts
3606
+ var CLASSIFIER_MAX_CHOICES = 255;
3607
+ function isManifestRepresentable(manifest) {
3608
+ const slugs = manifest.node_types.map((n) => n.type);
3609
+ return slugs.length > 0 && slugs.length + 1 <= CLASSIFIER_MAX_CHOICES && !slugs.some((s) => isReservedAbstainSlug(s));
3610
+ }
3611
+ function typingEngages(site, provider, mode, manifest) {
3612
+ return site === "auto" && typeof provider.classify === "function" && mode !== "off" && isManifestRepresentable(manifest);
3613
+ }
3614
+ function canEngageWriteTyping(config, provider, mode, manifest) {
3615
+ return typingEngages(resolveSystemOneTypeOnWrite(config), provider, mode, manifest);
3616
+ }
3617
+ function canEngageIngestTyping(config, provider, mode, manifest) {
3618
+ return typingEngages(resolveSystemOneTypeOnIngest(config), provider, mode, manifest);
3619
+ }
3620
+ function buildTypingQuestion(manifest) {
3621
+ return {
3622
+ kind: "choice",
3623
+ options: [...manifest.node_types.map((n) => n.type), ONTOLOGY_ABSTAIN_SENTINEL],
3624
+ instructions: `Choose the ontology node type that best describes this fact, or choose "${ONTOLOGY_ABSTAIN_SENTINEL}" if none of the listed types fits.
3625
+ ` + manifest.node_types.map((n) => `- ${n.type}: ${n.description}`).join("\n")
3626
+ };
3627
+ }
3628
+ function volunteeredTypeResolves(rawOkfType, manifest) {
3629
+ return typeof rawOkfType === "string" && resolveNodeTypeMatch(rawOkfType, manifest) !== null;
3630
+ }
3631
+ async function classifyFactsForWrite(options, ctx, facts, manifest, floor, opts) {
3632
+ const question = buildTypingQuestion(manifest);
3633
+ const rawConcurrency = opts?.concurrency ?? options.config?.chunkConcurrency ?? 1;
3634
+ const concurrency = Number.isFinite(rawConcurrency) && rawConcurrency >= 1 ? Math.floor(rawConcurrency) : 1;
3635
+ let stopped = false;
3636
+ return withConcurrency(
3637
+ facts.map((fact) => async () => {
3638
+ if (stopped) return { kind: "unattempted" };
3639
+ let response;
3640
+ try {
3641
+ response = await callClassify(
3642
+ options,
3643
+ { operation: ctx.operation, entityId: ctx.entityId, trigger: ctx.trigger, meter: ctx.meter },
3644
+ { state: classifierStateForFact(fact), questions: { okf_type: question } }
3645
+ );
3646
+ } catch (err) {
3647
+ if (err instanceof WikiBudgetExhausted) {
3648
+ stopped = true;
3649
+ return { kind: "unattempted" };
3650
+ }
3651
+ if (isContextOverflowError(err)) return { kind: "overflow_skip" };
3652
+ return { kind: "threw" };
3653
+ }
3654
+ const checked = validateClassifierAnswer(response, "okf_type", question);
3655
+ if (!checked.ok) return { kind: "invalid", reason: checked.reason };
3656
+ if (checked.answer.kind !== "choice") return { kind: "invalid", reason: "kind_mismatch" };
3657
+ if (isReservedAbstainSlug(checked.answer.choice)) return { kind: "abstain" };
3658
+ if (checked.answer.confidence < floor) return { kind: "low_confidence" };
3659
+ return { kind: "accepted", okfType: checked.answer.choice, confidence: checked.answer.confidence };
3660
+ }),
3661
+ concurrency
3662
+ );
3663
+ }
3664
+ function toIngestCounters(c) {
3665
+ const { unattempted: _unattempted, ...rest } = c;
3666
+ return rest;
3667
+ }
3668
+ function emptyTypingCounters() {
3669
+ return { asked: 0, typed: 0, abstained: 0, lowConfidence: 0, invalid: 0, skipped: 0, unattempted: 0 };
3670
+ }
3671
+ function tallyTypingOutcome(c, o) {
3672
+ switch (o.kind) {
3673
+ case "unattempted":
3674
+ c.unattempted++;
3675
+ return;
3676
+ case "accepted":
3677
+ c.asked++;
3678
+ return;
3679
+ case "abstain":
3680
+ c.asked++;
3681
+ c.abstained++;
3682
+ return;
3683
+ case "low_confidence":
3684
+ c.asked++;
3685
+ c.lowConfidence++;
3686
+ return;
3687
+ case "invalid":
3688
+ case "threw":
3689
+ c.asked++;
3690
+ c.invalid++;
3691
+ return;
3692
+ case "overflow_skip":
3693
+ c.asked++;
3694
+ c.skipped++;
3695
+ return;
3696
+ }
3697
+ }
3698
+ function typingOutcomeReceipt(base, factId, outcome) {
3699
+ switch (outcome.kind) {
3700
+ case "abstain":
3701
+ return { ...base, code: "classification_abstained", detail: { factId, writer: "classifier" } };
3702
+ case "low_confidence":
3703
+ return { ...base, code: "classification_low_confidence", detail: { factId, reason: "below_threshold" } };
3704
+ case "invalid":
3705
+ return { ...base, code: "classification_invalid", detail: { factId, reason: outcome.reason } };
3706
+ case "threw":
3707
+ return { ...base, code: "classification_invalid", detail: { factId, reason: "classify_threw" } };
3708
+ case "overflow_skip":
3709
+ return { ...base, code: "context_overflow_skipped", detail: { factId } };
3710
+ default:
3711
+ return null;
3712
+ }
3713
+ }
3714
+ function normalizeForWrite(ontology, fact, manifest, mode, outcome, base, factId) {
3715
+ const drops = [];
3716
+ const receipts = [];
3717
+ const emit = shouldEmitOntologyReceipt(mode);
3718
+ let normalized = ontology?.validateAndNormalizeFact(fact, manifest, { strict: false, drops }) ?? { okf_type: null, edges: [] };
3719
+ if (emit) {
3720
+ receipts.push(...nodeTypeReceipts(
3721
+ base,
3722
+ factId,
3723
+ typeof fact.okf_type === "string" ? fact.okf_type : "",
3724
+ normalized.okf_type,
3725
+ normalized.match
3726
+ ));
3727
+ }
3728
+ let typedByClassifier = false;
3729
+ if (!normalized.okf_type && outcome?.kind === "accepted" && mode !== "off") {
3730
+ const second = ontology?.validateAndNormalizeFact(
3731
+ { ...fact, okf_type: outcome.okfType, edges: [] },
3732
+ manifest,
3733
+ { strict: false }
3734
+ ) ?? { okf_type: null};
3735
+ if (emit) {
3736
+ receipts.push(...nodeTypeReceipts(base, factId, outcome.okfType, second.okf_type, second.match));
3737
+ }
3738
+ normalized = { okf_type: second.okf_type, edges: [] };
3739
+ if (second.okf_type) {
3740
+ typedByClassifier = true;
3741
+ if (emit) {
3742
+ receipts.push({
3743
+ ...base,
3744
+ code: "node_type_assigned",
3745
+ detail: { factId, okfType: second.okf_type, writer: "classifier", confidence: outcome.confidence }
3746
+ });
3747
+ }
3748
+ }
3749
+ } else if (normalized.okf_type) {
3750
+ if (emit) {
3751
+ receipts.push({ ...base, code: "node_type_assigned", detail: { factId, okfType: normalized.okf_type, writer: "llm" } });
3752
+ }
3753
+ }
3754
+ if (outcome && outcome.kind !== "accepted" && emit && !normalized.okf_type) {
3755
+ const r = typingOutcomeReceipt(base, factId, outcome);
3756
+ if (r) receipts.push(r);
3757
+ }
3758
+ return { normalized, drops, receipts, typedByClassifier };
3759
+ }
3760
+
3761
+ // src/services/IngestionService.ts
3762
+ var LLM_PASS_DIAGNOSTIC_CODES = ["ingest_chunk_failed", "fact_rejected", "fact_deduplicated"];
3763
+ function dedupDiagnostic(entityId, sourceRef, locator) {
3764
+ return {
3765
+ entityId,
3766
+ operation: "ingest",
3767
+ trigger: "call",
3768
+ code: "fact_deduplicated",
3769
+ detail: locator ? { sourceRef, chunkIndex: locator.chunkIndex, itemIndex: locator.itemIndex, reason: "exact_title" } : { sourceRef, reason: "exact_title" }
3770
+ };
3771
+ }
3772
+ function zeroChunkResult(duplicateOf) {
3773
+ const result = {
3774
+ truncated: false,
3775
+ chunks: 0,
3776
+ ingestedChunks: 0,
3777
+ failedChunks: 0
3778
+ };
3779
+ if (duplicateOf !== void 0) result.duplicateOf = duplicateOf;
3780
+ return result;
3781
+ }
3782
+ var IngestionService = class {
3783
+ constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, metadataRepo, edgeRepo, searchService, jobManager, embeddingService, promptService, ontologyService, vectorRemoval) {
3784
+ this.db = db;
3785
+ this.prefix = prefix;
3786
+ this.options = options;
3787
+ this.entryRepo = entryRepo;
3788
+ this.sourceRefIndexRepo = sourceRefIndexRepo;
3789
+ this.metadataRepo = metadataRepo;
3790
+ this.edgeRepo = edgeRepo;
3791
+ this.searchService = searchService;
3792
+ this.jobManager = jobManager;
3793
+ this.embeddingService = embeddingService;
3794
+ this.ontologyService = ontologyService;
3795
+ this.vectorRemoval = vectorRemoval;
3796
+ this.promptService = promptService ?? new PromptService(this.options.config?.prompts, resolveGrounding(this.options.config?.grounding));
3797
+ }
3798
+ async ingestDocument(entityId, params, opts) {
3799
+ const sourceRef = normalizeSourceRef(params.sourceRef);
3800
+ if (!sourceRef) throw new Error("Invalid sourceRef");
3801
+ const sourceHash = normalizeSourceHash(params.sourceHash);
3802
+ if (!sourceHash) throw new Error("Invalid sourceHash (must be 64-char hex string)");
3803
+ const maxChunkLength = params.maxChunkLength ?? this.options.config?.maxChunkLength ?? resolveDefaultChunkLength(resolveContextBudget(this.options.config));
3804
+ const rawOverlap = params.chunkOverlap ?? this.options.config?.chunkOverlap ?? DEFAULT_CHUNK_OVERLAP;
3805
+ const chunkOverlap = Math.min(
3806
+ Number.isFinite(rawOverlap) && rawOverlap >= 0 ? Math.floor(rawOverlap) : DEFAULT_CHUNK_OVERLAP,
3807
+ maxChunkLength - 1
3808
+ );
3809
+ const rawConcurrency = params.chunkConcurrency ?? this.options.config?.chunkConcurrency ?? 1;
3810
+ const chunkConcurrency = Number.isFinite(rawConcurrency) && rawConcurrency >= 1 ? Math.floor(rawConcurrency) : 1;
3811
+ if (typeof params.documentChunk !== "string") {
3812
+ throw new Error(`documentChunk must be a string, received ${typeof params.documentChunk}`);
3813
+ }
3814
+ const releaseIngestLocks = await this.jobManager.acquireIngestLocks(entityId, sourceRef, sourceHash);
3815
+ try {
3816
+ const onDuplicateHash = opts?.onDuplicateHash ?? "ingest";
3817
+ if (onDuplicateHash !== "ingest") {
3818
+ const canonical = await this.sourceRefIndexRepo.findActiveByEntityAndHash(entityId, sourceHash);
3819
+ if (canonical !== null && canonical !== sourceRef) {
3820
+ if (onDuplicateHash === "throw") {
3821
+ throw new WikiDuplicateHashError({ canonical, sourceHash, entityId });
3822
+ }
3823
+ return zeroChunkResult(canonical);
3824
+ }
3825
+ }
3826
+ const { chunks: chunks2, truncated } = chunkText(params.documentChunk, maxChunkLength, chunkOverlap);
3827
+ if (chunks2.length === 0) return zeroChunkResult();
3828
+ const hoistedState = await this.ontologyService?.getEffectiveState(entityId) ?? { mode: "off", manifest: { node_types: [], edge_types: [] } };
3829
+ const engaged = this.ontologyService !== void 0 && canEngageIngestTyping(this.options.config, this.options.llmProvider, hoistedState.mode, hoistedState.manifest);
3830
+ const ontologyContext = await this.ontologyService?.buildWritePromptContext(entityId, { engaged }) ?? null;
3831
+ const { guidance, diagnostic } = PromptService.resolveGuidance(this.options.config, entityId);
3832
+ if (diagnostic) {
3833
+ emitDiagnostic(this.options, {
3834
+ code: diagnostic.code,
3835
+ operation: "ingest",
3836
+ trigger: "call",
3837
+ entityId,
3838
+ detail: diagnostic.detail
3839
+ });
3840
+ }
3841
+ const ingestGrounding = this.promptService.groundingFor("ingest");
3842
+ const chunkResults = await withConcurrency(
3843
+ chunks2.map((chunk, chunkIndex) => async () => {
3844
+ const { systemPrompt, userPrompt } = this.promptService.buildIngestPrompt(
3845
+ chunk,
3846
+ params.promptOverride,
3847
+ ontologyContext,
3848
+ guidance
3849
+ );
3850
+ try {
3851
+ const responseText = await callLlm(this.options, { operation: "ingest", entityId, trigger: "call" }, { systemPrompt, userPrompt });
3852
+ const result2 = parseJsonResponse(responseText);
3853
+ const rawFacts = Array.isArray(result2.facts) ? result2.facts : [];
3854
+ const facts = [];
3855
+ const itemIndexes = [];
3856
+ const rejected = [];
3335
3857
  rawFacts.forEach((raw, itemIndex) => {
3336
3858
  const valid = validateFact(raw);
3337
3859
  if (valid) {
@@ -3461,16 +3983,42 @@ var IngestionService = class {
3461
3983
  chunks: chunks2.length
3462
3984
  });
3463
3985
  }
3986
+ const typing = { outcomes: /* @__PURE__ */ new Map(), counters: emptyTypingCounters() };
3987
+ let hashHeldElsewhere = false;
3988
+ if (engaged && failedChunks === 0 && onDuplicateHash === "ingest") {
3989
+ const holder = await this.sourceRefIndexRepo.findActiveByEntityAndHash(entityId, sourceHash);
3990
+ hashHeldElsewhere = holder !== null && holder !== sourceRef;
3991
+ }
3992
+ if (engaged && !hashHeldElsewhere) {
3993
+ const asked = [];
3994
+ for (const slot of orderedChunkFacts) {
3995
+ for (const fact of slot.facts) {
3996
+ if (!volunteeredTypeResolves(fact.okf_type, hoistedState.manifest)) asked.push(fact);
3997
+ }
3998
+ }
3999
+ const outcomes = await classifyFactsForWrite(
4000
+ this.options,
4001
+ { entityId, trigger: "call", operation: "ingest" },
4002
+ asked,
4003
+ hoistedState.manifest,
4004
+ resolveTypingMinConfidence(this.options.config),
4005
+ { concurrency: chunkConcurrency }
4006
+ );
4007
+ asked.forEach((fact, i) => {
4008
+ typing.outcomes.set(fact, outcomes[i]);
4009
+ tallyTypingOutcome(typing.counters, outcomes[i]);
4010
+ });
4011
+ }
3464
4012
  const insertedFacts = [];
3465
4013
  const deletedSourceFactIds = [];
3466
4014
  try {
3467
4015
  if (failedChunks === 0) {
3468
4016
  const fullResult = await this.db.withTransactionAsync(async (tx) => {
3469
- return await this.runFullUpsertGraph(entityId, sourceRef, sourceHash, orderedChunkFacts, tx, diagBuffer, factLedger);
4017
+ return await this.runFullUpsertGraph(entityId, sourceRef, sourceHash, orderedChunkFacts, tx, diagBuffer, factLedger, typing);
3470
4018
  });
3471
4019
  deletedSourceFactIds.push(...fullResult.deletedSourceFactIds);
3472
4020
  insertedFacts.push(...fullResult.insertedFacts);
3473
- if (ontologyContext !== null && insertedFacts.length === 0 && deletedSourceFactIds.length > 0) {
4021
+ if (hoistedState.mode !== "off" && insertedFacts.length === 0 && deletedSourceFactIds.length > 0) {
3474
4022
  diagBuffer.push({
3475
4023
  entityId,
3476
4024
  operation: "ingest",
@@ -3483,7 +4031,7 @@ var IngestionService = class {
3483
4031
  const partialResult = await this.db.withTransactionAsync(async (tx) => {
3484
4032
  const flat = [];
3485
4033
  for (const slot of orderedChunkFacts) flat.push(...slot.facts);
3486
- return await this.appendPartialFacts(entityId, sourceRef, flat, tx, diagBuffer, factLedger);
4034
+ return await this.appendPartialFacts(entityId, sourceRef, flat, tx, diagBuffer, factLedger, typing);
3487
4035
  });
3488
4036
  insertedFacts.push(...partialResult.insertedDescriptors);
3489
4037
  }
@@ -3535,6 +4083,7 @@ var IngestionService = class {
3535
4083
  failedChunks
3536
4084
  };
3537
4085
  if (failedChunks > 0) result.parseFailures = failures;
4086
+ if (engaged) result.typing = toIngestCounters(typing.counters);
3538
4087
  return result;
3539
4088
  } finally {
3540
4089
  releaseIngestLocks();
@@ -3744,10 +4293,11 @@ var IngestionService = class {
3744
4293
  * On the partial path the caller never invokes this method; the empty
3745
4294
  * arrays stay empty.
3746
4295
  */
3747
- async runFullUpsertGraph(entityId, sourceRef, sourceHash, orderedChunkFacts, tx, diagBuffer, factLedger = /* @__PURE__ */ new Map()) {
4296
+ async runFullUpsertGraph(entityId, sourceRef, sourceHash, orderedChunkFacts, tx, diagBuffer, factLedger = /* @__PURE__ */ new Map(), typing) {
3748
4297
  const deletedSourceFactIds = [];
3749
4298
  const insertedFacts = [];
3750
4299
  const nodeTrust = /* @__PURE__ */ new Map();
4300
+ const diagBase = { entityId, operation: "ingest", trigger: "call" };
3751
4301
  deletedSourceFactIds.push(...await this.entryRepo.findIdsBySource(entityId, sourceRef, null, tx, false));
3752
4302
  const titleIndex = /* @__PURE__ */ new Map();
3753
4303
  const existingFacts = await this.entryRepo.findRecentByEntityId(entityId, 500, tx, sourceRef);
@@ -3761,6 +4311,7 @@ var IngestionService = class {
3761
4311
  let { mode, manifest } = ontologyState;
3762
4312
  const hostNodes = [];
3763
4313
  const rawEdgeRequests = [];
4314
+ const typedAtDoor = [];
3764
4315
  const now = Date.now();
3765
4316
  for (const { facts, ontology_updates } of orderedChunkFacts) {
3766
4317
  if (mode === "emergent" && ontology_updates && this.ontologyService) {
@@ -3780,14 +4331,15 @@ var IngestionService = class {
3780
4331
  for (const fact of facts) {
3781
4332
  const ontologyFact = fact;
3782
4333
  const id = generateId("fact_");
3783
- const validationDrops = [];
3784
- const normalized = this.ontologyService?.validateAndNormalizeFact(ontologyFact, manifest, { strict: false, drops: validationDrops }) ?? { okf_type: null, edges: [] };
3785
- for (const drop of validationDrops) {
4334
+ const outcome = typing?.outcomes.get(fact);
4335
+ const slot = normalizeForWrite(this.ontologyService, ontologyFact, manifest, mode, outcome, diagBase, id);
4336
+ const normalized = slot.normalized;
4337
+ for (const drop of slot.drops) {
3786
4338
  diagBuffer.push(edgeDropDiagnostic(drop, { entityId, operation: "ingest", trigger: "call", sourceRef, factId: id }));
3787
4339
  }
3788
- hostNodes.push({
4340
+ const hostNode = {
3789
4341
  id,
3790
- type: ontologyFact.okf_type ?? "",
4342
+ type: "",
3791
4343
  title: fact.title,
3792
4344
  body: fact.body,
3793
4345
  // Forward the LLM-extracted tags/confidence through the
@@ -3799,18 +4351,20 @@ var IngestionService = class {
3799
4351
  // 'certain' as documented.
3800
4352
  tags: fact.tags,
3801
4353
  confidence: fact.confidence
3802
- });
4354
+ };
4355
+ hostNodes.push(hostNode);
4356
+ typedAtDoor.push({ node: hostNode, fact: ontologyFact, id, outcome, slotType: normalized.okf_type });
3803
4357
  const locator = factLedger.get(fact);
3804
4358
  if (locator?.verdict) {
3805
- const outcome = groundingOutcome(locator.verdict, now);
3806
- nodeTrust.set(id, outcome.trust);
3807
- if (outcome.diagnostic) {
4359
+ const outcome2 = groundingOutcome(locator.verdict, now);
4360
+ nodeTrust.set(id, outcome2.trust);
4361
+ if (outcome2.diagnostic) {
3808
4362
  diagBuffer.push({
3809
4363
  entityId,
3810
4364
  operation: "ingest",
3811
4365
  trigger: "call",
3812
- code: outcome.diagnostic.code,
3813
- detail: { factId: id, sourceRef, chunkIndex: locator.chunkIndex, itemIndex: locator.itemIndex, reason: outcome.diagnostic.reason }
4366
+ code: outcome2.diagnostic.code,
4367
+ detail: { factId: id, sourceRef, chunkIndex: locator.chunkIndex, itemIndex: locator.itemIndex, reason: outcome2.diagnostic.reason }
3814
4368
  });
3815
4369
  }
3816
4370
  }
@@ -3821,6 +4375,18 @@ var IngestionService = class {
3821
4375
  }
3822
4376
  }
3823
4377
  }
4378
+ const doorReceipts = [];
4379
+ for (const { node, fact, id, outcome, slotType } of typedAtDoor) {
4380
+ const final = normalizeForWrite(this.ontologyService, fact, manifest, mode, outcome, diagBase, id);
4381
+ for (const receipt of final.receipts) {
4382
+ doorReceipts.push({ ...receipt, detail: { ...receipt.detail, sourceRef } });
4383
+ }
4384
+ node.type = final.normalized.okf_type ?? "";
4385
+ if (final.typedByClassifier && typing) typing.counters.typed++;
4386
+ if (outcome?.kind === "accepted" && final.normalized.okf_type !== slotType) {
4387
+ titleIndex.set(normalizeTitleKey(fact.title), { id, okf_type: final.normalized.okf_type });
4388
+ }
4389
+ }
3824
4390
  const hostEdges = [];
3825
4391
  for (const req of rawEdgeRequests) {
3826
4392
  const resolveDrops = [];
@@ -3841,6 +4407,7 @@ var IngestionService = class {
3841
4407
  hostEdges.push({ type: e.edge_type, sourceId: e.source_id, targetId: e.target_id });
3842
4408
  }
3843
4409
  }
4410
+ for (const receipt of doorReceipts) diagBuffer.push(receipt);
3844
4411
  await this.upsertGraphCore(
3845
4412
  entityId,
3846
4413
  { sourceRef, sourceHash, nodes: hostNodes, edges: hostEdges },
@@ -3869,7 +4436,7 @@ var IngestionService = class {
3869
4436
  * Runs INSIDE the caller's `tx`. Does not open a nested transaction.
3870
4437
  * Returns `{ inserted, skippedDuplicate }` for observability.
3871
4438
  */
3872
- async appendPartialFacts(entityId, sourceRef, dedupedFacts, tx, diagBuffer, factLedger = /* @__PURE__ */ new Map()) {
4439
+ async appendPartialFacts(entityId, sourceRef, dedupedFacts, tx, diagBuffer, factLedger = /* @__PURE__ */ new Map(), typing) {
3873
4440
  const liveIds = await this.entryRepo.findIdsBySource(entityId, sourceRef, null, tx, false);
3874
4441
  const liveFacts = liveIds.length === 0 ? [] : await this.entryRepo.findByIds(liveIds, void 0, tx);
3875
4442
  const liveTitles = new Set(liveFacts.map((f) => normalizeTitleKey(f.title)));
@@ -3880,6 +4447,7 @@ var IngestionService = class {
3880
4447
  for (const f of indexedFacts) {
3881
4448
  titleIndex.set(normalizeTitleKey(f.title), { id: f.id, okf_type: f.okf_type ?? null });
3882
4449
  }
4450
+ const diagBase = { entityId, operation: "ingest", trigger: "call" };
3883
4451
  const pendingEdges = [];
3884
4452
  let inserted = 0;
3885
4453
  let skippedDuplicate = 0;
@@ -3906,22 +4474,22 @@ var IngestionService = class {
3906
4474
  });
3907
4475
  }
3908
4476
  const ontologyFact = fact;
3909
- const validationDrops = [];
3910
- const normalized = this.ontologyService?.validateAndNormalizeFact(ontologyFact, manifest, { strict: false, drops: validationDrops }) ?? { okf_type: null, edges: [] };
4477
+ const { normalized, drops: validationDrops, receipts, typedByClassifier } = normalizeForWrite(
4478
+ this.ontologyService,
4479
+ ontologyFact,
4480
+ manifest,
4481
+ mode,
4482
+ typing?.outcomes.get(fact),
4483
+ diagBase,
4484
+ id
4485
+ );
3911
4486
  for (const drop of validationDrops) {
3912
4487
  diagBuffer.push(edgeDropDiagnostic(drop, { entityId, operation: "ingest", trigger: "call", sourceRef, factId: id }));
3913
4488
  }
3914
- if (shouldEmitOntologyReceipt(mode)) {
3915
- for (const receipt of nodeTypeReceipts(
3916
- { entityId, operation: "ingest", trigger: "call" },
3917
- id,
3918
- ontologyFact.okf_type ?? "",
3919
- normalized.okf_type,
3920
- normalized.match
3921
- )) {
3922
- diagBuffer.push({ ...receipt, detail: { ...receipt.detail, sourceRef } });
3923
- }
4489
+ for (const receipt of receipts) {
4490
+ diagBuffer.push({ ...receipt, detail: { ...receipt.detail, sourceRef } });
3924
4491
  }
4492
+ if (typedByClassifier && typing) typing.counters.typed++;
3925
4493
  if (normalized.edges.length > 0) {
3926
4494
  pendingEdges.push({ sourceId: id, sourceType: normalized.okf_type, edges: normalized.edges });
3927
4495
  }
@@ -3982,51 +4550,6 @@ var IngestionService = class {
3982
4550
  }
3983
4551
  };
3984
4552
 
3985
- // src/utils/classifier.ts
3986
- var isUnit = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1;
3987
- function validateClassifierAnswer(response, key, question) {
3988
- try {
3989
- if (response === null || typeof response !== "object") return { ok: false, reason: "malformed" };
3990
- const answers = response.answers;
3991
- if (answers === null || typeof answers !== "object") return { ok: false, reason: "missing_answer" };
3992
- if (!Object.prototype.hasOwnProperty.call(answers, key)) return { ok: false, reason: "missing_answer" };
3993
- const raw = answers[key];
3994
- if (raw === null || typeof raw !== "object") return { ok: false, reason: "missing_answer" };
3995
- const a = raw;
3996
- if (a.kind !== question.kind) return { ok: false, reason: "kind_mismatch" };
3997
- if (question.kind === "choice") {
3998
- if (typeof a.choice !== "string" || !question.options.includes(a.choice)) return { ok: false, reason: "choice_not_offered" };
3999
- if (!isUnit(a.confidence)) return { ok: false, reason: "invalid_probability" };
4000
- const probs = a.probabilities;
4001
- if (probs === null || typeof probs !== "object" || Array.isArray(probs)) return { ok: false, reason: "invalid_probability" };
4002
- const probabilities = {};
4003
- for (const [k, v] of Object.entries(probs)) {
4004
- if (!isUnit(v)) return { ok: false, reason: "invalid_probability" };
4005
- probabilities[k] = v;
4006
- }
4007
- return { ok: true, answer: { kind: "choice", choice: a.choice, confidence: a.confidence, probabilities } };
4008
- }
4009
- if (question.kind === "binary") {
4010
- if (!isUnit(a.probability)) return { ok: false, reason: "invalid_probability" };
4011
- return { ok: true, answer: { kind: "binary", probability: a.probability } };
4012
- }
4013
- const maxScore = question.levels.length - 1;
4014
- if (typeof a.score !== "number" || !Number.isFinite(a.score) || a.score < 0 || a.score > maxScore) {
4015
- return { ok: false, reason: "score_out_of_range" };
4016
- }
4017
- if (!isUnit(a.confidence)) return { ok: false, reason: "invalid_probability" };
4018
- if (!Array.isArray(a.probabilities) || !a.probabilities.every(isUnit)) return { ok: false, reason: "invalid_probability" };
4019
- return { ok: true, answer: { kind: "score", score: a.score, confidence: a.confidence, probabilities: a.probabilities.slice() } };
4020
- } catch {
4021
- return { ok: false, reason: "malformed" };
4022
- }
4023
- }
4024
- function classifierStateForFact(fact) {
4025
- const parts = [fact.title, fact.body];
4026
- if (Array.isArray(fact.tags) && fact.tags.length > 0) parts.push(`Tags: ${fact.tags.join(", ")}`);
4027
- return parts.join("\n\n");
4028
- }
4029
-
4030
4553
  // src/utils/shortlist.ts
4031
4554
  function shortlistScore(factTitle, factBody, row) {
4032
4555
  const factTokens = /* @__PURE__ */ new Set([...titleTokens(factTitle), ...titleTokens(factBody)]);
@@ -4234,159 +4757,14 @@ var TemporalService = class {
4234
4757
  this.searchService.evictCache(entityId);
4235
4758
  return { valid_to: restored };
4236
4759
  }
4237
- async history(entityId, factId) {
4238
- const start = await this.entryRepo.findTemporalRow(factId);
4239
- if (!start || start.entity_id !== entityId || start.deleted_at != null) return [];
4240
- const { predecessors, successors } = await this.entryRepo.findSupersessionChainIds(entityId, factId, HISTORY_MAX_DEPTH);
4241
- const facts = await this.entryRepo.findByIds([...predecessors.map((r) => r.id), factId, ...successors.map((r) => r.id)], [entityId]);
4242
- return facts.sort((a, b) => (a.valid_from ?? a.created_at) - (b.valid_from ?? b.created_at) || a.created_at - b.created_at || a.id.localeCompare(b.id));
4243
- }
4244
- };
4245
-
4246
- // src/utils/engineDefaults.ts
4247
- var DEFAULT_LIBRARIAN_STRATEGY = "ops";
4248
- var DEFAULT_MAINTENANCE_MODE = "deferred";
4249
- function resolveLibrarianStrategy(config) {
4250
- return config?.librarian?.strategy ?? DEFAULT_LIBRARIAN_STRATEGY;
4251
- }
4252
- function resolveMaintenanceMode(config) {
4253
- return config?.maintenance ?? DEFAULT_MAINTENANCE_MODE;
4254
- }
4255
- var warnedDefaults = /* @__PURE__ */ new Set();
4256
- function warnOnce(message) {
4257
- if (warnedDefaults.has(message)) return;
4258
- warnedDefaults.add(message);
4259
- console.warn(message);
4260
- }
4261
- function formatConfigValue(value) {
4262
- try {
4263
- const json = JSON.stringify(value);
4264
- return json ?? String(value);
4265
- } catch {
4266
- return `[unserializable: ${typeof value}]`;
4267
- }
4268
- }
4269
- var isTypingMode = (v) => v === "auto" || v === "llm";
4270
- var isConfidenceFloor = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1;
4271
- function resolveSystemOneTyping(config, classifierCallOption) {
4272
- const systemOne = config?.systemOne;
4273
- const legacy = config?.ontology?.backfillClassifier;
4274
- const systemOneValid = isTypingMode(systemOne?.typing);
4275
- const legacyValid = isTypingMode(legacy);
4276
- if (systemOne?.typing !== void 0 && !systemOneValid) {
4277
- warnOnce(
4278
- `[core-llm-wiki] systemOne: \`systemOne.typing\` is ${formatConfigValue(systemOne.typing)}, which is not 'auto' or 'llm'. The key is treated as unset; the default ('llm') applies.`
4279
- );
4280
- }
4281
- if (legacy !== void 0 && !legacyValid) {
4282
- warnOnce(
4283
- `[core-llm-wiki] systemOne: \`ontology.backfillClassifier\` is ${formatConfigValue(legacy)}, which is not 'auto' or 'llm'. The key is treated as unset; the default ('llm') applies.`
4284
- );
4285
- }
4286
- if (systemOneValid && legacyValid && systemOne.typing !== legacy) {
4287
- warnOnce(
4288
- `[core-llm-wiki] systemOne: \`systemOne.typing\` (${systemOne.typing}) and \`ontology.backfillClassifier\` (${legacy}) disagree; \`systemOne.typing\` wins. Remove the legacy key to silence this warning.`
4289
- );
4290
- }
4291
- return classifierCallOption ?? (systemOneValid ? systemOne.typing : void 0) ?? (legacyValid ? legacy : void 0) ?? "llm";
4292
- }
4293
- function resolveSystemOneEdges(config) {
4294
- const edges = config?.systemOne?.edges;
4295
- if (edges !== void 0 && !isTypingMode(edges)) {
4296
- warnOnce(
4297
- `[core-llm-wiki] systemOne: \`systemOne.edges\` is ${formatConfigValue(edges)}, which is not 'auto' or 'llm'. The key is treated as unset; the default ('llm') applies.`
4298
- );
4299
- return "llm";
4300
- }
4301
- return edges ?? "llm";
4302
- }
4303
- function resolveSystemOneResolve(config) {
4304
- const resolve = config?.systemOne?.resolve;
4305
- if (resolve !== void 0 && !isTypingMode(resolve)) {
4306
- warnOnce(
4307
- `[core-llm-wiki] systemOne: \`systemOne.resolve\` is ${formatConfigValue(resolve)}, which is not 'auto' or 'llm'. The key is treated as unset; the default ('llm') applies.`
4308
- );
4309
- return "llm";
4310
- }
4311
- return resolve ?? "llm";
4312
- }
4313
- var DEFAULT_SHORTLIST_K = 10;
4314
- function resolveShortlistK(config) {
4315
- const k = config?.ontology?.shortlistK;
4316
- if (k === void 0) return DEFAULT_SHORTLIST_K;
4317
- if (typeof k !== "number" || !Number.isInteger(k) || k < 1) {
4318
- throw new Error(
4319
- `[core-llm-wiki] \`ontology.shortlistK\` is ${formatConfigValue(k)}, which is not a finite integer >= 1.`
4320
- );
4321
- }
4322
- return k;
4323
- }
4324
- var DEFAULT_TYPING_MIN_CONFIDENCE = 0.5;
4325
- function resolveTypingMinConfidence(config) {
4326
- const systemOneFloor = config?.systemOne?.minConfidence?.typing;
4327
- const legacyFloor = config?.ontology?.classifyMinConfidence;
4328
- const systemOneValid = isConfidenceFloor(systemOneFloor);
4329
- const legacyValid = isConfidenceFloor(legacyFloor);
4330
- if (systemOneFloor !== void 0 && !systemOneValid) {
4331
- warnOnce(
4332
- `[core-llm-wiki] systemOne: \`systemOne.minConfidence.typing\` is ${formatConfigValue(systemOneFloor)}, which is not a finite number in [0, 1]. The key is treated as unset and the chain continues.`
4333
- );
4334
- }
4335
- if (legacyFloor !== void 0 && !legacyValid) {
4336
- warnOnce(
4337
- `[core-llm-wiki] systemOne: \`ontology.classifyMinConfidence\` is ${formatConfigValue(legacyFloor)}, which is not a finite number in [0, 1]. The key is treated as unset and the chain continues.`
4338
- );
4339
- }
4340
- return (systemOneValid ? systemOneFloor : void 0) ?? (legacyValid ? legacyFloor : void 0) ?? DEFAULT_TYPING_MIN_CONFIDENCE;
4341
- }
4342
- var isEdgesFloor = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0.5 && v <= 1;
4343
- function resolveEdgesMinConfidence(config) {
4344
- if (resolveSystemOneEdges(config) !== "auto") return void 0;
4345
- const floor = config?.systemOne?.minConfidence?.edges;
4346
- if (isEdgesFloor(floor)) return floor;
4347
- warnOnce(
4348
- floor === void 0 ? "[core-llm-wiki] systemOne: `systemOne.minConfidence.edges` is required when `systemOne.edges` is 'auto'. The edge screen is off for this site; edges stay on the generative path." : `[core-llm-wiki] systemOne: \`systemOne.minConfidence.edges\` is ${formatConfigValue(floor)}, which is not a finite number in [0.5, 1]. The edge screen is off for this site; edges stay on the generative path.`
4349
- );
4350
- return void 0;
4351
- }
4352
- function resolveResolveMinConfidence(config) {
4353
- if (resolveSystemOneResolve(config) !== "auto") return void 0;
4354
- const floor = config?.systemOne?.minConfidence?.resolve;
4355
- if (isEdgesFloor(floor)) return floor;
4356
- warnOnce(
4357
- floor === void 0 ? "[core-llm-wiki] systemOne: `systemOne.minConfidence.resolve` is required when `systemOne.resolve` is 'auto'. A wrong NOOP drops a live fact, so there is no default floor. The resolution screen is off; resolution stays on the generative path." : `[core-llm-wiki] systemOne: \`systemOne.minConfidence.resolve\` is ${formatConfigValue(floor)}, which is not a finite number in [0.5, 1]. A wrong NOOP drops a live fact, so the resolution screen is off; resolution stays on the generative path.`
4358
- );
4359
- return void 0;
4360
- }
4361
- function resolveSystemOneHealScreen(config) {
4362
- const healScreen = config?.systemOne?.healScreen;
4363
- if (healScreen !== void 0 && !isTypingMode(healScreen)) {
4364
- warnOnce(
4365
- `[core-llm-wiki] systemOne: \`systemOne.healScreen\` is ${formatConfigValue(healScreen)}, which is not 'auto' or 'llm'. The key is treated as unset; the default ('llm') applies.`
4366
- );
4367
- return "llm";
4368
- }
4369
- return healScreen ?? "llm";
4370
- }
4371
- function resolveSystemOneTypeOnWrite(config) {
4372
- const typeOnWrite = config?.systemOne?.typeOnWrite;
4373
- if (typeOnWrite !== void 0 && !isTypingMode(typeOnWrite)) {
4374
- warnOnce(
4375
- `[core-llm-wiki] systemOne: \`systemOne.typeOnWrite\` is ${formatConfigValue(typeOnWrite)}, which is not 'auto' or 'llm'. The key is treated as unset; the default ('llm') applies.`
4376
- );
4377
- return "llm";
4378
- }
4379
- return typeOnWrite ?? "llm";
4380
- }
4381
- function resolveHealScreenMinConfidence(config) {
4382
- if (resolveSystemOneHealScreen(config) !== "auto") return void 0;
4383
- const floor = config?.systemOne?.minConfidence?.healScreen;
4384
- if (isEdgesFloor(floor)) return floor;
4385
- warnOnce(
4386
- floor === void 0 ? "[core-llm-wiki] systemOne: `systemOne.minConfidence.healScreen` is required when `systemOne.healScreen` is 'auto'. The heal screen is off for this site; heal stays ungated." : `[core-llm-wiki] systemOne: \`systemOne.minConfidence.healScreen\` is ${formatConfigValue(floor)}, which is not a finite number in [0.5, 1]. The heal screen is off for this site; heal stays ungated.`
4387
- );
4388
- return void 0;
4389
- }
4760
+ async history(entityId, factId) {
4761
+ const start = await this.entryRepo.findTemporalRow(factId);
4762
+ if (!start || start.entity_id !== entityId || start.deleted_at != null) return [];
4763
+ const { predecessors, successors } = await this.entryRepo.findSupersessionChainIds(entityId, factId, HISTORY_MAX_DEPTH);
4764
+ const facts = await this.entryRepo.findByIds([...predecessors.map((r) => r.id), factId, ...successors.map((r) => r.id)], [entityId]);
4765
+ return facts.sort((a, b) => (a.valid_from ?? a.created_at) - (b.valid_from ?? b.created_at) || a.created_at - b.created_at || a.id.localeCompare(b.id));
4766
+ }
4767
+ };
4390
4768
 
4391
4769
  // src/utils/embedding.ts
4392
4770
  function parseEmbedding(blob, text) {
@@ -4507,257 +4885,97 @@ var EdgeRepository = class extends BaseRepository {
4507
4885
  if (opts.edgeTypes && opts.edgeTypes.length === 0) {
4508
4886
  const anchor = await executor.getFirstAsync(
4509
4887
  `SELECT id FROM ${this.prefix}entries WHERE id = ? AND entity_id = ? AND deleted_at IS NULL`,
4510
- [sourceId, entityId]
4511
- );
4512
- return { nodeIds: anchor ? [anchor.id] : [], edges: [] };
4513
- }
4514
- const edgeTypesClause = opts.edgeTypes ? `e.edge_type IN (${opts.edgeTypes.map(() => "?").join(",")})` : "1=1";
4515
- const excludeSourceTypesPlaceholders = opts.excludeSourceTypes.map(() => "?").join(",");
4516
- const minConfidenceRank = CONFIDENCE_RANK[opts.minConfidence];
4517
- const sql = `
4518
- WITH RECURSIVE walk(node_id, depth, visited) AS (
4519
- SELECT id, 0, ',' || id || ','
4520
- FROM ${this.prefix}entries
4521
- WHERE id = ? AND entity_id = ? AND deleted_at IS NULL
4522
-
4523
- UNION
4524
-
4525
- SELECT
4526
- CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END,
4527
- w.depth + 1,
4528
- w.visited || (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END) || ','
4529
- FROM walk w
4530
- JOIN ${this.prefix}edges e
4531
- ON e.entity_id = ?
4532
- AND (
4533
- (? != 'inbound' AND e.source_id = w.node_id) OR
4534
- (? != 'outbound' AND e.target_id = w.node_id)
4535
- )
4536
- AND (${edgeTypesClause})
4537
- JOIN ${this.prefix}entries n
4538
- ON n.id = (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END)
4539
- AND n.entity_id = ?
4540
- AND n.deleted_at IS NULL
4541
- AND (
4542
- CASE n.confidence
4543
- WHEN 'tentative' THEN 0
4544
- WHEN 'inferred' THEN 1
4545
- WHEN 'certain' THEN 2
4546
- ELSE -1
4547
- END
4548
- ) >= ?
4549
- AND n.source_type NOT IN (${excludeSourceTypesPlaceholders})
4550
- AND (? = 0 OR n.lifecycle_status != 'draft')
4551
- AND ${liveAtSql(opts.live.mode, "n.")}
4552
- WHERE w.depth < ?
4553
- AND instr(w.visited, ',' || (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END) || ',') = 0
4554
- )
4555
- SELECT node_id, MIN(depth) AS depth
4556
- FROM walk
4557
- GROUP BY node_id
4558
- ORDER BY depth ASC, (SELECT updated_at FROM ${this.prefix}entries WHERE id = node_id) DESC
4559
- LIMIT ?
4560
- `;
4561
- const params = [
4562
- sourceId,
4563
- entityId,
4564
- entityId,
4565
- opts.direction,
4566
- opts.direction,
4567
- ...opts.edgeTypes ?? [],
4568
- entityId,
4569
- minConfidenceRank,
4570
- ...opts.excludeSourceTypes,
4571
- opts.excludeDrafts === true ? 1 : 0,
4572
- opts.live.t,
4573
- opts.live.t,
4574
- opts.maxDepth,
4575
- opts.maxNodes
4576
- ];
4577
- const rows = await executor.getAllAsync(sql, params);
4578
- const nodeIds = rows.map((r) => r.node_id);
4579
- if (nodeIds.length === 0) return { nodeIds: [], edges: [] };
4580
- const valueRows = nodeIds.map(() => "(?)").join(", ");
4581
- const edgeRows = await executor.getAllAsync(
4582
- `WITH neighborhood(node_id) AS (VALUES ${valueRows})
4583
- SELECT e.* FROM ${this.prefix}edges e
4584
- JOIN neighborhood ns ON e.source_id = ns.node_id
4585
- JOIN neighborhood nt ON e.target_id = nt.node_id
4586
- WHERE e.entity_id = ?`,
4587
- [...nodeIds, entityId]
4588
- );
4589
- return { nodeIds, edges: edgeRows.map(mapRowToEdge) };
4590
- }
4591
- };
4592
- function mapRowToEdge(row) {
4593
- return {
4594
- id: String(row.id),
4595
- entity_id: String(row.entity_id),
4596
- source_id: String(row.source_id),
4597
- target_id: String(row.target_id),
4598
- edge_type: String(row.edge_type),
4599
- created_at: Number(row.created_at)
4600
- };
4601
- }
4602
-
4603
- // src/services/BoundedLlmCall.ts
4604
- var DEFAULT_BATCH_SIZE = 10;
4605
- var ESTIMATED_OUTPUT_TOKENS_PER_ITEM = 150;
4606
- var OUTPUT_BUDGET_FRACTION = 0.8;
4607
- var TRUNCATION_PATTERNS = [
4608
- /truncat/i,
4609
- /token limit/i,
4610
- /max(imum)?[ _-]?tokens?/i,
4611
- /output limit/i,
4612
- /length limit/i,
4613
- /finish[_ ]?reason/i
4614
- ];
4615
- var EXCEEDS_LIMIT_PATTERN = /exceed[a-z]*[^.]{0,40}\b(model|context)?[ _-]?limit/i;
4616
- var RATE_LIMIT_PATTERN = /\b(?:status|http|code|error)[^\d]{0,10}429\b|\b429[ _-]?too[ _-]?many[ _-]?requests\b|\b(rate[ _-]?limit|too many requests|(tokens?|requests?)[ _-]?per[ _-]?(minute|min)\b|retry[ _-]?after|quota exceeded)\b/i;
4617
- var CONTEXT_OVERFLOW_PATTERNS = [
4618
- /maximum context length/i,
4619
- /context[_ ]?length[_ ]?exceeded/i,
4620
- /prompt is too long/i,
4621
- /input (token count|is too long)/i,
4622
- /exceeds? the (available )?context( size)?/i,
4623
- // Tail requires a context-window clause (context|maximum), NOT bare `token`:
4624
- // a 429 body like "input exceeds the tokens-per-minute limit" must NOT
4625
- // classify as input overflow (it would split the batch and stamp a cooldown).
4626
- /(input|prompt).{0,40}exceed(s|ed)? .{0,30}(context|maximum)/i,
4627
- /context limit/i,
4628
- // llama.rn (RNLlamaJSI.cpp): prompt >= n_ctx with ctx_shift off
4629
- /\bcontext is full\b/i,
4630
- /too long for (the )?requested model/i,
4631
- // vLLM dual-match wording (errata E2 ruling): the regex ENFORCES the dual-match —
4632
- // "max_tokens ... too large" PLUS a context clause; a bare message is NOT overflow
4633
- /max[_ ]?tokens?.{0,40}too large.{0,80}context/i
4634
- ];
4635
- function isContextOverflowError(err) {
4636
- const message = getErrorMessage(err);
4637
- if (message === void 0) return false;
4638
- if (RATE_LIMIT_PATTERN.test(message)) return false;
4639
- return CONTEXT_OVERFLOW_PATTERNS.some((p) => p.test(message));
4640
- }
4641
- function getErrorMessage(err) {
4642
- try {
4643
- return err instanceof Error ? err.message : String(err ?? "");
4644
- } catch {
4645
- return void 0;
4646
- }
4647
- }
4648
- function isTruncationError(err) {
4649
- const message = getErrorMessage(err);
4650
- if (message === void 0) return false;
4651
- if (RATE_LIMIT_PATTERN.test(message)) return false;
4652
- if (EXCEEDS_LIMIT_PATTERN.test(message)) return false;
4653
- return TRUNCATION_PATTERNS.some((pattern) => pattern.test(message));
4654
- }
4655
- function isConfigError(err) {
4656
- const message = getErrorMessage(err);
4657
- if (message === void 0) return false;
4658
- if (RATE_LIMIT_PATTERN.test(message)) return false;
4659
- return EXCEEDS_LIMIT_PATTERN.test(message);
4660
- }
4661
- function initialBatchSize(maxOutputTokens) {
4662
- if (!maxOutputTokens || !Number.isFinite(maxOutputTokens) || maxOutputTokens <= 0) {
4663
- return DEFAULT_BATCH_SIZE;
4664
- }
4665
- const estimate = Math.floor(
4666
- maxOutputTokens * OUTPUT_BUDGET_FRACTION / ESTIMATED_OUTPUT_TOKENS_PER_ITEM
4667
- );
4668
- return Math.max(DEFAULT_BATCH_SIZE, estimate);
4669
- }
4670
- var promptLength = (prompts) => prompts.systemPrompt.length + prompts.userPrompt.length;
4671
- async function runBatched(args) {
4672
- const { items, buildPrompt, call, parse, maxPromptChars, maxOutputTokens, onSkip, supportsEscalation } = args;
4673
- const results = [];
4674
- const skipped = [];
4675
- let batches = 0;
4676
- const settled = /* @__PURE__ */ new Set();
4677
- let budgetStop;
4678
- let batchSize = initialBatchSize(maxOutputTokens);
4679
- const trim = async (candidate) => {
4680
- const whole = await buildPrompt(candidate);
4681
- if (candidate.length <= 1 || promptLength(whole) <= maxPromptChars) {
4682
- return { batch: candidate, prompts: whole };
4683
- }
4684
- let low = 2;
4685
- let high = candidate.length - 1;
4686
- let best;
4687
- let bestPrompts;
4688
- while (low <= high) {
4689
- const mid = Math.floor((low + high) / 2);
4690
- const batch = candidate.slice(0, mid);
4691
- const prompts = await buildPrompt(batch);
4692
- if (promptLength(prompts) <= maxPromptChars) {
4693
- best = batch;
4694
- bestPrompts = prompts;
4695
- low = mid + 1;
4696
- } else {
4697
- high = mid - 1;
4698
- }
4699
- }
4700
- if (best && bestPrompts) return { batch: best, prompts: bestPrompts };
4701
- const single = candidate.slice(0, 1);
4702
- return { batch: single, prompts: await buildPrompt(single) };
4703
- };
4704
- const onFailure = async (batch, err, attemptLevel, fromCall) => {
4705
- if (batch.length === 1) {
4706
- if (fromCall && (isContextOverflowError(err) ? supportsEscalation : isTruncationError(err)) && attemptLevel < 3) {
4707
- await attempt(batch, void 0, attemptLevel + 1);
4708
- } else {
4709
- const reason = fromCall && !isTruncationError(err) && !isConfigError(err) && !isContextOverflowError(err) ? "call_error" : "non_convergent";
4710
- skipped.push({ item: batch[0], reason });
4711
- settled.add(batch[0]);
4712
- onSkip?.(batch[0], err);
4713
- }
4714
- return;
4715
- }
4716
- if (fromCall && !isTruncationError(err) && !isContextOverflowError(err)) throw err;
4717
- const mid = Math.ceil(batch.length / 2);
4718
- if (mid < batchSize) batchSize = mid;
4719
- let i = 0;
4720
- while (i < batch.length && !budgetStop) {
4721
- const size = Math.min(batchSize, batch.length - i);
4722
- const trimmed = await trim(batch.slice(i, i + size));
4723
- await attempt(trimmed.batch, trimmed.prompts);
4724
- i += trimmed.batch.length;
4725
- }
4726
- };
4727
- const attempt = async (batch, prebuilt, attemptLevel = 0) => {
4728
- if (budgetStop) return;
4729
- if (batch.length === 0) return;
4730
- const prompts = prebuilt && attemptLevel === 0 ? prebuilt : await buildPrompt(batch, attemptLevel);
4731
- batches++;
4732
- let responseText;
4733
- try {
4734
- responseText = await call(prompts);
4735
- } catch (err) {
4736
- if (err instanceof WikiBudgetExhausted) {
4737
- budgetStop = { requiredEstimate: err.requiredEstimate };
4738
- return;
4739
- }
4740
- await onFailure(batch, err, attemptLevel, true);
4741
- return;
4742
- }
4743
- let result;
4744
- try {
4745
- result = parse(responseText, batch, prompts);
4746
- } catch (err) {
4747
- await onFailure(batch, err, attemptLevel, false);
4748
- return;
4749
- }
4750
- results.push(result);
4751
- for (const item of batch) settled.add(item);
4752
- };
4753
- let index = 0;
4754
- while (index < items.length && !budgetStop) {
4755
- const { batch, prompts } = await trim(items.slice(index, index + batchSize));
4756
- index += batch.length;
4757
- await attempt(batch, prompts, 0);
4888
+ [sourceId, entityId]
4889
+ );
4890
+ return { nodeIds: anchor ? [anchor.id] : [], edges: [] };
4891
+ }
4892
+ const edgeTypesClause = opts.edgeTypes ? `e.edge_type IN (${opts.edgeTypes.map(() => "?").join(",")})` : "1=1";
4893
+ const excludeSourceTypesPlaceholders = opts.excludeSourceTypes.map(() => "?").join(",");
4894
+ const minConfidenceRank = CONFIDENCE_RANK[opts.minConfidence];
4895
+ const sql = `
4896
+ WITH RECURSIVE walk(node_id, depth, visited) AS (
4897
+ SELECT id, 0, ',' || id || ','
4898
+ FROM ${this.prefix}entries
4899
+ WHERE id = ? AND entity_id = ? AND deleted_at IS NULL
4900
+
4901
+ UNION
4902
+
4903
+ SELECT
4904
+ CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END,
4905
+ w.depth + 1,
4906
+ w.visited || (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END) || ','
4907
+ FROM walk w
4908
+ JOIN ${this.prefix}edges e
4909
+ ON e.entity_id = ?
4910
+ AND (
4911
+ (? != 'inbound' AND e.source_id = w.node_id) OR
4912
+ (? != 'outbound' AND e.target_id = w.node_id)
4913
+ )
4914
+ AND (${edgeTypesClause})
4915
+ JOIN ${this.prefix}entries n
4916
+ ON n.id = (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END)
4917
+ AND n.entity_id = ?
4918
+ AND n.deleted_at IS NULL
4919
+ AND (
4920
+ CASE n.confidence
4921
+ WHEN 'tentative' THEN 0
4922
+ WHEN 'inferred' THEN 1
4923
+ WHEN 'certain' THEN 2
4924
+ ELSE -1
4925
+ END
4926
+ ) >= ?
4927
+ AND n.source_type NOT IN (${excludeSourceTypesPlaceholders})
4928
+ AND (? = 0 OR n.lifecycle_status != 'draft')
4929
+ AND ${liveAtSql(opts.live.mode, "n.")}
4930
+ WHERE w.depth < ?
4931
+ AND instr(w.visited, ',' || (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END) || ',') = 0
4932
+ )
4933
+ SELECT node_id, MIN(depth) AS depth
4934
+ FROM walk
4935
+ GROUP BY node_id
4936
+ ORDER BY depth ASC, (SELECT updated_at FROM ${this.prefix}entries WHERE id = node_id) DESC
4937
+ LIMIT ?
4938
+ `;
4939
+ const params = [
4940
+ sourceId,
4941
+ entityId,
4942
+ entityId,
4943
+ opts.direction,
4944
+ opts.direction,
4945
+ ...opts.edgeTypes ?? [],
4946
+ entityId,
4947
+ minConfidenceRank,
4948
+ ...opts.excludeSourceTypes,
4949
+ opts.excludeDrafts === true ? 1 : 0,
4950
+ opts.live.t,
4951
+ opts.live.t,
4952
+ opts.maxDepth,
4953
+ opts.maxNodes
4954
+ ];
4955
+ const rows = await executor.getAllAsync(sql, params);
4956
+ const nodeIds = rows.map((r) => r.node_id);
4957
+ if (nodeIds.length === 0) return { nodeIds: [], edges: [] };
4958
+ const valueRows = nodeIds.map(() => "(?)").join(", ");
4959
+ const edgeRows = await executor.getAllAsync(
4960
+ `WITH neighborhood(node_id) AS (VALUES ${valueRows})
4961
+ SELECT e.* FROM ${this.prefix}edges e
4962
+ JOIN neighborhood ns ON e.source_id = ns.node_id
4963
+ JOIN neighborhood nt ON e.target_id = nt.node_id
4964
+ WHERE e.entity_id = ?`,
4965
+ [...nodeIds, entityId]
4966
+ );
4967
+ return { nodeIds, edges: edgeRows.map(mapRowToEdge) };
4758
4968
  }
4759
- const unattempted = budgetStop ? items.filter((item) => !settled.has(item)) : [];
4760
- return { results, skipped, batches, unattempted, ...budgetStop ? { budgetStop } : {} };
4969
+ };
4970
+ function mapRowToEdge(row) {
4971
+ return {
4972
+ id: String(row.id),
4973
+ entity_id: String(row.entity_id),
4974
+ source_id: String(row.source_id),
4975
+ target_id: String(row.target_id),
4976
+ edge_type: String(row.edge_type),
4977
+ created_at: Number(row.created_at)
4978
+ };
4761
4979
  }
4762
4980
 
4763
4981
  // src/db/schema.ts
@@ -5201,8 +5419,27 @@ var MIGRATIONS = [
5201
5419
  await addPriorValidToColumn(db, prefix);
5202
5420
  await addDerivedEventsColumn(db, prefix);
5203
5421
  }
5422
+ },
5423
+ {
5424
+ version: 19,
5425
+ description: "Nullable events.forgotten_at column and partial index marking events the host forgot with forget({ eventId }) (specs/forget-event-exclusion)",
5426
+ run: async (db, prefix) => {
5427
+ await addEventsForgottenAtColumn(db, prefix);
5428
+ await createEventsForgottenIndex(db, prefix);
5429
+ }
5204
5430
  }
5205
5431
  ];
5432
+ async function addEventsForgottenAtColumn(db, prefix) {
5433
+ const cols = await db.getAllAsync(`PRAGMA table_info(${prefix}events)`);
5434
+ if (!cols.some((c) => c.name === "forgotten_at")) {
5435
+ await db.execAsync(`ALTER TABLE ${prefix}events ADD COLUMN forgotten_at INTEGER`);
5436
+ }
5437
+ }
5438
+ async function createEventsForgottenIndex(db, prefix) {
5439
+ await db.execAsync(
5440
+ `CREATE INDEX IF NOT EXISTS ${prefix}events_forgotten_idx ON ${prefix}events(entity_id, forgotten_at) WHERE forgotten_at IS NOT NULL`
5441
+ );
5442
+ }
5206
5443
  async function addPriorValidToColumn(db, prefix) {
5207
5444
  const cols = await db.getAllAsync(`PRAGMA table_info(${prefix}entries)`);
5208
5445
  if (!cols.some((c) => c.name === "prior_valid_to")) {
@@ -5257,152 +5494,6 @@ async function restartRebuildAfterVacuum(db, prefix, meta) {
5257
5494
  });
5258
5495
  }
5259
5496
 
5260
- // src/services/typing/typeOnWrite.ts
5261
- var CLASSIFIER_MAX_CHOICES = 255;
5262
- function isManifestRepresentable(manifest) {
5263
- const slugs = manifest.node_types.map((n) => n.type);
5264
- return slugs.length > 0 && slugs.length + 1 <= CLASSIFIER_MAX_CHOICES && !slugs.some((s) => isReservedAbstainSlug(s));
5265
- }
5266
- function canEngageWriteTyping(config, provider, mode, manifest) {
5267
- return resolveSystemOneTypeOnWrite(config) === "auto" && typeof provider.classify === "function" && mode !== "off" && isManifestRepresentable(manifest);
5268
- }
5269
- function buildTypingQuestion(manifest) {
5270
- return {
5271
- kind: "choice",
5272
- options: [...manifest.node_types.map((n) => n.type), ONTOLOGY_ABSTAIN_SENTINEL],
5273
- instructions: `Choose the ontology node type that best describes this fact, or choose "${ONTOLOGY_ABSTAIN_SENTINEL}" if none of the listed types fits.
5274
- ` + manifest.node_types.map((n) => `- ${n.type}: ${n.description}`).join("\n")
5275
- };
5276
- }
5277
- function volunteeredTypeResolves(rawOkfType, manifest) {
5278
- return typeof rawOkfType === "string" && resolveNodeTypeMatch(rawOkfType, manifest) !== null;
5279
- }
5280
- async function classifyFactsForWrite(options, ctx, facts, manifest, floor) {
5281
- const question = buildTypingQuestion(manifest);
5282
- const rawConcurrency = options.config?.chunkConcurrency ?? 1;
5283
- const concurrency = Number.isFinite(rawConcurrency) && rawConcurrency >= 1 ? Math.floor(rawConcurrency) : 1;
5284
- let stopped = false;
5285
- return withConcurrency(
5286
- facts.map((fact) => async () => {
5287
- if (stopped) return { kind: "unattempted" };
5288
- let response;
5289
- try {
5290
- response = await callClassify(
5291
- options,
5292
- { operation: ctx.operation, entityId: ctx.entityId, trigger: ctx.trigger, meter: ctx.meter },
5293
- { state: classifierStateForFact(fact), questions: { okf_type: question } }
5294
- );
5295
- } catch (err) {
5296
- if (err instanceof WikiBudgetExhausted) {
5297
- stopped = true;
5298
- return { kind: "unattempted" };
5299
- }
5300
- if (isContextOverflowError(err)) return { kind: "overflow_skip" };
5301
- return { kind: "threw" };
5302
- }
5303
- const checked = validateClassifierAnswer(response, "okf_type", question);
5304
- if (!checked.ok) return { kind: "invalid", reason: checked.reason };
5305
- if (checked.answer.kind !== "choice") return { kind: "invalid", reason: "kind_mismatch" };
5306
- if (isReservedAbstainSlug(checked.answer.choice)) return { kind: "abstain" };
5307
- if (checked.answer.confidence < floor) return { kind: "low_confidence" };
5308
- return { kind: "accepted", okfType: checked.answer.choice, confidence: checked.answer.confidence };
5309
- }),
5310
- concurrency
5311
- );
5312
- }
5313
- function emptyTypingCounters() {
5314
- return { asked: 0, typed: 0, abstained: 0, lowConfidence: 0, invalid: 0, skipped: 0, unattempted: 0 };
5315
- }
5316
- function tallyTypingOutcome(c, o) {
5317
- switch (o.kind) {
5318
- case "unattempted":
5319
- c.unattempted++;
5320
- return;
5321
- case "accepted":
5322
- c.asked++;
5323
- return;
5324
- case "abstain":
5325
- c.asked++;
5326
- c.abstained++;
5327
- return;
5328
- case "low_confidence":
5329
- c.asked++;
5330
- c.lowConfidence++;
5331
- return;
5332
- case "invalid":
5333
- case "threw":
5334
- c.asked++;
5335
- c.invalid++;
5336
- return;
5337
- case "overflow_skip":
5338
- c.asked++;
5339
- c.skipped++;
5340
- return;
5341
- }
5342
- }
5343
- function typingOutcomeReceipt(base, factId, outcome) {
5344
- switch (outcome.kind) {
5345
- case "abstain":
5346
- return { ...base, code: "classification_abstained", detail: { factId, writer: "classifier" } };
5347
- case "low_confidence":
5348
- return { ...base, code: "classification_low_confidence", detail: { factId, reason: "below_threshold" } };
5349
- case "invalid":
5350
- return { ...base, code: "classification_invalid", detail: { factId, reason: outcome.reason } };
5351
- case "threw":
5352
- return { ...base, code: "classification_invalid", detail: { factId, reason: "classify_threw" } };
5353
- case "overflow_skip":
5354
- return { ...base, code: "context_overflow_skipped", detail: { factId } };
5355
- default:
5356
- return null;
5357
- }
5358
- }
5359
- function normalizeForWrite(ontology, fact, manifest, mode, outcome, base, factId) {
5360
- const drops = [];
5361
- const receipts = [];
5362
- const emit = shouldEmitOntologyReceipt(mode);
5363
- let normalized = ontology?.validateAndNormalizeFact(fact, manifest, { strict: false, drops }) ?? { okf_type: null, edges: [] };
5364
- if (emit) {
5365
- receipts.push(...nodeTypeReceipts(
5366
- base,
5367
- factId,
5368
- typeof fact.okf_type === "string" ? fact.okf_type : "",
5369
- normalized.okf_type,
5370
- normalized.match
5371
- ));
5372
- }
5373
- let typedByClassifier = false;
5374
- if (!normalized.okf_type && outcome?.kind === "accepted" && mode !== "off") {
5375
- const second = ontology?.validateAndNormalizeFact(
5376
- { ...fact, okf_type: outcome.okfType, edges: [] },
5377
- manifest,
5378
- { strict: false }
5379
- ) ?? { okf_type: null};
5380
- if (emit) {
5381
- receipts.push(...nodeTypeReceipts(base, factId, outcome.okfType, second.okf_type, second.match));
5382
- }
5383
- normalized = { okf_type: second.okf_type, edges: [] };
5384
- if (second.okf_type) {
5385
- typedByClassifier = true;
5386
- if (emit) {
5387
- receipts.push({
5388
- ...base,
5389
- code: "node_type_assigned",
5390
- detail: { factId, okfType: second.okf_type, writer: "classifier", confidence: outcome.confidence }
5391
- });
5392
- }
5393
- }
5394
- } else if (normalized.okf_type) {
5395
- if (emit) {
5396
- receipts.push({ ...base, code: "node_type_assigned", detail: { factId, okfType: normalized.okf_type, writer: "llm" } });
5397
- }
5398
- }
5399
- if (outcome && outcome.kind !== "accepted" && emit && !normalized.okf_type) {
5400
- const r = typingOutcomeReceipt(base, factId, outcome);
5401
- if (r) receipts.push(r);
5402
- }
5403
- return { normalized, drops, receipts, typedByClassifier };
5404
- }
5405
-
5406
5497
  // src/services/librarian/constants.ts
5407
5498
  var FUZZY_THRESHOLD = 0.5;
5408
5499
  var MIN_TOKENS_TO_QUALIFY = 3;
@@ -5412,6 +5503,9 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
5412
5503
  const { entityId, trigger } = ctx;
5413
5504
  const promptOverride = ctx.promptOverride;
5414
5505
  const events = await deps.eventRepo.getRecent(entityId, 50);
5506
+ if (events.length === 0 && await deps.eventRepo.count(entityId) > 0) {
5507
+ return { processedThrough: null, factsWritten: 0 };
5508
+ }
5415
5509
  const currentFactsRows = await deps.entryRepo.findRecentByEntityId(entityId, 100);
5416
5510
  const currentFacts = currentFactsRows.map((f) => {
5417
5511
  const { embedding: _embedding, embedding_blob: _blob, ...rest } = f;
@@ -6242,12 +6336,18 @@ async function applyOps(deps, ctx, input) {
6242
6336
  return id;
6243
6337
  };
6244
6338
  const sourceIds = [...new Set(input.gated.map((g) => g.candidate.sourceEventId).filter((x) => x !== null))];
6245
- const presentIds = sourceIds.length > 0 ? await deps.eventRepo.findExistingIds(entityId, sourceIds, tx) : /* @__PURE__ */ new Set();
6339
+ const presentIds = sourceIds.length > 0 ? await deps.eventRepo.findLiveIds(entityId, sourceIds, tx) : /* @__PURE__ */ new Set();
6340
+ const failedIds = sourceIds.filter((id) => !presentIds.has(id));
6341
+ const stillExist = failedIds.length > 0 ? await deps.eventRepo.findExistingIds(entityId, failedIds, tx) : /* @__PURE__ */ new Set();
6246
6342
  const gatedLive = [];
6247
6343
  for (const g of input.gated) {
6248
6344
  const ev = g.candidate.sourceEventId;
6249
6345
  if (ev !== null && !presentIds.has(ev)) {
6250
- input.diagnostics.push({ ...diagBase, code: "source_event_gone", detail: { itemIndex: g.candidate.index, sourceRef: ev } });
6346
+ input.diagnostics.push({
6347
+ ...diagBase,
6348
+ code: "source_event_gone",
6349
+ detail: { itemIndex: g.candidate.index, sourceRef: ev, reason: stillExist.has(ev) ? "forgotten" : "gone" }
6350
+ });
6251
6351
  continue;
6252
6352
  }
6253
6353
  gatedLive.push(g);
@@ -6689,6 +6789,21 @@ var _MaintenanceService = class _MaintenanceService {
6689
6789
  }
6690
6790
  }
6691
6791
  deletedTasks = await this.taskRepo.bulkDeletePruned(entityId, cutoff, tx, { noCutoff: softDeletedAll });
6792
+ const delOpts = { noCutoff: softDeletedAll };
6793
+ const hasForgottenCol = await this.metadataRepo.columnExists(`${this.prefix}events`, "forgotten_at", tx) && await this.eventRepo.hasDeletableForgotten(entityId, cutoff, tx, delOpts);
6794
+ const cpBefore = hasForgottenCol ? await this.metadataRepo.getCheckpoint(entityId, tx) : null;
6795
+ const memDrop = cpBefore && (cpBefore.memory ?? 0) > 0 ? await this.eventRepo.countForgottenInPrefix(entityId, cpBefore.memory, cutoff, tx, delOpts) : 0;
6796
+ const healDrop = cpBefore && (cpBefore.heal ?? 0) > 0 ? await this.eventRepo.countForgottenInPrefix(entityId, cpBefore.heal, cutoff, tx, delOpts) : 0;
6797
+ const forgottenGone = hasForgottenCol ? (await this.eventRepo.deleteForgotten(entityId, cutoff, tx, delOpts)).changes : 0;
6798
+ if (forgottenGone > 0) {
6799
+ deletedEvents += forgottenGone;
6800
+ const updates = {};
6801
+ if (memDrop > 0) updates.memory = Math.max(0, cpBefore.memory - memDrop);
6802
+ if (healDrop > 0) updates.heal = Math.max(0, cpBefore.heal - healDrop);
6803
+ if (updates.memory !== void 0 || updates.heal !== void 0) {
6804
+ await this.metadataRepo.updateCheckpoint(entityId, updates, tx);
6805
+ }
6806
+ }
6692
6807
  });
6693
6808
  if (hookLedger) {
6694
6809
  const keptSet = new Set(kept);
@@ -6709,18 +6824,20 @@ var _MaintenanceService = class _MaintenanceService {
6709
6824
  const cutoff = now - retainEventsFor * 864e5;
6710
6825
  const guarded = resolveMaintenanceMode(this.options.config) === "deferred" || resolveLibrarianStrategy(this.options.config) === "ops";
6711
6826
  let wm = null;
6827
+ let retentionDeleted = 0;
6712
6828
  await this.db.withTransactionAsync(async (tx) => {
6713
6829
  if (guarded) {
6714
6830
  wm = await this.metadataRepo.getLibrarianWatermark(entityId, tx);
6715
- deletedEvents = (await this.eventRepo.pruneThrough(entityId, cutoff, wm, tx)).changes;
6831
+ retentionDeleted = (await this.eventRepo.pruneThrough(entityId, cutoff, wm, tx)).changes;
6716
6832
  } else {
6717
- deletedEvents = (await this.eventRepo.prune(entityId, cutoff, tx)).changes;
6833
+ retentionDeleted = (await this.eventRepo.prune(entityId, cutoff, tx)).changes;
6718
6834
  }
6719
- if (deletedEvents > 0) {
6835
+ deletedEvents += retentionDeleted;
6836
+ if (retentionDeleted > 0) {
6720
6837
  const cp = await this.metadataRepo.getCheckpoint(entityId, tx);
6721
6838
  const updates = {};
6722
- if ((cp.memory ?? 0) > 0) updates.memory = Math.max(0, cp.memory - deletedEvents);
6723
- if ((cp.heal ?? 0) > 0) updates.heal = Math.max(0, cp.heal - deletedEvents);
6839
+ if ((cp.memory ?? 0) > 0) updates.memory = Math.max(0, cp.memory - retentionDeleted);
6840
+ if ((cp.heal ?? 0) > 0) updates.heal = Math.max(0, cp.heal - retentionDeleted);
6724
6841
  if (updates.memory !== void 0 || updates.heal !== void 0) {
6725
6842
  await this.metadataRepo.updateCheckpoint(entityId, updates, tx);
6726
6843
  }
@@ -6928,9 +7045,11 @@ var _MaintenanceService = class _MaintenanceService {
6928
7045
  if (report.skipped.length === 0 && report.holds.length === 0) {
6929
7046
  let remainingTombstones;
6930
7047
  try {
7048
+ const eventsTracked = await this.metadataRepo.columnExists(`${this.prefix}events`, "forgotten_at");
6931
7049
  const row = await this.db.getFirstAsync(
6932
7050
  `SELECT (SELECT COUNT(*) FROM ${this.prefix}entries WHERE deleted_at IS NOT NULL)
6933
- + (SELECT COUNT(*) FROM ${this.prefix}tasks WHERE deleted_at IS NOT NULL) AS n`
7051
+ + (SELECT COUNT(*) FROM ${this.prefix}tasks WHERE deleted_at IS NOT NULL)
7052
+ ${eventsTracked ? `+ (SELECT COUNT(*) FROM ${this.prefix}events WHERE forgotten_at IS NOT NULL)` : ""} AS n`
6934
7053
  );
6935
7054
  remainingTombstones = row?.n ?? 0;
6936
7055
  } catch (err) {
@@ -7343,6 +7462,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
7343
7462
  let deletedEntries = 0;
7344
7463
  let deletedTasks = 0;
7345
7464
  let deletedEvents = 0;
7465
+ let eventMarked = 0;
7346
7466
  let chainIds = [];
7347
7467
  let chainTruncated = false;
7348
7468
  const deletedEntryIds = [];
@@ -7423,6 +7543,9 @@ DROP TRIGGER IF EXISTS ${ad};`);
7423
7543
  if (taskResult) deletedTasks++;
7424
7544
  deletedEntries += refResult;
7425
7545
  deletedEntries += pointerResult;
7546
+ if (params.eventId !== void 0) {
7547
+ eventMarked = await this.metadataRepo.columnExists(`${this.prefix}events`, "forgotten_at", tx) ? await this.eventRepo.markForgotten(entityId, params.eventId, now, tx) : 0;
7548
+ }
7426
7549
  }
7427
7550
  if (ledgerOn && this.vectorRemoval?.gate() === "hook" && deletedEntryIds.length > 0) {
7428
7551
  await this.vectorRemovalRepo?.backstopEnqueue(entityId, Array.from(new Set(deletedEntryIds)), now, tx);
@@ -7475,7 +7598,9 @@ DROP TRIGGER IF EXISTS ${ad};`);
7475
7598
  }
7476
7599
  }
7477
7600
  if (!params.clearAll) {
7478
- const base = { deleted: { entries: deletedEntries, tasks: deletedTasks } };
7601
+ const base = {
7602
+ deleted: params.eventId !== void 0 ? { entries: deletedEntries, tasks: deletedTasks, events: eventMarked } : { entries: deletedEntries, tasks: deletedTasks }
7603
+ };
7479
7604
  if (params.includeChain) {
7480
7605
  base.chainEntryIds = chainIds;
7481
7606
  if (chainTruncated) {
@@ -7581,7 +7706,8 @@ DROP TRIGGER IF EXISTS ${ad};`);
7581
7706
  }
7582
7707
  if (params.eventId !== void 0) {
7583
7708
  const entries2 = await this.entryRepo.countLiveByPointerEvent(entityId, params.eventId);
7584
- return { deleted: { entries: entries2, tasks: 0 } };
7709
+ const events = await this.metadataRepo.columnExists(`${this.prefix}events`, "forgotten_at") ? await this.eventRepo.countForgettable(entityId, params.eventId) : 0;
7710
+ return { deleted: { entries: entries2, tasks: 0, events } };
7585
7711
  }
7586
7712
  const sourceRef = params.sourceRef !== void 0 ? normalizeSourceRef(params.sourceRef) : null;
7587
7713
  if (params.sourceRef !== void 0 && !sourceRef) throw new Error("Invalid sourceRef");