@equationalapplications/core-llm-wiki 8.4.0 → 9.1.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
@@ -727,7 +727,11 @@ var SEVERITY = {
727
727
  event_created_at_clamped: "warn",
728
728
  event_created_at_restamped: "info",
729
729
  external_deletion_pending: "warn",
730
- external_deletion_discarded: "warn"
730
+ external_deletion_discarded: "warn",
731
+ guidance_too_long: "warn",
732
+ guidance_resolver_failed: "warn",
733
+ source_pointer_unresolved: "warn",
734
+ source_pointer_invalid: "warn"
731
735
  };
732
736
  var MESSAGE = {
733
737
  ingest_chunk_failed: "One or more document chunks failed to parse or generate.",
@@ -753,7 +757,11 @@ var MESSAGE = {
753
757
  event_created_at_clamped: "Imported events dated in the future were re-dated just after the current time, or after the librarian position if that is later, keeping their order.",
754
758
  event_created_at_restamped: "Imported events that would have sorted behind the librarian position, or had an unusable date, were adjusted: an affected created_at was re-dated just after the current time, or after the librarian position if that is later, keeping their order; an unusable occurred_at was cleared.",
755
759
  external_deletion_pending: "Removals owed to the external vector index are still pending.",
756
- external_deletion_discarded: "Pending external vector removals were discarded because forceDeleteIgnoreRankerHook is set."
760
+ external_deletion_discarded: "Pending external vector removals were discarded because forceDeleteIgnoreRankerHook is set.",
761
+ guidance_too_long: "The configured guidance exceeded the length cap and was not sent for this pass.",
762
+ guidance_resolver_failed: "The per-entity guidance resolver failed; its value was not used for this pass.",
763
+ source_pointer_unresolved: "A stored librarian fact carries no source pointer because the model answer could not yield one.",
764
+ source_pointer_invalid: "Import met a malformed source pointer value and stored a null pointer."
757
765
  };
758
766
  var warnedNonFunction = /* @__PURE__ */ new WeakSet();
759
767
  function copyDetail(detail) {
@@ -1234,6 +1242,44 @@ function entitySummaryMetaKey(entityId) {
1234
1242
  }
1235
1243
  var START_OF_LOG_WATERMARK = Object.freeze({ at: Number.MIN_SAFE_INTEGER, id: "" });
1236
1244
 
1245
+ // src/utils/sourcePointer.ts
1246
+ var POINTER_SLOTS = ["event_id", "ref", "quote", "position"];
1247
+ function isStringOrNull(v) {
1248
+ return v === null || typeof v === "string";
1249
+ }
1250
+ function isValidPosition(v) {
1251
+ if (v === null) return true;
1252
+ if (typeof v !== "object" || v === null || Array.isArray(v)) return false;
1253
+ const o = v;
1254
+ const keys = Object.keys(o);
1255
+ if (keys.length !== 2 || !("start" in o) || !("length" in o)) return false;
1256
+ const { start, length } = o;
1257
+ return typeof start === "number" && Number.isInteger(start) && start >= 0 && typeof length === "number" && Number.isInteger(length) && length >= 0;
1258
+ }
1259
+ function validateSourcePointerValue(v) {
1260
+ if (v === null) return null;
1261
+ if (typeof v !== "object" || Array.isArray(v)) return void 0;
1262
+ const o = v;
1263
+ const keys = Object.keys(o);
1264
+ for (const k of keys) {
1265
+ if (!POINTER_SLOTS.includes(k)) return void 0;
1266
+ }
1267
+ if (!isStringOrNull(o["event_id"] === void 0 ? null : o["event_id"]) || !isStringOrNull(o["ref"] === void 0 ? null : o["ref"]) || !isStringOrNull(o["quote"] === void 0 ? null : o["quote"])) {
1268
+ return void 0;
1269
+ }
1270
+ if (!isValidPosition(o["position"] === void 0 ? null : o["position"])) return void 0;
1271
+ const normalized = {
1272
+ event_id: o["event_id"] ?? null,
1273
+ ref: o["ref"] ?? null,
1274
+ quote: o["quote"] ?? null,
1275
+ position: o["position"] ?? null
1276
+ };
1277
+ if (normalized.event_id === null && normalized.ref === null && normalized.quote === null && normalized.position === null) {
1278
+ return null;
1279
+ }
1280
+ return normalized;
1281
+ }
1282
+
1237
1283
  // src/services/legacyWatermark.ts
1238
1284
  async function anchorAtLegacyBoundary(metadataRepo, eventRepo, entityId, checkpoint, total, db) {
1239
1285
  if (checkpoint <= 0 || total <= 0) return null;
@@ -1523,6 +1569,19 @@ var ImportExportService = class {
1523
1569
  );
1524
1570
  }
1525
1571
  }
1572
+ const hasSourcePointerKey = fact["source_pointer"] !== void 0;
1573
+ const rawPointerValue = hasSourcePointerKey ? fact["source_pointer"] : void 0;
1574
+ const pointerValidated = hasSourcePointerKey ? validateSourcePointerValue(rawPointerValue) : null;
1575
+ if (pointerValidated === void 0) {
1576
+ emitDiagnostic(this.options, {
1577
+ code: "source_pointer_invalid",
1578
+ operation: "importDump",
1579
+ trigger: "call",
1580
+ entityId,
1581
+ detail: { factId: fact.id }
1582
+ });
1583
+ }
1584
+ const sourcePointer = pointerValidated === void 0 ? null : pointerValidated;
1526
1585
  const factObj = {
1527
1586
  id: fact.id,
1528
1587
  entity_id: entityId,
@@ -1540,6 +1599,7 @@ var ImportExportService = class {
1540
1599
  deleted_at: fact.deleted_at,
1541
1600
  embedding_blob: blobData ?? void 0,
1542
1601
  okf_type: fact.okf_type ?? null,
1602
+ source_pointer: sourcePointer,
1543
1603
  // OKF v0.2 — forwarded as-is; parseOkfBundle / the caller is responsible for
1544
1604
  // populating these per spec, importDump does not derive or validate them.
1545
1605
  lifecycle_status: fact.lifecycle_status ?? "stable",
@@ -1557,7 +1617,7 @@ var ImportExportService = class {
1557
1617
  return { last_verified_at: latest?.at ?? null, last_verified_by: latest?.by ?? null };
1558
1618
  })()
1559
1619
  };
1560
- await this.entryRepo.upsertForImport(factObj, tx);
1620
+ await this.entryRepo.upsertForImport(factObj, tx, hasSourcePointerKey);
1561
1621
  await this.entryRepo.setTemporal(fact.id, entityId, {
1562
1622
  valid_from: fact.valid_from ?? null,
1563
1623
  valid_to: fact.valid_to ?? null,
@@ -1886,6 +1946,14 @@ function generateId(prefix = "") {
1886
1946
  }
1887
1947
 
1888
1948
  // src/prompts.ts
1949
+ var LEAVE_OUT_RULE_SENTENCE = "Memory leaves out what a better record already holds, and points to that record.";
1950
+ var GUIDANCE_MAX_CHARS = 2e3;
1951
+ function guidanceSection(guidance) {
1952
+ return `--- Host guidance ---
1953
+ ${guidance}
1954
+ --- End host guidance ---
1955
+ ${LEAVE_OUT_RULE_SENTENCE}`;
1956
+ }
1889
1957
  var LIBRARIAN_SYSTEM_PROMPT = `You are a knowledge extraction agent. Your job is to analyze recent episodic events and extract stable facts and actionable tasks about the user or entity.
1890
1958
  Return ONLY a valid JSON object matching this schema:
1891
1959
  {
@@ -2009,6 +2077,64 @@ var PromptService = class {
2009
2077
  this.globalOverrides = globalOverrides;
2010
2078
  this.grounding = grounding;
2011
2079
  }
2080
+ /**
2081
+ * Specs/librarian-guidance: resolve the effective guidance for one pass
2082
+ * or call — default `config.prompts.guidance`, per-entity
2083
+ * `config.librarian.guidanceForEntity` winning when it returns a
2084
+ * non-empty (trimmed) string. Synchronous: a resolver that throws,
2085
+ * returns a thenable (its rejection is swallowed with a no-op handler;
2086
+ * a throwing `then` counts too), or returns any non-string value is
2087
+ * treated as "no value" and reported in `diagnostic`. Over-cap text
2088
+ * (UTF-16 units, verbatim) is not sent and reported in `diagnostic`.
2089
+ * Emits nothing itself; the caller emits, immediately at resolution.
2090
+ */
2091
+ static resolveGuidance(config, entityId) {
2092
+ let source = null;
2093
+ let effective;
2094
+ let resolverDiagnostic;
2095
+ const defaultValue = config?.prompts?.guidance;
2096
+ const resolver = config?.librarian?.guidanceForEntity;
2097
+ let entityValue;
2098
+ if (resolver) {
2099
+ try {
2100
+ entityValue = resolver(entityId);
2101
+ if (entityValue === void 0) {
2102
+ } else if (typeof entityValue === "string") {
2103
+ if (entityValue.trim() !== "") {
2104
+ source = "per_entity";
2105
+ effective = entityValue;
2106
+ }
2107
+ } else {
2108
+ try {
2109
+ entityValue?.then?.(() => void 0, () => void 0);
2110
+ } catch {
2111
+ }
2112
+ resolverDiagnostic = {
2113
+ code: "guidance_resolver_failed",
2114
+ detail: { reason: "non_string" }
2115
+ };
2116
+ }
2117
+ } catch {
2118
+ resolverDiagnostic = { code: "guidance_resolver_failed", detail: { reason: "threw" } };
2119
+ }
2120
+ }
2121
+ if (source === null && defaultValue !== void 0 && defaultValue.trim() !== "") {
2122
+ source = "default";
2123
+ effective = defaultValue;
2124
+ }
2125
+ if (source === null || effective === void 0) {
2126
+ return resolverDiagnostic ? { diagnostic: resolverDiagnostic } : {};
2127
+ }
2128
+ if (effective.length > GUIDANCE_MAX_CHARS) {
2129
+ return {
2130
+ diagnostic: {
2131
+ code: "guidance_too_long",
2132
+ detail: { guidanceLength: effective.length, guidanceSource: source }
2133
+ }
2134
+ };
2135
+ }
2136
+ return resolverDiagnostic ? { guidance: effective, diagnostic: resolverDiagnostic } : { guidance: effective };
2137
+ }
2012
2138
  /** The resolved grounding config when `writer` is in `grounding.writers`; otherwise null (spec §6.2). */
2013
2139
  groundingFor(writer) {
2014
2140
  return this.grounding?.writers.has(writer) ? this.grounding : null;
@@ -2019,6 +2145,19 @@ var PromptService = class {
2019
2145
  return cfg ? `${systemPrompt}
2020
2146
 
2021
2147
  ${groundingEvidenceBlock(writer, cfg)}` : systemPrompt;
2148
+ }
2149
+ /**
2150
+ * Specs/librarian-guidance: append the marked guidance section (with the
2151
+ * general leave-out rule) to the ALREADY-HYDRATED system prompt — after
2152
+ * ontology, immediately before grounding. The guidance text is never
2153
+ * run through hydration, so `{{…}}` inside it cannot change a builder's
2154
+ * template branch or be expanded with data. No-op on empty input.
2155
+ */
2156
+ appendGuidance(systemPrompt, guidance) {
2157
+ if (!guidance) return systemPrompt;
2158
+ return `${systemPrompt}
2159
+
2160
+ ${guidanceSection(guidance)}`;
2022
2161
  }
2023
2162
  hydrate(template, variables) {
2024
2163
  return template.replace(/\{\{\s*(\w+)\s*\}\}/g, (_match, key) => {
@@ -2055,31 +2194,31 @@ ${groundingEvidenceBlock(writer, cfg)}` : systemPrompt;
2055
2194
 
2056
2195
  ${ctx.ontologyModeInstructions}`;
2057
2196
  }
2058
- buildIngestPrompt(documentChunk, runtimeOverride, ontologyContext) {
2197
+ buildIngestPrompt(documentChunk, runtimeOverride, ontologyContext, guidance) {
2059
2198
  const template = runtimeOverride ?? this.globalOverrides?.ingestSystemPrompt ?? INGEST_SYSTEM_PROMPT;
2060
2199
  const hasDocumentChunk = /\{\{\s*documentChunk\s*\}\}/.test(template);
2061
2200
  if (hasDocumentChunk || this.hasOntologyPlaceholders(template)) {
2062
2201
  return {
2063
- systemPrompt: this.appendGrounding(this.buildSystemPrompt(template, { documentChunk }, ontologyContext), "ingest"),
2202
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.buildSystemPrompt(template, { documentChunk }, ontologyContext), guidance), "ingest"),
2064
2203
  userPrompt: hasDocumentChunk ? "Please extract the facts." : `Document Chunk:
2065
2204
  ${documentChunk}`
2066
2205
  };
2067
2206
  }
2068
2207
  return {
2069
- systemPrompt: this.appendGrounding(this.appendOntology(template, ontologyContext), "ingest"),
2208
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.appendOntology(template, ontologyContext), guidance), "ingest"),
2070
2209
  userPrompt: `Document Chunk:
2071
2210
  ${documentChunk}`
2072
2211
  };
2073
2212
  }
2074
- buildLibrarianPrompt(events, currentFacts, runtimeOverride, ontologyContext) {
2075
- const template = runtimeOverride ?? this.globalOverrides?.librarianSystemPrompt ?? LIBRARIAN_SYSTEM_PROMPT;
2213
+ buildLibrarianPrompt(events, currentFacts, runtimeOverride, ontologyContext, guidance) {
2214
+ const template = runtimeOverride ?? LIBRARIAN_SYSTEM_PROMPT;
2076
2215
  const hasEvents = /\{\{\s*events\s*\}\}/.test(template);
2077
2216
  const hasCurrentFacts = /\{\{\s*currentFacts\s*\}\}/.test(template);
2078
2217
  const eventsShown = hasEvents || !hasCurrentFacts;
2079
2218
  const corpusField = this.groundingFor("librarian") ? { groundingCorpus: buildGroundingCorpus(eventsShown ? events.map(summaryOf) : []) } : {};
2080
2219
  if (hasEvents || hasCurrentFacts || this.hasOntologyPlaceholders(template)) {
2081
2220
  return {
2082
- systemPrompt: this.appendGrounding(this.buildSystemPrompt(template, { events, currentFacts }, ontologyContext), "librarian"),
2221
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.buildSystemPrompt(template, { events, currentFacts }, ontologyContext), guidance), "librarian"),
2083
2222
  userPrompt: hasEvents || hasCurrentFacts ? "Please synthesize the context." : `Events:
2084
2223
  ${JSON.stringify(events, null, 2)}
2085
2224
 
@@ -2089,7 +2228,7 @@ ${JSON.stringify(currentFacts, null, 2)}`,
2089
2228
  };
2090
2229
  }
2091
2230
  return {
2092
- systemPrompt: this.appendGrounding(this.appendOntology(template, ontologyContext), "librarian"),
2231
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.appendOntology(template, ontologyContext), guidance), "librarian"),
2093
2232
  userPrompt: `Events:
2094
2233
  ${JSON.stringify(events, null, 2)}
2095
2234
 
@@ -2192,13 +2331,17 @@ ${JSON.stringify(facts, null, 2)}`
2192
2331
  };
2193
2332
  }
2194
2333
  /** Ops extract (spec §5.2): events only — no existing facts. */
2195
- buildOpsExtractPrompt(events, ontologyContext) {
2334
+ buildOpsExtractPrompt(events, ontologyContext, guidance) {
2196
2335
  const lines = events.map((l) => `${l.label} [${new Date(l.at).toISOString()}] (${l.event.event_type}) ${l.event.summary}`);
2197
2336
  const grounding = this.groundingFor("librarian");
2198
2337
  return {
2199
- systemPrompt: this.appendGrounding(this.appendOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), "librarian"),
2338
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.appendOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), guidance), "librarian"),
2200
2339
  userPrompt: `Events:
2201
2340
  ${lines.join("\n")}`,
2341
+ // Corpus entries are one-per-batch-event in batch order (summaries are
2342
+ // TEXT NOT NULL, so the filter inside buildGroundingCorpus drops
2343
+ // nothing): extract.ts stores a candidate's `sourcePartIndex` as the
2344
+ // batch index and buildSourcePointer reads the quote back by it.
2202
2345
  ...grounding ? { groundingCorpus: buildGroundingCorpus(events.map((l) => l.event.summary)) } : {}
2203
2346
  };
2204
2347
  }
@@ -2213,11 +2356,11 @@ ${JSON.stringify({ items })}` };
2213
2356
  * placeholders and leaves data placeholders verbatim; heal never receives
2214
2357
  * ontology context, matching `buildHealPrompt`.
2215
2358
  */
2216
- buildInstructionTemplates(ontologyContext, librarianStrategy) {
2359
+ buildInstructionTemplates(ontologyContext, librarianStrategy, guidance) {
2217
2360
  const o = this.globalOverrides;
2218
2361
  return {
2219
- ingest: this.appendGrounding(this.buildSystemPrompt(o?.ingestSystemPrompt ?? INGEST_SYSTEM_PROMPT, {}, ontologyContext), "ingest"),
2220
- librarian: librarianStrategy === "ops" ? this.appendGrounding(this.appendOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), "librarian") : this.appendGrounding(this.buildSystemPrompt(o?.librarianSystemPrompt ?? LIBRARIAN_SYSTEM_PROMPT, {}, ontologyContext), "librarian"),
2362
+ ingest: this.appendGrounding(this.appendGuidance(this.buildSystemPrompt(o?.ingestSystemPrompt ?? INGEST_SYSTEM_PROMPT, {}, ontologyContext), guidance), "ingest"),
2363
+ librarian: librarianStrategy === "ops" ? this.appendGrounding(this.appendGuidance(this.appendOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), guidance), "librarian") : this.appendGrounding(this.appendGuidance(this.buildSystemPrompt(LIBRARIAN_SYSTEM_PROMPT, {}, ontologyContext), guidance), "librarian"),
2221
2364
  heal: this.appendGrounding(o?.healSystemPrompt ?? HEAL_SYSTEM_PROMPT, "heal"),
2222
2365
  ontologyBackfill: this.buildSystemPrompt(o?.ontologyBackfillSystemPrompt ?? ONTOLOGY_BACKFILL_SYSTEM_PROMPT, {}, ontologyContext)
2223
2366
  };
@@ -2392,13 +2535,24 @@ var IngestionService = class {
2392
2535
  const { chunks: chunks2, truncated } = chunkText(params.documentChunk, maxChunkLength, chunkOverlap);
2393
2536
  if (chunks2.length === 0) return zeroChunkResult();
2394
2537
  const ontologyContext = await this.ontologyService?.buildPromptContext(entityId) ?? null;
2538
+ const { guidance, diagnostic } = PromptService.resolveGuidance(this.options.config, entityId);
2539
+ if (diagnostic) {
2540
+ emitDiagnostic(this.options, {
2541
+ code: diagnostic.code,
2542
+ operation: "ingest",
2543
+ trigger: "call",
2544
+ entityId,
2545
+ detail: diagnostic.detail
2546
+ });
2547
+ }
2395
2548
  const ingestGrounding = this.promptService.groundingFor("ingest");
2396
2549
  const chunkResults = await withConcurrency(
2397
2550
  chunks2.map((chunk, chunkIndex) => async () => {
2398
2551
  const { systemPrompt, userPrompt } = this.promptService.buildIngestPrompt(
2399
2552
  chunk,
2400
2553
  params.promptOverride,
2401
- ontologyContext
2554
+ ontologyContext,
2555
+ guidance
2402
2556
  );
2403
2557
  try {
2404
2558
  const responseText = await callLlm(this.options, { operation: "ingest", entityId, trigger: "call" }, { systemPrompt, userPrompt });
@@ -3740,6 +3894,17 @@ var MIGRATIONS = [
3740
3894
  );
3741
3895
  if (row?.n) await db.execAsync(fts5PendingIndexesDdl(prefix));
3742
3896
  }
3897
+ },
3898
+ {
3899
+ version: 16,
3900
+ description: "Source pointers on librarian facts: nullable source_pointer TEXT on entries",
3901
+ run: async (db, prefix) => {
3902
+ const cols = await db.getAllAsync(`PRAGMA table_info(${prefix}entries)`);
3903
+ const existing = new Set(cols.map((c) => c.name));
3904
+ if (!existing.has("source_pointer")) {
3905
+ await db.execAsync(`ALTER TABLE ${prefix}entries ADD COLUMN source_pointer TEXT`);
3906
+ }
3907
+ }
3743
3908
  }
3744
3909
  ];
3745
3910
  async function createLegacySourceTypeIndex(db, prefix) {
@@ -3803,7 +3968,8 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
3803
3968
  promptEvents,
3804
3969
  currentFacts,
3805
3970
  promptOverride,
3806
- ontologyContext
3971
+ ontologyContext,
3972
+ ctx.guidance
3807
3973
  );
3808
3974
  let responseText;
3809
3975
  try {
@@ -3901,9 +4067,20 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
3901
4067
  access_count: 0,
3902
4068
  deleted_at: null,
3903
4069
  okf_type: normalized.okf_type,
4070
+ // Legacy writes no pointer (spec §Legacy path): the column stays null
4071
+ // on every legacy fact, and the legacy prompt keeps its exact text.
4072
+ source_pointer: null,
3904
4073
  ...grounding?.trust
3905
4074
  };
3906
4075
  await deps.entryRepo.upsert(factObj, tx);
4076
+ const volunteeredSourceEvent = facts[validFactItemIndexes[k]]?.source_event;
4077
+ if (volunteeredSourceEvent !== void 0 && volunteeredSourceEvent !== null) {
4078
+ diagBuffer.push({
4079
+ ...diagBase,
4080
+ code: "source_pointer_unresolved",
4081
+ detail: { factId: id, itemIndex: validFactItemIndexes[k], reason: "unsupported_strategy" }
4082
+ });
4083
+ }
3907
4084
  insertedFacts.push({ id, entity_id: entityId, title: fact.title, body: fact.body, tags: JSON.stringify(fact.tags) });
3908
4085
  factsForDedupe.push(factObj);
3909
4086
  titleIndex.set(normalizeTitleKey(fact.title), { id, okf_type: normalized.okf_type });
@@ -3975,7 +4152,7 @@ var OPS_MAX_EVENTS_PER_PASS = 50;
3975
4152
  var OPS_MAX_EXTRACT_CHARS = 24e3;
3976
4153
  var RESOLVE_RESERVE_FACTOR = 2;
3977
4154
  var estimatePrompt = (p) => estimateTokens(p.systemPrompt) + estimateTokens(p.userPrompt);
3978
- async function selectBatch(deps, entityId, wm, meter) {
4155
+ async function selectBatch(deps, entityId, wm, meter, guidance) {
3979
4156
  const events = await deps.eventRepo.getAfter(entityId, wm, OPS_MAX_EVENTS_PER_PASS);
3980
4157
  if (events.length === 0) return { batch: [] };
3981
4158
  let n = 0;
@@ -3989,7 +4166,7 @@ async function selectBatch(deps, entityId, wm, meter) {
3989
4166
  if (meter && meter.budget !== void 0) {
3990
4167
  const ontologyContext = await deps.ontologyService?.buildPromptContext(entityId) ?? null;
3991
4168
  for (; ; ) {
3992
- const need = RESOLVE_RESERVE_FACTOR * estimatePrompt(deps.promptService.buildOpsExtractPrompt(batch, ontologyContext));
4169
+ const need = RESOLVE_RESERVE_FACTOR * estimatePrompt(deps.promptService.buildOpsExtractPrompt(batch, ontologyContext, guidance));
3993
4170
  if (meter.fits(need)) break;
3994
4171
  if (batch.length === 1) return { budgetStop: { requiredEstimate: need } };
3995
4172
  batch = labelEvents(events.slice(0, Math.max(1, Math.floor(batch.length / 2))));
@@ -4000,7 +4177,7 @@ async function selectBatch(deps, entityId, wm, meter) {
4000
4177
  async function runExtract(deps, ctx, batch) {
4001
4178
  const { entityId, trigger } = ctx;
4002
4179
  const ontologyContext = await deps.ontologyService?.buildPromptContext(entityId) ?? null;
4003
- const prompt = deps.promptService.buildOpsExtractPrompt(batch, ontologyContext);
4180
+ const prompt = deps.promptService.buildOpsExtractPrompt(batch, ontologyContext, ctx.guidance);
4004
4181
  const text = await callLlm(deps.options, { operation: "librarian", entityId, trigger, meter: ctx.meter }, prompt);
4005
4182
  const parsed = parseJsonResponse(text);
4006
4183
  const base = { entityId, operation: "librarian", trigger };
@@ -4017,9 +4194,23 @@ async function runExtract(deps, ctx, batch) {
4017
4194
  return;
4018
4195
  }
4019
4196
  const r = raw;
4020
- const sourceLabel = typeof r.source_event === "string" && byLabel.has(r.source_event) ? r.source_event : null;
4197
+ let sourceEventId = null;
4198
+ let sourcePartIndex = null;
4199
+ let pointerUnresolved;
4200
+ const rawSourceEvent = r.source_event;
4201
+ if (rawSourceEvent === void 0 || rawSourceEvent === null) {
4202
+ pointerUnresolved = "missing";
4203
+ } else if (typeof rawSourceEvent === "string" && byLabel.has(rawSourceEvent)) {
4204
+ const labeled = byLabel.get(rawSourceEvent);
4205
+ sourceEventId = labeled.event.id;
4206
+ sourcePartIndex = batch.findIndex((b) => b.label === rawSourceEvent);
4207
+ pointerUnresolved = null;
4208
+ } else {
4209
+ pointerUnresolved = "unknown_label";
4210
+ }
4211
+ const sourceLabel = typeof rawSourceEvent === "string" && byLabel.has(rawSourceEvent) ? rawSourceEvent : null;
4021
4212
  const validFrom = parseValidFrom(r.valid_from) ?? (sourceLabel ? byLabel.get(sourceLabel).at : defaultValidFrom);
4022
- candidates.push({ index, fact, sourceLabel, validFrom });
4213
+ candidates.push({ index, fact, sourceLabel, sourceEventId, sourcePartIndex, pointerUnresolved, validFrom });
4023
4214
  });
4024
4215
  const tasks = [];
4025
4216
  (Array.isArray(parsed.tasks) ? parsed.tasks : []).forEach((raw, index) => {
@@ -4309,6 +4500,17 @@ var TemporalService = class {
4309
4500
  };
4310
4501
 
4311
4502
  // src/services/librarian/ops/apply.ts
4503
+ function buildSourcePointer(candidate, verdict, groundingOn, groundingCorpus) {
4504
+ if (candidate.sourceEventId === null) return null;
4505
+ let quote = null;
4506
+ if (groundingOn && verdict?.status === "grounded" && candidate.sourcePartIndex !== null) {
4507
+ const part = groundingCorpus?.[candidate.sourcePartIndex];
4508
+ if (part !== void 0) {
4509
+ quote = verdict.retained.find((q) => part.includes(q)) ?? null;
4510
+ }
4511
+ }
4512
+ return { event_id: candidate.sourceEventId, ref: null, quote, position: null };
4513
+ }
4312
4514
  async function applyOps(deps, ctx, input) {
4313
4515
  const { entityId, trigger } = ctx;
4314
4516
  const diagBase = { entityId, operation: "librarian", trigger };
@@ -4337,7 +4539,8 @@ async function applyOps(deps, ctx, input) {
4337
4539
  const drops = [];
4338
4540
  const normalized = deps.ontologyService?.validateAndNormalizeFact(fact, manifest, { strict: false, drops }) ?? { okf_type: null, edges: [] };
4339
4541
  for (const d of drops) input.diagnostics.push(edgeDropDiagnostic(d, { ...diagBase, factId: id }));
4340
- const g2 = grounding ? groundingOutcome(checkGrounding(fact.evidence, input.groundingCorpus ?? [], grounding), now) : null;
4542
+ const gVerdict = grounding ? checkGrounding(fact.evidence, input.groundingCorpus ?? [], grounding) : null;
4543
+ const g2 = gVerdict ? groundingOutcome(gVerdict, now) : null;
4341
4544
  if (g2?.diagnostic) {
4342
4545
  input.diagnostics.push({
4343
4546
  ...diagBase,
@@ -4345,6 +4548,7 @@ async function applyOps(deps, ctx, input) {
4345
4548
  detail: { factId: id, itemIndex: g.candidate.index, reason: g2.diagnostic.reason }
4346
4549
  });
4347
4550
  }
4551
+ const pointer = buildSourcePointer(g.candidate, gVerdict, grounding !== void 0 && grounding !== null, input.groundingCorpus);
4348
4552
  const row = {
4349
4553
  id,
4350
4554
  entity_id: entityId,
@@ -4361,11 +4565,19 @@ async function applyOps(deps, ctx, input) {
4361
4565
  access_count: 0,
4362
4566
  deleted_at: null,
4363
4567
  okf_type: normalized.okf_type,
4568
+ source_pointer: pointer,
4364
4569
  ...g2?.trust,
4365
4570
  ...draft ? { lifecycle_status: "draft" } : {}
4366
4571
  };
4367
4572
  await deps.entryRepo.upsert(row, tx);
4368
4573
  await deps.entryRepo.setTemporal(id, entityId, { valid_from: validFrom }, tx);
4574
+ if (g.candidate.pointerUnresolved !== null) {
4575
+ input.diagnostics.push({
4576
+ ...diagBase,
4577
+ code: "source_pointer_unresolved",
4578
+ detail: { factId: id, itemIndex: g.candidate.index, reason: g.candidate.pointerUnresolved }
4579
+ });
4580
+ }
4369
4581
  titleIndex.set(normalizeTitleKey(title), { id, okf_type: normalized.okf_type });
4370
4582
  if (normalized.edges.length > 0) pendingEdges.push({ sourceId: id, sourceType: normalized.okf_type, edges: normalized.edges });
4371
4583
  const textChanged = title !== fact.title || body !== fact.body;
@@ -4471,7 +4683,7 @@ var runOpsLibrarianPass = async (deps, ctx) => {
4471
4683
  const cfg = resolveGateConfig(deps.options.config?.librarian?.gate);
4472
4684
  await deps.seedWatermark(entityId);
4473
4685
  const wm = await deps.getWatermark(entityId);
4474
- const sel = await selectBatch(deps, entityId, wm, ctx.meter);
4686
+ const sel = await selectBatch(deps, entityId, wm, ctx.meter, ctx.guidance);
4475
4687
  if ("budgetStop" in sel) return { processedThrough: null, factsWritten: 0, budgetStop: sel.budgetStop };
4476
4688
  if (sel.batch.length === 0) return { processedThrough: null, factsWritten: 0 };
4477
4689
  if (!deps.searchService.isKeywordAvailable() && await gateNeedsKeyword(deps, entityId)) {
@@ -5109,7 +5321,17 @@ var MaintenanceService = class {
5109
5321
  * A budget-stopped pass wrote nothing and must not move the watermark.
5110
5322
  */
5111
5323
  async runLibrarianPass(ctx) {
5112
- const result = await runLibrarianStrategy(this.librarianDeps(), ctx);
5324
+ const { guidance, diagnostic } = PromptService.resolveGuidance(this.options.config, ctx.entityId);
5325
+ if (diagnostic) {
5326
+ emitDiagnostic(this.options, {
5327
+ code: diagnostic.code,
5328
+ operation: "librarian",
5329
+ trigger: ctx.trigger,
5330
+ entityId: ctx.entityId,
5331
+ detail: diagnostic.detail
5332
+ });
5333
+ }
5334
+ const result = await runLibrarianStrategy(this.librarianDeps(), { ...ctx, guidance });
5113
5335
  if (result.processedThrough && !result.budgetStop) {
5114
5336
  await this.advanceLibrarianWatermark(ctx.entityId, result.processedThrough);
5115
5337
  }
@@ -5379,6 +5601,7 @@ var MaintenanceService = class {
5379
5601
  source_type: "librarian_inferred",
5380
5602
  source_hash: null,
5381
5603
  source_ref: null,
5604
+ source_pointer: null,
5382
5605
  created_at: now,
5383
5606
  updated_at: now,
5384
5607
  last_accessed_at: null,