@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/README.md CHANGED
@@ -59,7 +59,7 @@ The [Node.js quickstart](https://equationalapplications.github.io/expo-llm-wiki/
59
59
  | [@equationalapplications/core-llm-tools](https://github.com/equationalapplications/expo-llm-wiki/blob/main/packages/core-llm-tools/README.md) | Gemini tool schemas and capability injector |
60
60
  | [@equationalapplications/core-okf](https://github.com/equationalapplications/expo-llm-wiki/blob/main/packages/okf/README.md) | Zero-dependency Open Knowledge Format (OKF) v0.1 + v0.2 primitives — parse and produce interoperable knowledge bundles. |
61
61
  | [@equationalapplications/schema-org-llm-wiki](https://github.com/equationalapplications/expo-llm-wiki/blob/main/packages/schema-org/README.md) | Curated schema.org warm-agent ontology manifest |
62
- | [@equationalapplications/schema-software-org](https://github.com/equationalapplications/expo-llm-wiki/blob/main/packages/schema-software-org/README.md) | Software-organization executive ontology manifest — 17 node types, 40 edges, warm-agent superset, data-only |
62
+ | [@equationalapplications/schema-software-org](https://github.com/equationalapplications/expo-llm-wiki/blob/main/packages/schema-software-org/README.md) | Software-organization executive ontology manifest — 21 node types, 42 edges, warm-agent superset, data-only |
63
63
  | [@equationalapplications/mcp-server](https://github.com/equationalapplications/expo-llm-wiki/blob/main/packages/mcp-server/README.md) | MCP server exposing SynapseTree memory tools to coding agents |
64
64
 
65
65
  ## License
@@ -1785,6 +1785,14 @@ var JobManager = class {
1785
1785
  };
1786
1786
 
1787
1787
  // src/prompts.ts
1788
+ var LEAVE_OUT_RULE_SENTENCE = "Memory leaves out what a better record already holds, and points to that record.";
1789
+ var GUIDANCE_MAX_CHARS = 2e3;
1790
+ function guidanceSection(guidance) {
1791
+ return `--- Host guidance ---
1792
+ ${guidance}
1793
+ --- End host guidance ---
1794
+ ${LEAVE_OUT_RULE_SENTENCE}`;
1795
+ }
1788
1796
  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.
1789
1797
  Return ONLY a valid JSON object matching this schema:
1790
1798
  {
@@ -1908,6 +1916,64 @@ var PromptService = class {
1908
1916
  this.globalOverrides = globalOverrides;
1909
1917
  this.grounding = grounding;
1910
1918
  }
1919
+ /**
1920
+ * Specs/librarian-guidance: resolve the effective guidance for one pass
1921
+ * or call — default `config.prompts.guidance`, per-entity
1922
+ * `config.librarian.guidanceForEntity` winning when it returns a
1923
+ * non-empty (trimmed) string. Synchronous: a resolver that throws,
1924
+ * returns a thenable (its rejection is swallowed with a no-op handler;
1925
+ * a throwing `then` counts too), or returns any non-string value is
1926
+ * treated as "no value" and reported in `diagnostic`. Over-cap text
1927
+ * (UTF-16 units, verbatim) is not sent and reported in `diagnostic`.
1928
+ * Emits nothing itself; the caller emits, immediately at resolution.
1929
+ */
1930
+ static resolveGuidance(config, entityId) {
1931
+ let source = null;
1932
+ let effective;
1933
+ let resolverDiagnostic;
1934
+ const defaultValue = config?.prompts?.guidance;
1935
+ const resolver = config?.librarian?.guidanceForEntity;
1936
+ let entityValue;
1937
+ if (resolver) {
1938
+ try {
1939
+ entityValue = resolver(entityId);
1940
+ if (entityValue === void 0) {
1941
+ } else if (typeof entityValue === "string") {
1942
+ if (entityValue.trim() !== "") {
1943
+ source = "per_entity";
1944
+ effective = entityValue;
1945
+ }
1946
+ } else {
1947
+ try {
1948
+ entityValue?.then?.(() => void 0, () => void 0);
1949
+ } catch {
1950
+ }
1951
+ resolverDiagnostic = {
1952
+ code: "guidance_resolver_failed",
1953
+ detail: { reason: "non_string" }
1954
+ };
1955
+ }
1956
+ } catch {
1957
+ resolverDiagnostic = { code: "guidance_resolver_failed", detail: { reason: "threw" } };
1958
+ }
1959
+ }
1960
+ if (source === null && defaultValue !== void 0 && defaultValue.trim() !== "") {
1961
+ source = "default";
1962
+ effective = defaultValue;
1963
+ }
1964
+ if (source === null || effective === void 0) {
1965
+ return resolverDiagnostic ? { diagnostic: resolverDiagnostic } : {};
1966
+ }
1967
+ if (effective.length > GUIDANCE_MAX_CHARS) {
1968
+ return {
1969
+ diagnostic: {
1970
+ code: "guidance_too_long",
1971
+ detail: { guidanceLength: effective.length, guidanceSource: source }
1972
+ }
1973
+ };
1974
+ }
1975
+ return resolverDiagnostic ? { guidance: effective, diagnostic: resolverDiagnostic } : { guidance: effective };
1976
+ }
1911
1977
  /** The resolved grounding config when `writer` is in `grounding.writers`; otherwise null (spec §6.2). */
1912
1978
  groundingFor(writer) {
1913
1979
  return this.grounding?.writers.has(writer) ? this.grounding : null;
@@ -1918,6 +1984,19 @@ var PromptService = class {
1918
1984
  return cfg ? `${systemPrompt}
1919
1985
 
1920
1986
  ${groundingEvidenceBlock(writer, cfg)}` : systemPrompt;
1987
+ }
1988
+ /**
1989
+ * Specs/librarian-guidance: append the marked guidance section (with the
1990
+ * general leave-out rule) to the ALREADY-HYDRATED system prompt — after
1991
+ * ontology, immediately before grounding. The guidance text is never
1992
+ * run through hydration, so `{{…}}` inside it cannot change a builder's
1993
+ * template branch or be expanded with data. No-op on empty input.
1994
+ */
1995
+ appendGuidance(systemPrompt, guidance) {
1996
+ if (!guidance) return systemPrompt;
1997
+ return `${systemPrompt}
1998
+
1999
+ ${guidanceSection(guidance)}`;
1921
2000
  }
1922
2001
  hydrate(template, variables) {
1923
2002
  return template.replace(/\{\{\s*(\w+)\s*\}\}/g, (_match, key) => {
@@ -1954,31 +2033,31 @@ ${groundingEvidenceBlock(writer, cfg)}` : systemPrompt;
1954
2033
 
1955
2034
  ${ctx.ontologyModeInstructions}`;
1956
2035
  }
1957
- buildIngestPrompt(documentChunk, runtimeOverride, ontologyContext) {
2036
+ buildIngestPrompt(documentChunk, runtimeOverride, ontologyContext, guidance) {
1958
2037
  const template = runtimeOverride ?? this.globalOverrides?.ingestSystemPrompt ?? INGEST_SYSTEM_PROMPT;
1959
2038
  const hasDocumentChunk = /\{\{\s*documentChunk\s*\}\}/.test(template);
1960
2039
  if (hasDocumentChunk || this.hasOntologyPlaceholders(template)) {
1961
2040
  return {
1962
- systemPrompt: this.appendGrounding(this.buildSystemPrompt(template, { documentChunk }, ontologyContext), "ingest"),
2041
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.buildSystemPrompt(template, { documentChunk }, ontologyContext), guidance), "ingest"),
1963
2042
  userPrompt: hasDocumentChunk ? "Please extract the facts." : `Document Chunk:
1964
2043
  ${documentChunk}`
1965
2044
  };
1966
2045
  }
1967
2046
  return {
1968
- systemPrompt: this.appendGrounding(this.appendOntology(template, ontologyContext), "ingest"),
2047
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.appendOntology(template, ontologyContext), guidance), "ingest"),
1969
2048
  userPrompt: `Document Chunk:
1970
2049
  ${documentChunk}`
1971
2050
  };
1972
2051
  }
1973
- buildLibrarianPrompt(events, currentFacts, runtimeOverride, ontologyContext) {
1974
- const template = runtimeOverride ?? this.globalOverrides?.librarianSystemPrompt ?? LIBRARIAN_SYSTEM_PROMPT;
2052
+ buildLibrarianPrompt(events, currentFacts, runtimeOverride, ontologyContext, guidance) {
2053
+ const template = runtimeOverride ?? LIBRARIAN_SYSTEM_PROMPT;
1975
2054
  const hasEvents = /\{\{\s*events\s*\}\}/.test(template);
1976
2055
  const hasCurrentFacts = /\{\{\s*currentFacts\s*\}\}/.test(template);
1977
2056
  const eventsShown = hasEvents || !hasCurrentFacts;
1978
2057
  const corpusField = this.groundingFor("librarian") ? { groundingCorpus: buildGroundingCorpus(eventsShown ? events.map(summaryOf) : []) } : {};
1979
2058
  if (hasEvents || hasCurrentFacts || this.hasOntologyPlaceholders(template)) {
1980
2059
  return {
1981
- systemPrompt: this.appendGrounding(this.buildSystemPrompt(template, { events, currentFacts }, ontologyContext), "librarian"),
2060
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.buildSystemPrompt(template, { events, currentFacts }, ontologyContext), guidance), "librarian"),
1982
2061
  userPrompt: hasEvents || hasCurrentFacts ? "Please synthesize the context." : `Events:
1983
2062
  ${JSON.stringify(events, null, 2)}
1984
2063
 
@@ -1988,7 +2067,7 @@ ${JSON.stringify(currentFacts, null, 2)}`,
1988
2067
  };
1989
2068
  }
1990
2069
  return {
1991
- systemPrompt: this.appendGrounding(this.appendOntology(template, ontologyContext), "librarian"),
2070
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.appendOntology(template, ontologyContext), guidance), "librarian"),
1992
2071
  userPrompt: `Events:
1993
2072
  ${JSON.stringify(events, null, 2)}
1994
2073
 
@@ -2091,13 +2170,17 @@ ${JSON.stringify(facts, null, 2)}`
2091
2170
  };
2092
2171
  }
2093
2172
  /** Ops extract (spec §5.2): events only — no existing facts. */
2094
- buildOpsExtractPrompt(events, ontologyContext) {
2173
+ buildOpsExtractPrompt(events, ontologyContext, guidance) {
2095
2174
  const lines = events.map((l) => `${l.label} [${new Date(l.at).toISOString()}] (${l.event.event_type}) ${l.event.summary}`);
2096
2175
  const grounding = this.groundingFor("librarian");
2097
2176
  return {
2098
- systemPrompt: this.appendGrounding(this.appendOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), "librarian"),
2177
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.appendOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), guidance), "librarian"),
2099
2178
  userPrompt: `Events:
2100
2179
  ${lines.join("\n")}`,
2180
+ // Corpus entries are one-per-batch-event in batch order (summaries are
2181
+ // TEXT NOT NULL, so the filter inside buildGroundingCorpus drops
2182
+ // nothing): extract.ts stores a candidate's `sourcePartIndex` as the
2183
+ // batch index and buildSourcePointer reads the quote back by it.
2101
2184
  ...grounding ? { groundingCorpus: buildGroundingCorpus(events.map((l) => l.event.summary)) } : {}
2102
2185
  };
2103
2186
  }
@@ -2112,11 +2195,11 @@ ${JSON.stringify({ items })}` };
2112
2195
  * placeholders and leaves data placeholders verbatim; heal never receives
2113
2196
  * ontology context, matching `buildHealPrompt`.
2114
2197
  */
2115
- buildInstructionTemplates(ontologyContext, librarianStrategy) {
2198
+ buildInstructionTemplates(ontologyContext, librarianStrategy, guidance) {
2116
2199
  const o = this.globalOverrides;
2117
2200
  return {
2118
- ingest: this.appendGrounding(this.buildSystemPrompt(o?.ingestSystemPrompt ?? INGEST_SYSTEM_PROMPT, {}, ontologyContext), "ingest"),
2119
- librarian: librarianStrategy === "ops" ? this.appendGrounding(this.appendOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), "librarian") : this.appendGrounding(this.buildSystemPrompt(o?.librarianSystemPrompt ?? LIBRARIAN_SYSTEM_PROMPT, {}, ontologyContext), "librarian"),
2201
+ ingest: this.appendGrounding(this.appendGuidance(this.buildSystemPrompt(o?.ingestSystemPrompt ?? INGEST_SYSTEM_PROMPT, {}, ontologyContext), guidance), "ingest"),
2202
+ 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"),
2120
2203
  heal: this.appendGrounding(o?.healSystemPrompt ?? HEAL_SYSTEM_PROMPT, "heal"),
2121
2204
  ontologyBackfill: this.buildSystemPrompt(o?.ontologyBackfillSystemPrompt ?? ONTOLOGY_BACKFILL_SYSTEM_PROMPT, {}, ontologyContext)
2122
2205
  };
@@ -2195,7 +2278,11 @@ var SEVERITY = {
2195
2278
  event_created_at_clamped: "warn",
2196
2279
  event_created_at_restamped: "info",
2197
2280
  external_deletion_pending: "warn",
2198
- external_deletion_discarded: "warn"
2281
+ external_deletion_discarded: "warn",
2282
+ guidance_too_long: "warn",
2283
+ guidance_resolver_failed: "warn",
2284
+ source_pointer_unresolved: "warn",
2285
+ source_pointer_invalid: "warn"
2199
2286
  };
2200
2287
  var MESSAGE = {
2201
2288
  ingest_chunk_failed: "One or more document chunks failed to parse or generate.",
@@ -2221,7 +2308,11 @@ var MESSAGE = {
2221
2308
  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.",
2222
2309
  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.",
2223
2310
  external_deletion_pending: "Removals owed to the external vector index are still pending.",
2224
- external_deletion_discarded: "Pending external vector removals were discarded because forceDeleteIgnoreRankerHook is set."
2311
+ external_deletion_discarded: "Pending external vector removals were discarded because forceDeleteIgnoreRankerHook is set.",
2312
+ guidance_too_long: "The configured guidance exceeded the length cap and was not sent for this pass.",
2313
+ guidance_resolver_failed: "The per-entity guidance resolver failed; its value was not used for this pass.",
2314
+ source_pointer_unresolved: "A stored librarian fact carries no source pointer because the model answer could not yield one.",
2315
+ source_pointer_invalid: "Import met a malformed source pointer value and stored a null pointer."
2225
2316
  };
2226
2317
  var warnedNonFunction = /* @__PURE__ */ new WeakSet();
2227
2318
  function copyDetail(detail) {
@@ -2448,13 +2539,24 @@ var IngestionService = class {
2448
2539
  const { chunks: chunks2, truncated } = chunkText(params.documentChunk, maxChunkLength, chunkOverlap);
2449
2540
  if (chunks2.length === 0) return zeroChunkResult();
2450
2541
  const ontologyContext = await this.ontologyService?.buildPromptContext(entityId) ?? null;
2542
+ const { guidance, diagnostic } = PromptService.resolveGuidance(this.options.config, entityId);
2543
+ if (diagnostic) {
2544
+ emitDiagnostic(this.options, {
2545
+ code: diagnostic.code,
2546
+ operation: "ingest",
2547
+ trigger: "call",
2548
+ entityId,
2549
+ detail: diagnostic.detail
2550
+ });
2551
+ }
2451
2552
  const ingestGrounding = this.promptService.groundingFor("ingest");
2452
2553
  const chunkResults = await withConcurrency(
2453
2554
  chunks2.map((chunk, chunkIndex) => async () => {
2454
2555
  const { systemPrompt, userPrompt } = this.promptService.buildIngestPrompt(
2455
2556
  chunk,
2456
2557
  params.promptOverride,
2457
- ontologyContext
2558
+ ontologyContext,
2559
+ guidance
2458
2560
  );
2459
2561
  try {
2460
2562
  const responseText = await callLlm(this.options, { operation: "ingest", entityId, trigger: "call" }, { systemPrompt, userPrompt });
@@ -3093,9 +3195,9 @@ function changedDefaultWarnings(config) {
3093
3195
  "[core-llm-wiki] auto-run thresholds are set, but `maintenance` now defaults to 'deferred', so write() will not start the librarian or heal. Set `maintenance: 'auto'` or call runPendingMaintenance()."
3094
3196
  );
3095
3197
  }
3096
- if (config?.prompts?.librarianSystemPrompt !== void 0 && config?.librarian?.strategy === void 0) {
3198
+ if (config?.prompts?.librarianSystemPrompt !== void 0) {
3097
3199
  warnings.push(
3098
- "[core-llm-wiki] `prompts.librarianSystemPrompt` is set, but `librarian.strategy` now defaults to 'ops', which does not use it. Set `librarian: { strategy: 'legacy' }` to keep the override."
3200
+ "[core-llm-wiki] `prompts.librarianSystemPrompt` was removed in 9.0.0 and its value is ignored. Move the domain part of it to `prompts.guidance`, which works under both librarian strategies."
3099
3201
  );
3100
3202
  }
3101
3203
  if (config?.librarian?.strategy === "legacy" && config?.maintenance === void 0 && !hasThreshold) {
@@ -4280,7 +4382,8 @@ async function setupDatabase(db, prefix) {
4280
4382
  valid_from INTEGER,
4281
4383
  valid_to INTEGER,
4282
4384
  superseded_by TEXT,
4283
- superseded_at INTEGER
4385
+ superseded_at INTEGER,
4386
+ source_pointer TEXT
4284
4387
  );
4285
4388
 
4286
4389
  CREATE INDEX IF NOT EXISTS ${prefix}entries_entity_idx ON ${prefix}entries(entity_id);
@@ -4929,6 +5032,17 @@ var MIGRATIONS = [
4929
5032
  );
4930
5033
  if (row?.n) await db.execAsync(fts5PendingIndexesDdl(prefix));
4931
5034
  }
5035
+ },
5036
+ {
5037
+ version: 16,
5038
+ description: "Source pointers on librarian facts: nullable source_pointer TEXT on entries",
5039
+ run: async (db, prefix) => {
5040
+ const cols = await db.getAllAsync(`PRAGMA table_info(${prefix}entries)`);
5041
+ const existing = new Set(cols.map((c) => c.name));
5042
+ if (!existing.has("source_pointer")) {
5043
+ await db.execAsync(`ALTER TABLE ${prefix}entries ADD COLUMN source_pointer TEXT`);
5044
+ }
5045
+ }
4932
5046
  }
4933
5047
  ];
4934
5048
  async function createLegacySourceTypeIndex(db, prefix) {
@@ -5098,7 +5212,8 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
5098
5212
  promptEvents,
5099
5213
  currentFacts,
5100
5214
  promptOverride,
5101
- ontologyContext
5215
+ ontologyContext,
5216
+ ctx.guidance
5102
5217
  );
5103
5218
  let responseText;
5104
5219
  try {
@@ -5196,9 +5311,20 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
5196
5311
  access_count: 0,
5197
5312
  deleted_at: null,
5198
5313
  okf_type: normalized.okf_type,
5314
+ // Legacy writes no pointer (spec §Legacy path): the column stays null
5315
+ // on every legacy fact, and the legacy prompt keeps its exact text.
5316
+ source_pointer: null,
5199
5317
  ...grounding?.trust
5200
5318
  };
5201
5319
  await deps.entryRepo.upsert(factObj, tx);
5320
+ const volunteeredSourceEvent = facts[validFactItemIndexes[k]]?.source_event;
5321
+ if (volunteeredSourceEvent !== void 0 && volunteeredSourceEvent !== null) {
5322
+ diagBuffer.push({
5323
+ ...diagBase,
5324
+ code: "source_pointer_unresolved",
5325
+ detail: { factId: id, itemIndex: validFactItemIndexes[k], reason: "unsupported_strategy" }
5326
+ });
5327
+ }
5202
5328
  insertedFacts.push({ id, entity_id: entityId, title: fact.title, body: fact.body, tags: JSON.stringify(fact.tags) });
5203
5329
  factsForDedupe.push(factObj);
5204
5330
  titleIndex.set(normalizeTitleKey(fact.title), { id, okf_type: normalized.okf_type });
@@ -5270,7 +5396,7 @@ var OPS_MAX_EVENTS_PER_PASS = 50;
5270
5396
  var OPS_MAX_EXTRACT_CHARS = 24e3;
5271
5397
  var RESOLVE_RESERVE_FACTOR = 2;
5272
5398
  var estimatePrompt = (p) => estimateTokens(p.systemPrompt) + estimateTokens(p.userPrompt);
5273
- async function selectBatch(deps, entityId, wm, meter) {
5399
+ async function selectBatch(deps, entityId, wm, meter, guidance) {
5274
5400
  const events = await deps.eventRepo.getAfter(entityId, wm, OPS_MAX_EVENTS_PER_PASS);
5275
5401
  if (events.length === 0) return { batch: [] };
5276
5402
  let n = 0;
@@ -5284,7 +5410,7 @@ async function selectBatch(deps, entityId, wm, meter) {
5284
5410
  if (meter && meter.budget !== void 0) {
5285
5411
  const ontologyContext = await deps.ontologyService?.buildPromptContext(entityId) ?? null;
5286
5412
  for (; ; ) {
5287
- const need = RESOLVE_RESERVE_FACTOR * estimatePrompt(deps.promptService.buildOpsExtractPrompt(batch, ontologyContext));
5413
+ const need = RESOLVE_RESERVE_FACTOR * estimatePrompt(deps.promptService.buildOpsExtractPrompt(batch, ontologyContext, guidance));
5288
5414
  if (meter.fits(need)) break;
5289
5415
  if (batch.length === 1) return { budgetStop: { requiredEstimate: need } };
5290
5416
  batch = labelEvents(events.slice(0, Math.max(1, Math.floor(batch.length / 2))));
@@ -5295,7 +5421,7 @@ async function selectBatch(deps, entityId, wm, meter) {
5295
5421
  async function runExtract(deps, ctx, batch) {
5296
5422
  const { entityId, trigger } = ctx;
5297
5423
  const ontologyContext = await deps.ontologyService?.buildPromptContext(entityId) ?? null;
5298
- const prompt = deps.promptService.buildOpsExtractPrompt(batch, ontologyContext);
5424
+ const prompt = deps.promptService.buildOpsExtractPrompt(batch, ontologyContext, ctx.guidance);
5299
5425
  const text = await callLlm(deps.options, { operation: "librarian", entityId, trigger, meter: ctx.meter }, prompt);
5300
5426
  const parsed = parseJsonResponse(text);
5301
5427
  const base = { entityId, operation: "librarian", trigger };
@@ -5312,9 +5438,23 @@ async function runExtract(deps, ctx, batch) {
5312
5438
  return;
5313
5439
  }
5314
5440
  const r = raw;
5315
- const sourceLabel = typeof r.source_event === "string" && byLabel.has(r.source_event) ? r.source_event : null;
5441
+ let sourceEventId = null;
5442
+ let sourcePartIndex = null;
5443
+ let pointerUnresolved;
5444
+ const rawSourceEvent = r.source_event;
5445
+ if (rawSourceEvent === void 0 || rawSourceEvent === null) {
5446
+ pointerUnresolved = "missing";
5447
+ } else if (typeof rawSourceEvent === "string" && byLabel.has(rawSourceEvent)) {
5448
+ const labeled = byLabel.get(rawSourceEvent);
5449
+ sourceEventId = labeled.event.id;
5450
+ sourcePartIndex = batch.findIndex((b) => b.label === rawSourceEvent);
5451
+ pointerUnresolved = null;
5452
+ } else {
5453
+ pointerUnresolved = "unknown_label";
5454
+ }
5455
+ const sourceLabel = typeof rawSourceEvent === "string" && byLabel.has(rawSourceEvent) ? rawSourceEvent : null;
5316
5456
  const validFrom = parseValidFrom(r.valid_from) ?? (sourceLabel ? byLabel.get(sourceLabel).at : defaultValidFrom);
5317
- candidates.push({ index, fact, sourceLabel, validFrom });
5457
+ candidates.push({ index, fact, sourceLabel, sourceEventId, sourcePartIndex, pointerUnresolved, validFrom });
5318
5458
  });
5319
5459
  const tasks = [];
5320
5460
  (Array.isArray(parsed.tasks) ? parsed.tasks : []).forEach((raw, index) => {
@@ -5591,6 +5731,17 @@ var TemporalService = class {
5591
5731
  };
5592
5732
 
5593
5733
  // src/services/librarian/ops/apply.ts
5734
+ function buildSourcePointer(candidate, verdict, groundingOn, groundingCorpus) {
5735
+ if (candidate.sourceEventId === null) return null;
5736
+ let quote = null;
5737
+ if (groundingOn && verdict?.status === "grounded" && candidate.sourcePartIndex !== null) {
5738
+ const part = groundingCorpus?.[candidate.sourcePartIndex];
5739
+ if (part !== void 0) {
5740
+ quote = verdict.retained.find((q) => part.includes(q)) ?? null;
5741
+ }
5742
+ }
5743
+ return { event_id: candidate.sourceEventId, ref: null, quote, position: null };
5744
+ }
5594
5745
  async function applyOps(deps, ctx, input) {
5595
5746
  const { entityId, trigger } = ctx;
5596
5747
  const diagBase = { entityId, operation: "librarian", trigger };
@@ -5619,7 +5770,8 @@ async function applyOps(deps, ctx, input) {
5619
5770
  const drops = [];
5620
5771
  const normalized = deps.ontologyService?.validateAndNormalizeFact(fact, manifest, { strict: false, drops }) ?? { okf_type: null, edges: [] };
5621
5772
  for (const d of drops) input.diagnostics.push(edgeDropDiagnostic(d, { ...diagBase, factId: id }));
5622
- const g2 = grounding ? groundingOutcome(checkGrounding(fact.evidence, input.groundingCorpus ?? [], grounding), now) : null;
5773
+ const gVerdict = grounding ? checkGrounding(fact.evidence, input.groundingCorpus ?? [], grounding) : null;
5774
+ const g2 = gVerdict ? groundingOutcome(gVerdict, now) : null;
5623
5775
  if (g2?.diagnostic) {
5624
5776
  input.diagnostics.push({
5625
5777
  ...diagBase,
@@ -5627,6 +5779,7 @@ async function applyOps(deps, ctx, input) {
5627
5779
  detail: { factId: id, itemIndex: g.candidate.index, reason: g2.diagnostic.reason }
5628
5780
  });
5629
5781
  }
5782
+ const pointer = buildSourcePointer(g.candidate, gVerdict, grounding !== void 0 && grounding !== null, input.groundingCorpus);
5630
5783
  const row = {
5631
5784
  id,
5632
5785
  entity_id: entityId,
@@ -5643,11 +5796,19 @@ async function applyOps(deps, ctx, input) {
5643
5796
  access_count: 0,
5644
5797
  deleted_at: null,
5645
5798
  okf_type: normalized.okf_type,
5799
+ source_pointer: pointer,
5646
5800
  ...g2?.trust,
5647
5801
  ...draft ? { lifecycle_status: "draft" } : {}
5648
5802
  };
5649
5803
  await deps.entryRepo.upsert(row, tx);
5650
5804
  await deps.entryRepo.setTemporal(id, entityId, { valid_from: validFrom }, tx);
5805
+ if (g.candidate.pointerUnresolved !== null) {
5806
+ input.diagnostics.push({
5807
+ ...diagBase,
5808
+ code: "source_pointer_unresolved",
5809
+ detail: { factId: id, itemIndex: g.candidate.index, reason: g.candidate.pointerUnresolved }
5810
+ });
5811
+ }
5651
5812
  titleIndex.set(normalizeTitleKey(title), { id, okf_type: normalized.okf_type });
5652
5813
  if (normalized.edges.length > 0) pendingEdges.push({ sourceId: id, sourceType: normalized.okf_type, edges: normalized.edges });
5653
5814
  const textChanged = title !== fact.title || body !== fact.body;
@@ -5753,7 +5914,7 @@ var runOpsLibrarianPass = async (deps, ctx) => {
5753
5914
  const cfg = resolveGateConfig(deps.options.config?.librarian?.gate);
5754
5915
  await deps.seedWatermark(entityId);
5755
5916
  const wm = await deps.getWatermark(entityId);
5756
- const sel = await selectBatch(deps, entityId, wm, ctx.meter);
5917
+ const sel = await selectBatch(deps, entityId, wm, ctx.meter, ctx.guidance);
5757
5918
  if ("budgetStop" in sel) return { processedThrough: null, factsWritten: 0, budgetStop: sel.budgetStop };
5758
5919
  if (sel.batch.length === 0) return { processedThrough: null, factsWritten: 0 };
5759
5920
  if (!deps.searchService.isKeywordAvailable() && await gateNeedsKeyword(deps, entityId)) {
@@ -6391,7 +6552,17 @@ var MaintenanceService = class {
6391
6552
  * A budget-stopped pass wrote nothing and must not move the watermark.
6392
6553
  */
6393
6554
  async runLibrarianPass(ctx) {
6394
- const result = await runLibrarianStrategy(this.librarianDeps(), ctx);
6555
+ const { guidance, diagnostic } = PromptService.resolveGuidance(this.options.config, ctx.entityId);
6556
+ if (diagnostic) {
6557
+ emitDiagnostic(this.options, {
6558
+ code: diagnostic.code,
6559
+ operation: "librarian",
6560
+ trigger: ctx.trigger,
6561
+ entityId: ctx.entityId,
6562
+ detail: diagnostic.detail
6563
+ });
6564
+ }
6565
+ const result = await runLibrarianStrategy(this.librarianDeps(), { ...ctx, guidance });
6395
6566
  if (result.processedThrough && !result.budgetStop) {
6396
6567
  await this.advanceLibrarianWatermark(ctx.entityId, result.processedThrough);
6397
6568
  }
@@ -6661,6 +6832,7 @@ var MaintenanceService = class {
6661
6832
  source_type: "librarian_inferred",
6662
6833
  source_hash: null,
6663
6834
  source_ref: null,
6835
+ source_pointer: null,
6664
6836
  created_at: now,
6665
6837
  updated_at: now,
6666
6838
  last_accessed_at: null,
@@ -7062,6 +7234,59 @@ var MaintenanceService = class {
7062
7234
  }
7063
7235
  };
7064
7236
 
7237
+ // src/utils/sourcePointer.ts
7238
+ var POINTER_SLOTS = ["event_id", "ref", "quote", "position"];
7239
+ function isStringOrNull(v) {
7240
+ return v === null || typeof v === "string";
7241
+ }
7242
+ function isValidPosition(v) {
7243
+ if (v === null) return true;
7244
+ if (typeof v !== "object" || v === null || Array.isArray(v)) return false;
7245
+ const o = v;
7246
+ const keys = Object.keys(o);
7247
+ if (keys.length !== 2 || !("start" in o) || !("length" in o)) return false;
7248
+ const { start, length } = o;
7249
+ return typeof start === "number" && Number.isInteger(start) && start >= 0 && typeof length === "number" && Number.isInteger(length) && length >= 0;
7250
+ }
7251
+ function validateSourcePointerValue(v) {
7252
+ if (v === null) return null;
7253
+ if (typeof v !== "object" || Array.isArray(v)) return void 0;
7254
+ const o = v;
7255
+ const keys = Object.keys(o);
7256
+ for (const k of keys) {
7257
+ if (!POINTER_SLOTS.includes(k)) return void 0;
7258
+ }
7259
+ 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"])) {
7260
+ return void 0;
7261
+ }
7262
+ if (!isValidPosition(o["position"] === void 0 ? null : o["position"])) return void 0;
7263
+ const normalized = {
7264
+ event_id: o["event_id"] ?? null,
7265
+ ref: o["ref"] ?? null,
7266
+ quote: o["quote"] ?? null,
7267
+ position: o["position"] ?? null
7268
+ };
7269
+ if (normalized.event_id === null && normalized.ref === null && normalized.quote === null && normalized.position === null) {
7270
+ return null;
7271
+ }
7272
+ return normalized;
7273
+ }
7274
+ function parseStoredSourcePointer(raw) {
7275
+ if (raw === null || raw === void 0) return null;
7276
+ if (typeof raw !== "string") return null;
7277
+ let parsed;
7278
+ try {
7279
+ parsed = JSON.parse(raw);
7280
+ } catch {
7281
+ return null;
7282
+ }
7283
+ const v = validateSourcePointerValue(parsed);
7284
+ return v === void 0 ? null : v;
7285
+ }
7286
+ function serializeSourcePointer(p) {
7287
+ return p ? JSON.stringify(p) : null;
7288
+ }
7289
+
7065
7290
  // src/services/importEventStamps.ts
7066
7291
  var DATE_MAX = 864e13;
7067
7292
  var DECIMAL_TEXT = /^\s*[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?\s*$/;
@@ -7329,6 +7554,19 @@ var ImportExportService = class {
7329
7554
  );
7330
7555
  }
7331
7556
  }
7557
+ const hasSourcePointerKey = fact["source_pointer"] !== void 0;
7558
+ const rawPointerValue = hasSourcePointerKey ? fact["source_pointer"] : void 0;
7559
+ const pointerValidated = hasSourcePointerKey ? validateSourcePointerValue(rawPointerValue) : null;
7560
+ if (pointerValidated === void 0) {
7561
+ emitDiagnostic(this.options, {
7562
+ code: "source_pointer_invalid",
7563
+ operation: "importDump",
7564
+ trigger: "call",
7565
+ entityId,
7566
+ detail: { factId: fact.id }
7567
+ });
7568
+ }
7569
+ const sourcePointer = pointerValidated === void 0 ? null : pointerValidated;
7332
7570
  const factObj = {
7333
7571
  id: fact.id,
7334
7572
  entity_id: entityId,
@@ -7346,6 +7584,7 @@ var ImportExportService = class {
7346
7584
  deleted_at: fact.deleted_at,
7347
7585
  embedding_blob: blobData ?? void 0,
7348
7586
  okf_type: fact.okf_type ?? null,
7587
+ source_pointer: sourcePointer,
7349
7588
  // OKF v0.2 — forwarded as-is; parseOkfBundle / the caller is responsible for
7350
7589
  // populating these per spec, importDump does not derive or validate them.
7351
7590
  lifecycle_status: fact.lifecycle_status ?? "stable",
@@ -7363,7 +7602,7 @@ var ImportExportService = class {
7363
7602
  return { last_verified_at: latest?.at ?? null, last_verified_by: latest?.by ?? null };
7364
7603
  })()
7365
7604
  };
7366
- await this.entryRepo.upsertForImport(factObj, tx);
7605
+ await this.entryRepo.upsertForImport(factObj, tx, hasSourcePointerKey);
7367
7606
  await this.entryRepo.setTemporal(fact.id, entityId, {
7368
7607
  valid_from: fact.valid_from ?? null,
7369
7608
  valid_to: fact.valid_to ?? null,
@@ -8993,6 +9232,6 @@ var WriteService = class {
8993
9232
  }
8994
9233
  };
8995
9234
 
8996
- export { BaseRepository, CURRENT_SCHEMA_VERSION, DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DiagnosticBuffer, EMBED_CHARS_CEILING, EdgeRepository, EmbeddingService, FTS5_DRAIN_CHUNK, FTS5_REBUILD_SNAPSHOT_KEY, FTS5_REBUILD_WM_KEY, FTS5_RECLAIM_MERGE_PAGES, FTS5_RETIRED_COUNTER_KEY, FTS5_RETIRED_TABLES_KEY, FTS5_STATE_KEY, FTS5_SWEEP_CURSOR_KEY, HEAL_ANCHORS_PER_CANDIDATE, HEAL_BATCH_SIZE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, HEAL_RECHECK_MS, HOOK_TIMEOUT_MARKER, ImportExportService, IngestionService, JobManager, MAX_EMBED_ATTEMPTS, MIGRATIONS, MaintenanceService, MetadataRepository, ONTOLOGY_BACKFILL_BATCH_SIZE, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_RECHECK_MS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, PromptService, PrunePartialFailureError, RetrievalService, SearchService, TemporalService, UnavailableIndexStrategy, UsageMeter, VectorRemovalRepository, VectorRemovalService, WikiBusyError, WikiDraftNotFound, WikiDuplicateHashError, WikiExternalDeletionError, WikiGraphNodeOwnershipConflict, WikiIngestEmptyError, WikiInvalidReadOptions, WikiMigrationRequiredError, WikiParseError, WikiSearchUnavailableError, WikiSourceRefHashCollision, WikiStrictOntologyViolation, WikiSupersedeError, WikiTransactionError, WriteService, __privateAdd, __privateGet, __privateSet, assertEntityId, assertEpochMs, chunkText, configureRandomSource, createLegacySourceTypeIndex, createdAtValue, detectSchemaVersion, drainChunkSql, drainHiSql, edgeTripleAllowed, emitDiagnostic, emptyManifest, entityDrainChunkSql, entityDrainHiSql, entitySummaryMetaKey, extractSqliteCode, factTokenCost, fts5LedgerDropSql, fts5PendingIndexesDdl, fts5TablesDdl, fts5TriggerNames, fts5TriggersDdl, generateId, idDrainChunkSql, idReindexChunkSql, isLiveAt, isRetiredTableName, isUsableDate, isWikiSearchUnavailableError, liveAtSql, normalizeSourceHash, normalizeSourceRef, normalizeTitleKey, packFactsByBudget, parseEmbedding, parseJsonArray, parseJsonObject, probePendingWork, readRebuildProgress, reanchorRebuildFingerprint, resolveEdgeDefinitions, resolveGrounding, resolveLibrarianStrategy, resolveNodeType, retiredTableName, runSourceRefNormalize, safeSlice, setupDatabase, sweepChunkSql, sweepHiSql, typeSatisfies, validateInlineEdges, validateManifest, warnChangedDefaultsOnce, windowChunkSql, windowHiSql, writeNormalizeStamp, writeRebuildStart };
8997
- //# sourceMappingURL=chunk-EKYWAR2E.mjs.map
8998
- //# sourceMappingURL=chunk-EKYWAR2E.mjs.map
9235
+ export { BaseRepository, CURRENT_SCHEMA_VERSION, DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DiagnosticBuffer, EMBED_CHARS_CEILING, EdgeRepository, EmbeddingService, FTS5_DRAIN_CHUNK, FTS5_REBUILD_SNAPSHOT_KEY, FTS5_REBUILD_WM_KEY, FTS5_RECLAIM_MERGE_PAGES, FTS5_RETIRED_COUNTER_KEY, FTS5_RETIRED_TABLES_KEY, FTS5_STATE_KEY, FTS5_SWEEP_CURSOR_KEY, HEAL_ANCHORS_PER_CANDIDATE, HEAL_BATCH_SIZE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, HEAL_RECHECK_MS, HOOK_TIMEOUT_MARKER, ImportExportService, IngestionService, JobManager, MAX_EMBED_ATTEMPTS, MIGRATIONS, MaintenanceService, MetadataRepository, ONTOLOGY_BACKFILL_BATCH_SIZE, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_RECHECK_MS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, PromptService, PrunePartialFailureError, RetrievalService, SearchService, TemporalService, UnavailableIndexStrategy, UsageMeter, VectorRemovalRepository, VectorRemovalService, WikiBusyError, WikiDraftNotFound, WikiDuplicateHashError, WikiExternalDeletionError, WikiGraphNodeOwnershipConflict, WikiIngestEmptyError, WikiInvalidReadOptions, WikiMigrationRequiredError, WikiParseError, WikiSearchUnavailableError, WikiSourceRefHashCollision, WikiStrictOntologyViolation, WikiSupersedeError, WikiTransactionError, WriteService, __privateAdd, __privateGet, __privateSet, assertEntityId, assertEpochMs, chunkText, configureRandomSource, createLegacySourceTypeIndex, createdAtValue, detectSchemaVersion, drainChunkSql, drainHiSql, edgeTripleAllowed, emitDiagnostic, emptyManifest, entityDrainChunkSql, entityDrainHiSql, entitySummaryMetaKey, extractSqliteCode, factTokenCost, fts5LedgerDropSql, fts5PendingIndexesDdl, fts5TablesDdl, fts5TriggerNames, fts5TriggersDdl, generateId, idDrainChunkSql, idReindexChunkSql, isLiveAt, isRetiredTableName, isUsableDate, isWikiSearchUnavailableError, liveAtSql, normalizeSourceHash, normalizeSourceRef, normalizeTitleKey, packFactsByBudget, parseEmbedding, parseJsonArray, parseJsonObject, parseStoredSourcePointer, probePendingWork, readRebuildProgress, reanchorRebuildFingerprint, resolveEdgeDefinitions, resolveGrounding, resolveLibrarianStrategy, resolveNodeType, retiredTableName, runSourceRefNormalize, safeSlice, serializeSourcePointer, setupDatabase, sweepChunkSql, sweepHiSql, typeSatisfies, validateInlineEdges, validateManifest, validateSourcePointerValue, warnChangedDefaultsOnce, windowChunkSql, windowHiSql, writeNormalizeStamp, writeRebuildStart };
9236
+ //# sourceMappingURL=chunk-SIJD5GEF.mjs.map
9237
+ //# sourceMappingURL=chunk-SIJD5GEF.mjs.map