@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 +1 -1
- package/dist/{chunk-EKYWAR2E.mjs → chunk-SIJD5GEF.mjs} +270 -31
- package/dist/chunk-SIJD5GEF.mjs.map +1 -0
- package/dist/index.d.mts +8 -3
- package/dist/index.d.ts +8 -3
- package/dist/index.js +344 -48
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +77 -23
- package/dist/index.mjs.map +1 -1
- package/dist/{testing-Og5x9rFu.d.mts → testing-CmcCGx0_.d.mts} +108 -10
- package/dist/{testing-Og5x9rFu.d.ts → testing-CmcCGx0_.d.ts} +108 -10
- package/dist/testing.d.mts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +248 -25
- package/dist/testing.js.map +1 -1
- package/dist/testing.mjs +1 -1
- package/package.json +2 -2
- package/dist/chunk-EKYWAR2E.mjs.map +0 -1
package/dist/index.js
CHANGED
|
@@ -40,7 +40,11 @@ var SEVERITY = {
|
|
|
40
40
|
event_created_at_clamped: "warn",
|
|
41
41
|
event_created_at_restamped: "info",
|
|
42
42
|
external_deletion_pending: "warn",
|
|
43
|
-
external_deletion_discarded: "warn"
|
|
43
|
+
external_deletion_discarded: "warn",
|
|
44
|
+
guidance_too_long: "warn",
|
|
45
|
+
guidance_resolver_failed: "warn",
|
|
46
|
+
source_pointer_unresolved: "warn",
|
|
47
|
+
source_pointer_invalid: "warn"
|
|
44
48
|
};
|
|
45
49
|
var MESSAGE = {
|
|
46
50
|
ingest_chunk_failed: "One or more document chunks failed to parse or generate.",
|
|
@@ -66,7 +70,11 @@ var MESSAGE = {
|
|
|
66
70
|
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.",
|
|
67
71
|
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.",
|
|
68
72
|
external_deletion_pending: "Removals owed to the external vector index are still pending.",
|
|
69
|
-
external_deletion_discarded: "Pending external vector removals were discarded because forceDeleteIgnoreRankerHook is set."
|
|
73
|
+
external_deletion_discarded: "Pending external vector removals were discarded because forceDeleteIgnoreRankerHook is set.",
|
|
74
|
+
guidance_too_long: "The configured guidance exceeded the length cap and was not sent for this pass.",
|
|
75
|
+
guidance_resolver_failed: "The per-entity guidance resolver failed; its value was not used for this pass.",
|
|
76
|
+
source_pointer_unresolved: "A stored librarian fact carries no source pointer because the model answer could not yield one.",
|
|
77
|
+
source_pointer_invalid: "Import met a malformed source pointer value and stored a null pointer."
|
|
70
78
|
};
|
|
71
79
|
var warnedNonFunction = /* @__PURE__ */ new WeakSet();
|
|
72
80
|
function copyDetail(detail) {
|
|
@@ -941,7 +949,8 @@ async function setupDatabase(db, prefix) {
|
|
|
941
949
|
valid_from INTEGER,
|
|
942
950
|
valid_to INTEGER,
|
|
943
951
|
superseded_by TEXT,
|
|
944
|
-
superseded_at INTEGER
|
|
952
|
+
superseded_at INTEGER,
|
|
953
|
+
source_pointer TEXT
|
|
945
954
|
);
|
|
946
955
|
|
|
947
956
|
CREATE INDEX IF NOT EXISTS ${prefix}entries_entity_idx ON ${prefix}entries(entity_id);
|
|
@@ -1590,6 +1599,17 @@ var MIGRATIONS = [
|
|
|
1590
1599
|
);
|
|
1591
1600
|
if (row?.n) await db.execAsync(fts5PendingIndexesDdl(prefix));
|
|
1592
1601
|
}
|
|
1602
|
+
},
|
|
1603
|
+
{
|
|
1604
|
+
version: 16,
|
|
1605
|
+
description: "Source pointers on librarian facts: nullable source_pointer TEXT on entries",
|
|
1606
|
+
run: async (db, prefix) => {
|
|
1607
|
+
const cols = await db.getAllAsync(`PRAGMA table_info(${prefix}entries)`);
|
|
1608
|
+
const existing = new Set(cols.map((c) => c.name));
|
|
1609
|
+
if (!existing.has("source_pointer")) {
|
|
1610
|
+
await db.execAsync(`ALTER TABLE ${prefix}entries ADD COLUMN source_pointer TEXT`);
|
|
1611
|
+
}
|
|
1612
|
+
}
|
|
1593
1613
|
}
|
|
1594
1614
|
];
|
|
1595
1615
|
async function createLegacySourceTypeIndex(db, prefix) {
|
|
@@ -1830,6 +1850,61 @@ function assertEpochMs(name, v) {
|
|
|
1830
1850
|
}
|
|
1831
1851
|
return Math.trunc(v);
|
|
1832
1852
|
}
|
|
1853
|
+
|
|
1854
|
+
// src/utils/sourcePointer.ts
|
|
1855
|
+
var POINTER_SLOTS = ["event_id", "ref", "quote", "position"];
|
|
1856
|
+
function isStringOrNull(v) {
|
|
1857
|
+
return v === null || typeof v === "string";
|
|
1858
|
+
}
|
|
1859
|
+
function isValidPosition(v) {
|
|
1860
|
+
if (v === null) return true;
|
|
1861
|
+
if (typeof v !== "object" || v === null || Array.isArray(v)) return false;
|
|
1862
|
+
const o = v;
|
|
1863
|
+
const keys = Object.keys(o);
|
|
1864
|
+
if (keys.length !== 2 || !("start" in o) || !("length" in o)) return false;
|
|
1865
|
+
const { start, length } = o;
|
|
1866
|
+
return typeof start === "number" && Number.isInteger(start) && start >= 0 && typeof length === "number" && Number.isInteger(length) && length >= 0;
|
|
1867
|
+
}
|
|
1868
|
+
function validateSourcePointerValue(v) {
|
|
1869
|
+
if (v === null) return null;
|
|
1870
|
+
if (typeof v !== "object" || Array.isArray(v)) return void 0;
|
|
1871
|
+
const o = v;
|
|
1872
|
+
const keys = Object.keys(o);
|
|
1873
|
+
for (const k of keys) {
|
|
1874
|
+
if (!POINTER_SLOTS.includes(k)) return void 0;
|
|
1875
|
+
}
|
|
1876
|
+
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"])) {
|
|
1877
|
+
return void 0;
|
|
1878
|
+
}
|
|
1879
|
+
if (!isValidPosition(o["position"] === void 0 ? null : o["position"])) return void 0;
|
|
1880
|
+
const normalized = {
|
|
1881
|
+
event_id: o["event_id"] ?? null,
|
|
1882
|
+
ref: o["ref"] ?? null,
|
|
1883
|
+
quote: o["quote"] ?? null,
|
|
1884
|
+
position: o["position"] ?? null
|
|
1885
|
+
};
|
|
1886
|
+
if (normalized.event_id === null && normalized.ref === null && normalized.quote === null && normalized.position === null) {
|
|
1887
|
+
return null;
|
|
1888
|
+
}
|
|
1889
|
+
return normalized;
|
|
1890
|
+
}
|
|
1891
|
+
function parseStoredSourcePointer(raw) {
|
|
1892
|
+
if (raw === null || raw === void 0) return null;
|
|
1893
|
+
if (typeof raw !== "string") return null;
|
|
1894
|
+
let parsed;
|
|
1895
|
+
try {
|
|
1896
|
+
parsed = JSON.parse(raw);
|
|
1897
|
+
} catch {
|
|
1898
|
+
return null;
|
|
1899
|
+
}
|
|
1900
|
+
const v = validateSourcePointerValue(parsed);
|
|
1901
|
+
return v === void 0 ? null : v;
|
|
1902
|
+
}
|
|
1903
|
+
function serializeSourcePointer(p) {
|
|
1904
|
+
return p ? JSON.stringify(p) : null;
|
|
1905
|
+
}
|
|
1906
|
+
|
|
1907
|
+
// src/repositories/EntryRepository.ts
|
|
1833
1908
|
function mapRowToFact(row) {
|
|
1834
1909
|
const tags = (() => {
|
|
1835
1910
|
if (Array.isArray(row.tags)) return row.tags;
|
|
@@ -1843,7 +1918,8 @@ function mapRowToFact(row) {
|
|
|
1843
1918
|
const okf_verified = parseJsonArray(row.okf_verified, []);
|
|
1844
1919
|
const now = Date.now();
|
|
1845
1920
|
const staleAfterRaw = row.stale_after != null ? Number(row.stale_after) : null;
|
|
1846
|
-
|
|
1921
|
+
const sourcePointer = parseStoredSourcePointer(row.source_pointer);
|
|
1922
|
+
const mapped = {
|
|
1847
1923
|
id: row.id,
|
|
1848
1924
|
entity_id: row.entity_id,
|
|
1849
1925
|
title: row.title,
|
|
@@ -1876,8 +1952,13 @@ function mapRowToFact(row) {
|
|
|
1876
1952
|
...row.valid_from != null ? { valid_from: Number(row.valid_from) } : {},
|
|
1877
1953
|
...row.valid_to != null ? { valid_to: Number(row.valid_to) } : {},
|
|
1878
1954
|
...row.superseded_by != null ? { superseded_by: String(row.superseded_by) } : {},
|
|
1879
|
-
...row.superseded_at != null ? { superseded_at: Number(row.superseded_at) } : {}
|
|
1955
|
+
...row.superseded_at != null ? { superseded_at: Number(row.superseded_at) } : {},
|
|
1956
|
+
// Source pointer (specs/source-pointers): key appears only when non-null,
|
|
1957
|
+
// same temporal-fields pattern. Tolerant read: a malformed stored value
|
|
1958
|
+
// reads as null without throwing (test 1).
|
|
1959
|
+
...sourcePointer ? { source_pointer: sourcePointer } : {}
|
|
1880
1960
|
};
|
|
1961
|
+
return mapped;
|
|
1881
1962
|
}
|
|
1882
1963
|
function normalizeEmbeddingBlobValue(blob) {
|
|
1883
1964
|
if (blob instanceof Uint8Array) return blob;
|
|
@@ -1992,7 +2073,7 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
1992
2073
|
const existingRow = await executor.getFirstAsync(
|
|
1993
2074
|
`SELECT id, entity_id, lifecycle_status, stale_after, generated_by,
|
|
1994
2075
|
okf_sources, okf_verified, okf_usage_window,
|
|
1995
|
-
last_verified_at, last_verified_by
|
|
2076
|
+
last_verified_at, last_verified_by, source_pointer
|
|
1996
2077
|
FROM ${this.prefix}entries WHERE id = ?`,
|
|
1997
2078
|
[fact.id]
|
|
1998
2079
|
);
|
|
@@ -2006,8 +2087,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
2006
2087
|
source_hash, source_ref, created_at, updated_at, last_accessed_at, access_count,
|
|
2007
2088
|
deleted_at, embedding_blob, embedding, okf_type,
|
|
2008
2089
|
lifecycle_status, stale_after, generated_by, last_verified_at, last_verified_by,
|
|
2009
|
-
okf_sources, okf_verified, okf_usage_window
|
|
2010
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
2090
|
+
okf_sources, okf_verified, okf_usage_window, source_pointer
|
|
2091
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
2011
2092
|
ON CONFLICT(id) DO UPDATE SET
|
|
2012
2093
|
title = excluded.title,
|
|
2013
2094
|
body = excluded.body,
|
|
@@ -2055,7 +2136,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
2055
2136
|
fact.last_verified_by ?? null,
|
|
2056
2137
|
fact.okf_sources ? JSON.stringify(fact.okf_sources) : null,
|
|
2057
2138
|
fact.okf_verified ? JSON.stringify(fact.okf_verified) : null,
|
|
2058
|
-
fact.okf_usage_window ? JSON.stringify(fact.okf_usage_window) : null
|
|
2139
|
+
fact.okf_usage_window ? JSON.stringify(fact.okf_usage_window) : null,
|
|
2140
|
+
serializeSourcePointer(fact.source_pointer)
|
|
2059
2141
|
]
|
|
2060
2142
|
);
|
|
2061
2143
|
if (result.changes === 0) {
|
|
@@ -2078,7 +2160,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
2078
2160
|
okf_verified: parseJsonArray(existingRow.okf_verified, []),
|
|
2079
2161
|
okf_usage_window: parseJsonObject(existingRow.okf_usage_window),
|
|
2080
2162
|
last_verified_at: existingRow.last_verified_at != null ? Number(existingRow.last_verified_at) : null,
|
|
2081
|
-
last_verified_by: existingRow.last_verified_by ?? null
|
|
2163
|
+
last_verified_by: existingRow.last_verified_by ?? null,
|
|
2164
|
+
source_pointer: parseStoredSourcePointer(existingRow.source_pointer)
|
|
2082
2165
|
} : null;
|
|
2083
2166
|
await this.outbox.push({
|
|
2084
2167
|
entityId: fact.entity_id,
|
|
@@ -2138,7 +2221,7 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
2138
2221
|
const rows = await executor.getAllAsync(sql, args);
|
|
2139
2222
|
return rows.map((row) => row.id);
|
|
2140
2223
|
}
|
|
2141
|
-
async upsertForImport(fact, tx) {
|
|
2224
|
+
async upsertForImport(fact, tx, sourcePointerPresent = false) {
|
|
2142
2225
|
const executor = this.getExecutor(tx);
|
|
2143
2226
|
const tagsJson = JSON.stringify(fact.tags);
|
|
2144
2227
|
const embeddingBlob = this.normalizeEmbeddingBlob(fact.embedding_blob);
|
|
@@ -2148,8 +2231,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
2148
2231
|
source_hash, source_ref, created_at, updated_at, last_accessed_at, access_count,
|
|
2149
2232
|
deleted_at, embedding_blob, embedding, okf_type,
|
|
2150
2233
|
lifecycle_status, stale_after, generated_by, last_verified_at, last_verified_by,
|
|
2151
|
-
okf_sources, okf_verified, okf_usage_window
|
|
2152
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
2234
|
+
okf_sources, okf_verified, okf_usage_window, source_pointer
|
|
2235
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
2153
2236
|
ON CONFLICT(id) DO UPDATE SET
|
|
2154
2237
|
entity_id = excluded.entity_id,
|
|
2155
2238
|
title = excluded.title,
|
|
@@ -2177,7 +2260,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
2177
2260
|
last_verified_by = excluded.last_verified_by,
|
|
2178
2261
|
okf_sources = excluded.okf_sources,
|
|
2179
2262
|
okf_verified = excluded.okf_verified,
|
|
2180
|
-
okf_usage_window = excluded.okf_usage_window
|
|
2263
|
+
okf_usage_window = excluded.okf_usage_window,
|
|
2264
|
+
source_pointer = CASE WHEN ? THEN excluded.source_pointer ELSE source_pointer END`,
|
|
2181
2265
|
[
|
|
2182
2266
|
fact.id,
|
|
2183
2267
|
fact.entity_id,
|
|
@@ -2204,7 +2288,11 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
2204
2288
|
fact.last_verified_by ?? null,
|
|
2205
2289
|
fact.okf_sources ? JSON.stringify(fact.okf_sources) : null,
|
|
2206
2290
|
fact.okf_verified ? JSON.stringify(fact.okf_verified) : null,
|
|
2207
|
-
fact.okf_usage_window ? JSON.stringify(fact.okf_usage_window) : null
|
|
2291
|
+
fact.okf_usage_window ? JSON.stringify(fact.okf_usage_window) : null,
|
|
2292
|
+
serializeSourcePointer(fact.source_pointer),
|
|
2293
|
+
// The presence flag binds to the SET clause's CASE, AFTER the INSERT
|
|
2294
|
+
// values above.
|
|
2295
|
+
sourcePointerPresent ? 1 : 0
|
|
2208
2296
|
]
|
|
2209
2297
|
);
|
|
2210
2298
|
return result;
|
|
@@ -6211,6 +6299,14 @@ function groundingOutcome(verdict, now) {
|
|
|
6211
6299
|
}
|
|
6212
6300
|
|
|
6213
6301
|
// src/prompts.ts
|
|
6302
|
+
var LEAVE_OUT_RULE_SENTENCE = "Memory leaves out what a better record already holds, and points to that record.";
|
|
6303
|
+
var GUIDANCE_MAX_CHARS = 2e3;
|
|
6304
|
+
function guidanceSection(guidance) {
|
|
6305
|
+
return `--- Host guidance ---
|
|
6306
|
+
${guidance}
|
|
6307
|
+
--- End host guidance ---
|
|
6308
|
+
${LEAVE_OUT_RULE_SENTENCE}`;
|
|
6309
|
+
}
|
|
6214
6310
|
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.
|
|
6215
6311
|
Return ONLY a valid JSON object matching this schema:
|
|
6216
6312
|
{
|
|
@@ -6280,6 +6376,64 @@ var PromptService = class {
|
|
|
6280
6376
|
this.globalOverrides = globalOverrides;
|
|
6281
6377
|
this.grounding = grounding;
|
|
6282
6378
|
}
|
|
6379
|
+
/**
|
|
6380
|
+
* Specs/librarian-guidance: resolve the effective guidance for one pass
|
|
6381
|
+
* or call — default `config.prompts.guidance`, per-entity
|
|
6382
|
+
* `config.librarian.guidanceForEntity` winning when it returns a
|
|
6383
|
+
* non-empty (trimmed) string. Synchronous: a resolver that throws,
|
|
6384
|
+
* returns a thenable (its rejection is swallowed with a no-op handler;
|
|
6385
|
+
* a throwing `then` counts too), or returns any non-string value is
|
|
6386
|
+
* treated as "no value" and reported in `diagnostic`. Over-cap text
|
|
6387
|
+
* (UTF-16 units, verbatim) is not sent and reported in `diagnostic`.
|
|
6388
|
+
* Emits nothing itself; the caller emits, immediately at resolution.
|
|
6389
|
+
*/
|
|
6390
|
+
static resolveGuidance(config, entityId) {
|
|
6391
|
+
let source = null;
|
|
6392
|
+
let effective;
|
|
6393
|
+
let resolverDiagnostic;
|
|
6394
|
+
const defaultValue = config?.prompts?.guidance;
|
|
6395
|
+
const resolver = config?.librarian?.guidanceForEntity;
|
|
6396
|
+
let entityValue;
|
|
6397
|
+
if (resolver) {
|
|
6398
|
+
try {
|
|
6399
|
+
entityValue = resolver(entityId);
|
|
6400
|
+
if (entityValue === void 0) {
|
|
6401
|
+
} else if (typeof entityValue === "string") {
|
|
6402
|
+
if (entityValue.trim() !== "") {
|
|
6403
|
+
source = "per_entity";
|
|
6404
|
+
effective = entityValue;
|
|
6405
|
+
}
|
|
6406
|
+
} else {
|
|
6407
|
+
try {
|
|
6408
|
+
entityValue?.then?.(() => void 0, () => void 0);
|
|
6409
|
+
} catch {
|
|
6410
|
+
}
|
|
6411
|
+
resolverDiagnostic = {
|
|
6412
|
+
code: "guidance_resolver_failed",
|
|
6413
|
+
detail: { reason: "non_string" }
|
|
6414
|
+
};
|
|
6415
|
+
}
|
|
6416
|
+
} catch {
|
|
6417
|
+
resolverDiagnostic = { code: "guidance_resolver_failed", detail: { reason: "threw" } };
|
|
6418
|
+
}
|
|
6419
|
+
}
|
|
6420
|
+
if (source === null && defaultValue !== void 0 && defaultValue.trim() !== "") {
|
|
6421
|
+
source = "default";
|
|
6422
|
+
effective = defaultValue;
|
|
6423
|
+
}
|
|
6424
|
+
if (source === null || effective === void 0) {
|
|
6425
|
+
return resolverDiagnostic ? { diagnostic: resolverDiagnostic } : {};
|
|
6426
|
+
}
|
|
6427
|
+
if (effective.length > GUIDANCE_MAX_CHARS) {
|
|
6428
|
+
return {
|
|
6429
|
+
diagnostic: {
|
|
6430
|
+
code: "guidance_too_long",
|
|
6431
|
+
detail: { guidanceLength: effective.length, guidanceSource: source }
|
|
6432
|
+
}
|
|
6433
|
+
};
|
|
6434
|
+
}
|
|
6435
|
+
return resolverDiagnostic ? { guidance: effective, diagnostic: resolverDiagnostic } : { guidance: effective };
|
|
6436
|
+
}
|
|
6283
6437
|
/** The resolved grounding config when `writer` is in `grounding.writers`; otherwise null (spec §6.2). */
|
|
6284
6438
|
groundingFor(writer) {
|
|
6285
6439
|
return this.grounding?.writers.has(writer) ? this.grounding : null;
|
|
@@ -6290,6 +6444,19 @@ var PromptService = class {
|
|
|
6290
6444
|
return cfg ? `${systemPrompt}
|
|
6291
6445
|
|
|
6292
6446
|
${groundingEvidenceBlock(writer, cfg)}` : systemPrompt;
|
|
6447
|
+
}
|
|
6448
|
+
/**
|
|
6449
|
+
* Specs/librarian-guidance: append the marked guidance section (with the
|
|
6450
|
+
* general leave-out rule) to the ALREADY-HYDRATED system prompt — after
|
|
6451
|
+
* ontology, immediately before grounding. The guidance text is never
|
|
6452
|
+
* run through hydration, so `{{…}}` inside it cannot change a builder's
|
|
6453
|
+
* template branch or be expanded with data. No-op on empty input.
|
|
6454
|
+
*/
|
|
6455
|
+
appendGuidance(systemPrompt, guidance) {
|
|
6456
|
+
if (!guidance) return systemPrompt;
|
|
6457
|
+
return `${systemPrompt}
|
|
6458
|
+
|
|
6459
|
+
${guidanceSection(guidance)}`;
|
|
6293
6460
|
}
|
|
6294
6461
|
hydrate(template, variables) {
|
|
6295
6462
|
return template.replace(/\{\{\s*(\w+)\s*\}\}/g, (_match, key) => {
|
|
@@ -6326,31 +6493,31 @@ ${groundingEvidenceBlock(writer, cfg)}` : systemPrompt;
|
|
|
6326
6493
|
|
|
6327
6494
|
${ctx.ontologyModeInstructions}`;
|
|
6328
6495
|
}
|
|
6329
|
-
buildIngestPrompt(documentChunk, runtimeOverride, ontologyContext) {
|
|
6496
|
+
buildIngestPrompt(documentChunk, runtimeOverride, ontologyContext, guidance) {
|
|
6330
6497
|
const template = runtimeOverride ?? this.globalOverrides?.ingestSystemPrompt ?? INGEST_SYSTEM_PROMPT;
|
|
6331
6498
|
const hasDocumentChunk = /\{\{\s*documentChunk\s*\}\}/.test(template);
|
|
6332
6499
|
if (hasDocumentChunk || this.hasOntologyPlaceholders(template)) {
|
|
6333
6500
|
return {
|
|
6334
|
-
systemPrompt: this.appendGrounding(this.buildSystemPrompt(template, { documentChunk }, ontologyContext), "ingest"),
|
|
6501
|
+
systemPrompt: this.appendGrounding(this.appendGuidance(this.buildSystemPrompt(template, { documentChunk }, ontologyContext), guidance), "ingest"),
|
|
6335
6502
|
userPrompt: hasDocumentChunk ? "Please extract the facts." : `Document Chunk:
|
|
6336
6503
|
${documentChunk}`
|
|
6337
6504
|
};
|
|
6338
6505
|
}
|
|
6339
6506
|
return {
|
|
6340
|
-
systemPrompt: this.appendGrounding(this.appendOntology(template, ontologyContext), "ingest"),
|
|
6507
|
+
systemPrompt: this.appendGrounding(this.appendGuidance(this.appendOntology(template, ontologyContext), guidance), "ingest"),
|
|
6341
6508
|
userPrompt: `Document Chunk:
|
|
6342
6509
|
${documentChunk}`
|
|
6343
6510
|
};
|
|
6344
6511
|
}
|
|
6345
|
-
buildLibrarianPrompt(events, currentFacts, runtimeOverride, ontologyContext) {
|
|
6346
|
-
const template = runtimeOverride ??
|
|
6512
|
+
buildLibrarianPrompt(events, currentFacts, runtimeOverride, ontologyContext, guidance) {
|
|
6513
|
+
const template = runtimeOverride ?? LIBRARIAN_SYSTEM_PROMPT;
|
|
6347
6514
|
const hasEvents = /\{\{\s*events\s*\}\}/.test(template);
|
|
6348
6515
|
const hasCurrentFacts = /\{\{\s*currentFacts\s*\}\}/.test(template);
|
|
6349
6516
|
const eventsShown = hasEvents || !hasCurrentFacts;
|
|
6350
6517
|
const corpusField = this.groundingFor("librarian") ? { groundingCorpus: buildGroundingCorpus(eventsShown ? events.map(summaryOf) : []) } : {};
|
|
6351
6518
|
if (hasEvents || hasCurrentFacts || this.hasOntologyPlaceholders(template)) {
|
|
6352
6519
|
return {
|
|
6353
|
-
systemPrompt: this.appendGrounding(this.buildSystemPrompt(template, { events, currentFacts }, ontologyContext), "librarian"),
|
|
6520
|
+
systemPrompt: this.appendGrounding(this.appendGuidance(this.buildSystemPrompt(template, { events, currentFacts }, ontologyContext), guidance), "librarian"),
|
|
6354
6521
|
userPrompt: hasEvents || hasCurrentFacts ? "Please synthesize the context." : `Events:
|
|
6355
6522
|
${JSON.stringify(events, null, 2)}
|
|
6356
6523
|
|
|
@@ -6360,7 +6527,7 @@ ${JSON.stringify(currentFacts, null, 2)}`,
|
|
|
6360
6527
|
};
|
|
6361
6528
|
}
|
|
6362
6529
|
return {
|
|
6363
|
-
systemPrompt: this.appendGrounding(this.appendOntology(template, ontologyContext), "librarian"),
|
|
6530
|
+
systemPrompt: this.appendGrounding(this.appendGuidance(this.appendOntology(template, ontologyContext), guidance), "librarian"),
|
|
6364
6531
|
userPrompt: `Events:
|
|
6365
6532
|
${JSON.stringify(events, null, 2)}
|
|
6366
6533
|
|
|
@@ -6463,13 +6630,17 @@ ${JSON.stringify(facts, null, 2)}`
|
|
|
6463
6630
|
};
|
|
6464
6631
|
}
|
|
6465
6632
|
/** Ops extract (spec §5.2): events only — no existing facts. */
|
|
6466
|
-
buildOpsExtractPrompt(events, ontologyContext) {
|
|
6633
|
+
buildOpsExtractPrompt(events, ontologyContext, guidance) {
|
|
6467
6634
|
const lines = events.map((l) => `${l.label} [${new Date(l.at).toISOString()}] (${l.event.event_type}) ${l.event.summary}`);
|
|
6468
6635
|
const grounding = this.groundingFor("librarian");
|
|
6469
6636
|
return {
|
|
6470
|
-
systemPrompt: this.appendGrounding(this.appendOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), "librarian"),
|
|
6637
|
+
systemPrompt: this.appendGrounding(this.appendGuidance(this.appendOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), guidance), "librarian"),
|
|
6471
6638
|
userPrompt: `Events:
|
|
6472
6639
|
${lines.join("\n")}`,
|
|
6640
|
+
// Corpus entries are one-per-batch-event in batch order (summaries are
|
|
6641
|
+
// TEXT NOT NULL, so the filter inside buildGroundingCorpus drops
|
|
6642
|
+
// nothing): extract.ts stores a candidate's `sourcePartIndex` as the
|
|
6643
|
+
// batch index and buildSourcePointer reads the quote back by it.
|
|
6473
6644
|
...grounding ? { groundingCorpus: buildGroundingCorpus(events.map((l) => l.event.summary)) } : {}
|
|
6474
6645
|
};
|
|
6475
6646
|
}
|
|
@@ -6484,11 +6655,11 @@ ${JSON.stringify({ items })}` };
|
|
|
6484
6655
|
* placeholders and leaves data placeholders verbatim; heal never receives
|
|
6485
6656
|
* ontology context, matching `buildHealPrompt`.
|
|
6486
6657
|
*/
|
|
6487
|
-
buildInstructionTemplates(ontologyContext, librarianStrategy) {
|
|
6658
|
+
buildInstructionTemplates(ontologyContext, librarianStrategy, guidance) {
|
|
6488
6659
|
const o = this.globalOverrides;
|
|
6489
6660
|
return {
|
|
6490
|
-
ingest: this.appendGrounding(this.buildSystemPrompt(o?.ingestSystemPrompt ?? INGEST_SYSTEM_PROMPT, {}, ontologyContext), "ingest"),
|
|
6491
|
-
librarian: librarianStrategy === "ops" ? this.appendGrounding(this.appendOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), "librarian") : this.appendGrounding(this.buildSystemPrompt(
|
|
6661
|
+
ingest: this.appendGrounding(this.appendGuidance(this.buildSystemPrompt(o?.ingestSystemPrompt ?? INGEST_SYSTEM_PROMPT, {}, ontologyContext), guidance), "ingest"),
|
|
6662
|
+
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"),
|
|
6492
6663
|
heal: this.appendGrounding(o?.healSystemPrompt ?? HEAL_SYSTEM_PROMPT, "heal"),
|
|
6493
6664
|
ontologyBackfill: this.buildSystemPrompt(o?.ontologyBackfillSystemPrompt ?? ONTOLOGY_BACKFILL_SYSTEM_PROMPT, {}, ontologyContext)
|
|
6494
6665
|
};
|
|
@@ -6683,13 +6854,24 @@ var IngestionService = class {
|
|
|
6683
6854
|
const { chunks: chunks2, truncated } = chunkText(params.documentChunk, maxChunkLength, chunkOverlap);
|
|
6684
6855
|
if (chunks2.length === 0) return zeroChunkResult();
|
|
6685
6856
|
const ontologyContext = await this.ontologyService?.buildPromptContext(entityId) ?? null;
|
|
6857
|
+
const { guidance, diagnostic } = PromptService.resolveGuidance(this.options.config, entityId);
|
|
6858
|
+
if (diagnostic) {
|
|
6859
|
+
emitDiagnostic(this.options, {
|
|
6860
|
+
code: diagnostic.code,
|
|
6861
|
+
operation: "ingest",
|
|
6862
|
+
trigger: "call",
|
|
6863
|
+
entityId,
|
|
6864
|
+
detail: diagnostic.detail
|
|
6865
|
+
});
|
|
6866
|
+
}
|
|
6686
6867
|
const ingestGrounding = this.promptService.groundingFor("ingest");
|
|
6687
6868
|
const chunkResults = await withConcurrency(
|
|
6688
6869
|
chunks2.map((chunk, chunkIndex) => async () => {
|
|
6689
6870
|
const { systemPrompt, userPrompt } = this.promptService.buildIngestPrompt(
|
|
6690
6871
|
chunk,
|
|
6691
6872
|
params.promptOverride,
|
|
6692
|
-
ontologyContext
|
|
6873
|
+
ontologyContext,
|
|
6874
|
+
guidance
|
|
6693
6875
|
);
|
|
6694
6876
|
try {
|
|
6695
6877
|
const responseText = await callLlm(this.options, { operation: "ingest", entityId, trigger: "call" }, { systemPrompt, userPrompt });
|
|
@@ -7328,9 +7510,9 @@ function changedDefaultWarnings(config) {
|
|
|
7328
7510
|
"[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()."
|
|
7329
7511
|
);
|
|
7330
7512
|
}
|
|
7331
|
-
if (config?.prompts?.librarianSystemPrompt !== void 0
|
|
7513
|
+
if (config?.prompts?.librarianSystemPrompt !== void 0) {
|
|
7332
7514
|
warnings.push(
|
|
7333
|
-
"[core-llm-wiki] `prompts.librarianSystemPrompt`
|
|
7515
|
+
"[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."
|
|
7334
7516
|
);
|
|
7335
7517
|
}
|
|
7336
7518
|
if (config?.librarian?.strategy === "legacy" && config?.maintenance === void 0 && !hasThreshold) {
|
|
@@ -8065,7 +8247,8 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
|
|
|
8065
8247
|
promptEvents,
|
|
8066
8248
|
currentFacts,
|
|
8067
8249
|
promptOverride,
|
|
8068
|
-
ontologyContext
|
|
8250
|
+
ontologyContext,
|
|
8251
|
+
ctx.guidance
|
|
8069
8252
|
);
|
|
8070
8253
|
let responseText;
|
|
8071
8254
|
try {
|
|
@@ -8163,9 +8346,20 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
|
|
|
8163
8346
|
access_count: 0,
|
|
8164
8347
|
deleted_at: null,
|
|
8165
8348
|
okf_type: normalized.okf_type,
|
|
8349
|
+
// Legacy writes no pointer (spec §Legacy path): the column stays null
|
|
8350
|
+
// on every legacy fact, and the legacy prompt keeps its exact text.
|
|
8351
|
+
source_pointer: null,
|
|
8166
8352
|
...grounding?.trust
|
|
8167
8353
|
};
|
|
8168
8354
|
await deps.entryRepo.upsert(factObj, tx);
|
|
8355
|
+
const volunteeredSourceEvent = facts[validFactItemIndexes[k]]?.source_event;
|
|
8356
|
+
if (volunteeredSourceEvent !== void 0 && volunteeredSourceEvent !== null) {
|
|
8357
|
+
diagBuffer.push({
|
|
8358
|
+
...diagBase,
|
|
8359
|
+
code: "source_pointer_unresolved",
|
|
8360
|
+
detail: { factId: id, itemIndex: validFactItemIndexes[k], reason: "unsupported_strategy" }
|
|
8361
|
+
});
|
|
8362
|
+
}
|
|
8169
8363
|
insertedFacts.push({ id, entity_id: entityId, title: fact.title, body: fact.body, tags: JSON.stringify(fact.tags) });
|
|
8170
8364
|
factsForDedupe.push(factObj);
|
|
8171
8365
|
titleIndex.set(normalizeTitleKey(fact.title), { id, okf_type: normalized.okf_type });
|
|
@@ -8237,7 +8431,7 @@ var OPS_MAX_EVENTS_PER_PASS = 50;
|
|
|
8237
8431
|
var OPS_MAX_EXTRACT_CHARS = 24e3;
|
|
8238
8432
|
var RESOLVE_RESERVE_FACTOR = 2;
|
|
8239
8433
|
var estimatePrompt = (p) => estimateTokens(p.systemPrompt) + estimateTokens(p.userPrompt);
|
|
8240
|
-
async function selectBatch(deps, entityId, wm, meter) {
|
|
8434
|
+
async function selectBatch(deps, entityId, wm, meter, guidance) {
|
|
8241
8435
|
const events = await deps.eventRepo.getAfter(entityId, wm, OPS_MAX_EVENTS_PER_PASS);
|
|
8242
8436
|
if (events.length === 0) return { batch: [] };
|
|
8243
8437
|
let n = 0;
|
|
@@ -8251,7 +8445,7 @@ async function selectBatch(deps, entityId, wm, meter) {
|
|
|
8251
8445
|
if (meter && meter.budget !== void 0) {
|
|
8252
8446
|
const ontologyContext = await deps.ontologyService?.buildPromptContext(entityId) ?? null;
|
|
8253
8447
|
for (; ; ) {
|
|
8254
|
-
const need = RESOLVE_RESERVE_FACTOR * estimatePrompt(deps.promptService.buildOpsExtractPrompt(batch, ontologyContext));
|
|
8448
|
+
const need = RESOLVE_RESERVE_FACTOR * estimatePrompt(deps.promptService.buildOpsExtractPrompt(batch, ontologyContext, guidance));
|
|
8255
8449
|
if (meter.fits(need)) break;
|
|
8256
8450
|
if (batch.length === 1) return { budgetStop: { requiredEstimate: need } };
|
|
8257
8451
|
batch = labelEvents(events.slice(0, Math.max(1, Math.floor(batch.length / 2))));
|
|
@@ -8262,7 +8456,7 @@ async function selectBatch(deps, entityId, wm, meter) {
|
|
|
8262
8456
|
async function runExtract(deps, ctx, batch) {
|
|
8263
8457
|
const { entityId, trigger } = ctx;
|
|
8264
8458
|
const ontologyContext = await deps.ontologyService?.buildPromptContext(entityId) ?? null;
|
|
8265
|
-
const prompt = deps.promptService.buildOpsExtractPrompt(batch, ontologyContext);
|
|
8459
|
+
const prompt = deps.promptService.buildOpsExtractPrompt(batch, ontologyContext, ctx.guidance);
|
|
8266
8460
|
const text = await callLlm(deps.options, { operation: "librarian", entityId, trigger, meter: ctx.meter }, prompt);
|
|
8267
8461
|
const parsed = parseJsonResponse(text);
|
|
8268
8462
|
const base = { entityId, operation: "librarian", trigger };
|
|
@@ -8279,9 +8473,23 @@ async function runExtract(deps, ctx, batch) {
|
|
|
8279
8473
|
return;
|
|
8280
8474
|
}
|
|
8281
8475
|
const r = raw;
|
|
8282
|
-
|
|
8476
|
+
let sourceEventId = null;
|
|
8477
|
+
let sourcePartIndex = null;
|
|
8478
|
+
let pointerUnresolved;
|
|
8479
|
+
const rawSourceEvent = r.source_event;
|
|
8480
|
+
if (rawSourceEvent === void 0 || rawSourceEvent === null) {
|
|
8481
|
+
pointerUnresolved = "missing";
|
|
8482
|
+
} else if (typeof rawSourceEvent === "string" && byLabel.has(rawSourceEvent)) {
|
|
8483
|
+
const labeled = byLabel.get(rawSourceEvent);
|
|
8484
|
+
sourceEventId = labeled.event.id;
|
|
8485
|
+
sourcePartIndex = batch.findIndex((b) => b.label === rawSourceEvent);
|
|
8486
|
+
pointerUnresolved = null;
|
|
8487
|
+
} else {
|
|
8488
|
+
pointerUnresolved = "unknown_label";
|
|
8489
|
+
}
|
|
8490
|
+
const sourceLabel = typeof rawSourceEvent === "string" && byLabel.has(rawSourceEvent) ? rawSourceEvent : null;
|
|
8283
8491
|
const validFrom = parseValidFrom(r.valid_from) ?? (sourceLabel ? byLabel.get(sourceLabel).at : defaultValidFrom);
|
|
8284
|
-
candidates.push({ index, fact, sourceLabel, validFrom });
|
|
8492
|
+
candidates.push({ index, fact, sourceLabel, sourceEventId, sourcePartIndex, pointerUnresolved, validFrom });
|
|
8285
8493
|
});
|
|
8286
8494
|
const tasks = [];
|
|
8287
8495
|
(Array.isArray(parsed.tasks) ? parsed.tasks : []).forEach((raw, index) => {
|
|
@@ -8558,6 +8766,17 @@ var TemporalService = class {
|
|
|
8558
8766
|
};
|
|
8559
8767
|
|
|
8560
8768
|
// src/services/librarian/ops/apply.ts
|
|
8769
|
+
function buildSourcePointer(candidate, verdict, groundingOn, groundingCorpus) {
|
|
8770
|
+
if (candidate.sourceEventId === null) return null;
|
|
8771
|
+
let quote = null;
|
|
8772
|
+
if (groundingOn && verdict?.status === "grounded" && candidate.sourcePartIndex !== null) {
|
|
8773
|
+
const part = groundingCorpus?.[candidate.sourcePartIndex];
|
|
8774
|
+
if (part !== void 0) {
|
|
8775
|
+
quote = verdict.retained.find((q) => part.includes(q)) ?? null;
|
|
8776
|
+
}
|
|
8777
|
+
}
|
|
8778
|
+
return { event_id: candidate.sourceEventId, ref: null, quote, position: null };
|
|
8779
|
+
}
|
|
8561
8780
|
async function applyOps(deps, ctx, input) {
|
|
8562
8781
|
const { entityId, trigger } = ctx;
|
|
8563
8782
|
const diagBase = { entityId, operation: "librarian", trigger };
|
|
@@ -8586,7 +8805,8 @@ async function applyOps(deps, ctx, input) {
|
|
|
8586
8805
|
const drops = [];
|
|
8587
8806
|
const normalized = deps.ontologyService?.validateAndNormalizeFact(fact, manifest, { strict: false, drops }) ?? { okf_type: null, edges: [] };
|
|
8588
8807
|
for (const d of drops) input.diagnostics.push(edgeDropDiagnostic(d, { ...diagBase, factId: id }));
|
|
8589
|
-
const
|
|
8808
|
+
const gVerdict = grounding ? checkGrounding(fact.evidence, input.groundingCorpus ?? [], grounding) : null;
|
|
8809
|
+
const g2 = gVerdict ? groundingOutcome(gVerdict, now) : null;
|
|
8590
8810
|
if (g2?.diagnostic) {
|
|
8591
8811
|
input.diagnostics.push({
|
|
8592
8812
|
...diagBase,
|
|
@@ -8594,6 +8814,7 @@ async function applyOps(deps, ctx, input) {
|
|
|
8594
8814
|
detail: { factId: id, itemIndex: g.candidate.index, reason: g2.diagnostic.reason }
|
|
8595
8815
|
});
|
|
8596
8816
|
}
|
|
8817
|
+
const pointer = buildSourcePointer(g.candidate, gVerdict, grounding !== void 0 && grounding !== null, input.groundingCorpus);
|
|
8597
8818
|
const row = {
|
|
8598
8819
|
id,
|
|
8599
8820
|
entity_id: entityId,
|
|
@@ -8610,11 +8831,19 @@ async function applyOps(deps, ctx, input) {
|
|
|
8610
8831
|
access_count: 0,
|
|
8611
8832
|
deleted_at: null,
|
|
8612
8833
|
okf_type: normalized.okf_type,
|
|
8834
|
+
source_pointer: pointer,
|
|
8613
8835
|
...g2?.trust,
|
|
8614
8836
|
...draft ? { lifecycle_status: "draft" } : {}
|
|
8615
8837
|
};
|
|
8616
8838
|
await deps.entryRepo.upsert(row, tx);
|
|
8617
8839
|
await deps.entryRepo.setTemporal(id, entityId, { valid_from: validFrom }, tx);
|
|
8840
|
+
if (g.candidate.pointerUnresolved !== null) {
|
|
8841
|
+
input.diagnostics.push({
|
|
8842
|
+
...diagBase,
|
|
8843
|
+
code: "source_pointer_unresolved",
|
|
8844
|
+
detail: { factId: id, itemIndex: g.candidate.index, reason: g.candidate.pointerUnresolved }
|
|
8845
|
+
});
|
|
8846
|
+
}
|
|
8618
8847
|
titleIndex.set(normalizeTitleKey(title), { id, okf_type: normalized.okf_type });
|
|
8619
8848
|
if (normalized.edges.length > 0) pendingEdges.push({ sourceId: id, sourceType: normalized.okf_type, edges: normalized.edges });
|
|
8620
8849
|
const textChanged = title !== fact.title || body !== fact.body;
|
|
@@ -8720,7 +8949,7 @@ var runOpsLibrarianPass = async (deps, ctx) => {
|
|
|
8720
8949
|
const cfg = resolveGateConfig(deps.options.config?.librarian?.gate);
|
|
8721
8950
|
await deps.seedWatermark(entityId);
|
|
8722
8951
|
const wm = await deps.getWatermark(entityId);
|
|
8723
|
-
const sel = await selectBatch(deps, entityId, wm, ctx.meter);
|
|
8952
|
+
const sel = await selectBatch(deps, entityId, wm, ctx.meter, ctx.guidance);
|
|
8724
8953
|
if ("budgetStop" in sel) return { processedThrough: null, factsWritten: 0, budgetStop: sel.budgetStop };
|
|
8725
8954
|
if (sel.batch.length === 0) return { processedThrough: null, factsWritten: 0 };
|
|
8726
8955
|
if (!deps.searchService.isKeywordAvailable() && await gateNeedsKeyword(deps, entityId)) {
|
|
@@ -9358,7 +9587,17 @@ var MaintenanceService = class {
|
|
|
9358
9587
|
* A budget-stopped pass wrote nothing and must not move the watermark.
|
|
9359
9588
|
*/
|
|
9360
9589
|
async runLibrarianPass(ctx) {
|
|
9361
|
-
const
|
|
9590
|
+
const { guidance, diagnostic } = PromptService.resolveGuidance(this.options.config, ctx.entityId);
|
|
9591
|
+
if (diagnostic) {
|
|
9592
|
+
emitDiagnostic(this.options, {
|
|
9593
|
+
code: diagnostic.code,
|
|
9594
|
+
operation: "librarian",
|
|
9595
|
+
trigger: ctx.trigger,
|
|
9596
|
+
entityId: ctx.entityId,
|
|
9597
|
+
detail: diagnostic.detail
|
|
9598
|
+
});
|
|
9599
|
+
}
|
|
9600
|
+
const result = await runLibrarianStrategy(this.librarianDeps(), { ...ctx, guidance });
|
|
9362
9601
|
if (result.processedThrough && !result.budgetStop) {
|
|
9363
9602
|
await this.advanceLibrarianWatermark(ctx.entityId, result.processedThrough);
|
|
9364
9603
|
}
|
|
@@ -9628,6 +9867,7 @@ var MaintenanceService = class {
|
|
|
9628
9867
|
source_type: "librarian_inferred",
|
|
9629
9868
|
source_hash: null,
|
|
9630
9869
|
source_ref: null,
|
|
9870
|
+
source_pointer: null,
|
|
9631
9871
|
created_at: now,
|
|
9632
9872
|
updated_at: now,
|
|
9633
9873
|
last_accessed_at: null,
|
|
@@ -10547,6 +10787,19 @@ var ImportExportService = class {
|
|
|
10547
10787
|
);
|
|
10548
10788
|
}
|
|
10549
10789
|
}
|
|
10790
|
+
const hasSourcePointerKey = fact["source_pointer"] !== void 0;
|
|
10791
|
+
const rawPointerValue = hasSourcePointerKey ? fact["source_pointer"] : void 0;
|
|
10792
|
+
const pointerValidated = hasSourcePointerKey ? validateSourcePointerValue(rawPointerValue) : null;
|
|
10793
|
+
if (pointerValidated === void 0) {
|
|
10794
|
+
emitDiagnostic(this.options, {
|
|
10795
|
+
code: "source_pointer_invalid",
|
|
10796
|
+
operation: "importDump",
|
|
10797
|
+
trigger: "call",
|
|
10798
|
+
entityId,
|
|
10799
|
+
detail: { factId: fact.id }
|
|
10800
|
+
});
|
|
10801
|
+
}
|
|
10802
|
+
const sourcePointer = pointerValidated === void 0 ? null : pointerValidated;
|
|
10550
10803
|
const factObj = {
|
|
10551
10804
|
id: fact.id,
|
|
10552
10805
|
entity_id: entityId,
|
|
@@ -10564,6 +10817,7 @@ var ImportExportService = class {
|
|
|
10564
10817
|
deleted_at: fact.deleted_at,
|
|
10565
10818
|
embedding_blob: blobData ?? void 0,
|
|
10566
10819
|
okf_type: fact.okf_type ?? null,
|
|
10820
|
+
source_pointer: sourcePointer,
|
|
10567
10821
|
// OKF v0.2 — forwarded as-is; parseOkfBundle / the caller is responsible for
|
|
10568
10822
|
// populating these per spec, importDump does not derive or validate them.
|
|
10569
10823
|
lifecycle_status: fact.lifecycle_status ?? "stable",
|
|
@@ -10581,7 +10835,7 @@ var ImportExportService = class {
|
|
|
10581
10835
|
return { last_verified_at: latest?.at ?? null, last_verified_by: latest?.by ?? null };
|
|
10582
10836
|
})()
|
|
10583
10837
|
};
|
|
10584
|
-
await this.entryRepo.upsertForImport(factObj, tx);
|
|
10838
|
+
await this.entryRepo.upsertForImport(factObj, tx, hasSourcePointerKey);
|
|
10585
10839
|
await this.entryRepo.setTemporal(fact.id, entityId, {
|
|
10586
10840
|
valid_from: fact.valid_from ?? null,
|
|
10587
10841
|
valid_to: fact.valid_to ?? null,
|
|
@@ -13287,7 +13541,17 @@ var WikiMemory = class {
|
|
|
13287
13541
|
async getInstructions(entityId) {
|
|
13288
13542
|
assertEntityId2(entityId);
|
|
13289
13543
|
const ontologyContext = await this.ontologyService.buildPromptContext(entityId);
|
|
13290
|
-
|
|
13544
|
+
const { guidance, diagnostic } = PromptService.resolveGuidance(this.options.config, entityId);
|
|
13545
|
+
if (diagnostic) {
|
|
13546
|
+
emitDiagnostic(this.options, {
|
|
13547
|
+
code: diagnostic.code,
|
|
13548
|
+
operation: "read",
|
|
13549
|
+
trigger: "call",
|
|
13550
|
+
entityId,
|
|
13551
|
+
detail: diagnostic.detail
|
|
13552
|
+
});
|
|
13553
|
+
}
|
|
13554
|
+
return this.promptService.buildInstructionTemplates(ontologyContext, resolveLibrarianStrategy(this.options.config), guidance);
|
|
13291
13555
|
}
|
|
13292
13556
|
/**
|
|
13293
13557
|
* Returns the live source_refs for an entity, one row per ref, with the most
|
|
@@ -13401,7 +13665,7 @@ var WikiMemory = class {
|
|
|
13401
13665
|
/**
|
|
13402
13666
|
* @param options.promptOverride - Applies only to this manual call. Does NOT affect
|
|
13403
13667
|
* WriteService-triggered auto-runs. For persistent prompt customization across auto-runs,
|
|
13404
|
-
* set `options.config.prompts.
|
|
13668
|
+
* set `options.config.prompts.guidance` at WikiMemory construction time.
|
|
13405
13669
|
*/
|
|
13406
13670
|
async runLibrarian(entityId, options) {
|
|
13407
13671
|
return this.maintenanceService.runLibrarian(entityId, options);
|
|
@@ -14212,6 +14476,15 @@ function isoDateOrOmit(ms) {
|
|
|
14212
14476
|
if (!Number.isFinite(d.getTime())) return void 0;
|
|
14213
14477
|
return d.toISOString().slice(0, 10);
|
|
14214
14478
|
}
|
|
14479
|
+
function sourcePointerFrontmatter(p) {
|
|
14480
|
+
if (!p) return void 0;
|
|
14481
|
+
return {
|
|
14482
|
+
...p.event_id != null ? { event_id: p.event_id } : {},
|
|
14483
|
+
...p.ref != null ? { ref: p.ref } : {},
|
|
14484
|
+
...p.quote != null ? { quote: p.quote } : {},
|
|
14485
|
+
...p.position != null ? { position: p.position } : {}
|
|
14486
|
+
};
|
|
14487
|
+
}
|
|
14215
14488
|
function factFrontmatterV2(f) {
|
|
14216
14489
|
return {
|
|
14217
14490
|
type: f.okf_type ?? "fact",
|
|
@@ -14250,7 +14523,9 @@ function factFrontmatterV2(f) {
|
|
|
14250
14523
|
...f.valid_from != null ? { valid_from: f.valid_from } : {},
|
|
14251
14524
|
...f.valid_to != null ? { valid_to: f.valid_to } : {},
|
|
14252
14525
|
...f.superseded_by != null ? { superseded_by: f.superseded_by } : {},
|
|
14253
|
-
...f.superseded_at != null ? { superseded_at: f.superseded_at } : {}
|
|
14526
|
+
...f.superseded_at != null ? { superseded_at: f.superseded_at } : {},
|
|
14527
|
+
// Source pointer (specs/source-pointers): map only when non-null; null slots omitted.
|
|
14528
|
+
...sourcePointerFrontmatter(f.source_pointer) ? { source_pointer: sourcePointerFrontmatter(f.source_pointer) } : {}
|
|
14254
14529
|
};
|
|
14255
14530
|
}
|
|
14256
14531
|
function taskFrontmatterV2(t) {
|
|
@@ -14294,7 +14569,9 @@ function factFrontmatterV1(f) {
|
|
|
14294
14569
|
created_at: f.created_at,
|
|
14295
14570
|
access_count: f.access_count,
|
|
14296
14571
|
last_accessed_at: f.last_accessed_at,
|
|
14297
|
-
deleted_at: f.deleted_at
|
|
14572
|
+
deleted_at: f.deleted_at,
|
|
14573
|
+
// Source pointer (specs/source-pointers): same map rule as the v2 path.
|
|
14574
|
+
...sourcePointerFrontmatter(f.source_pointer) ? { source_pointer: sourcePointerFrontmatter(f.source_pointer) } : {}
|
|
14298
14575
|
};
|
|
14299
14576
|
}
|
|
14300
14577
|
function taskFrontmatterV1(t) {
|
|
@@ -14550,7 +14827,7 @@ function parseLogEntryText(text) {
|
|
|
14550
14827
|
}
|
|
14551
14828
|
return { event_type, summary: unescapeLogSummary((plainSummary ?? "").trim()) };
|
|
14552
14829
|
}
|
|
14553
|
-
function frontmatterToFact(entityId, id, frontmatter, body, now) {
|
|
14830
|
+
function frontmatterToFact(entityId, id, frontmatter, body, now, droppedPointerValues) {
|
|
14554
14831
|
const created_at = parseFrontmatterTimestamp(frontmatter.created_at, now);
|
|
14555
14832
|
const updated_at = parseFrontmatterTimestamp(
|
|
14556
14833
|
frontmatter.generated?.at,
|
|
@@ -14604,7 +14881,23 @@ function frontmatterToFact(entityId, id, frontmatter, body, now) {
|
|
|
14604
14881
|
...optionalEpoch("valid_from", frontmatter.valid_from),
|
|
14605
14882
|
...optionalEpoch("valid_to", frontmatter.valid_to),
|
|
14606
14883
|
...typeof frontmatter.superseded_by === "string" ? { superseded_by: frontmatter.superseded_by } : {},
|
|
14607
|
-
...optionalEpoch("superseded_at", frontmatter.superseded_at)
|
|
14884
|
+
...optionalEpoch("superseded_at", frontmatter.superseded_at),
|
|
14885
|
+
// Source pointer (specs/source-pointers §Export, import, and OKF): the
|
|
14886
|
+
// parse path has no diagnostic channel, so it reports through the result.
|
|
14887
|
+
// ABSENT key → the property is omitted (not null), so the import
|
|
14888
|
+
// presence guard survives the parse. Malformed → the property is omitted
|
|
14889
|
+
// AND the drop is reported as entry id + reason slug — never the raw
|
|
14890
|
+
// value, which can carry quote text.
|
|
14891
|
+
...(() => {
|
|
14892
|
+
const raw = frontmatter.source_pointer;
|
|
14893
|
+
if (raw === void 0) return {};
|
|
14894
|
+
const v = validateSourcePointerValue(raw);
|
|
14895
|
+
if (v === void 0) {
|
|
14896
|
+
droppedPointerValues.push({ factId: id, reason: "malformed" });
|
|
14897
|
+
return {};
|
|
14898
|
+
}
|
|
14899
|
+
return { source_pointer: v };
|
|
14900
|
+
})()
|
|
14608
14901
|
};
|
|
14609
14902
|
}
|
|
14610
14903
|
function optionalEpoch(key, v) {
|
|
@@ -14725,6 +15018,7 @@ function parseOkfBundle(entityId, files, options) {
|
|
|
14725
15018
|
}
|
|
14726
15019
|
const facts = [];
|
|
14727
15020
|
const tasks = [];
|
|
15021
|
+
const droppedPointerValues = [];
|
|
14728
15022
|
const edges = [];
|
|
14729
15023
|
let logContent = null;
|
|
14730
15024
|
const logMdPath = findLogMdPath(allowedFiles);
|
|
@@ -14742,7 +15036,7 @@ function parseOkfBundle(entityId, files, options) {
|
|
|
14742
15036
|
const edgeLinks = isProfile1 || isLegacyV1 ? relatedLinks : [...relatedLinks, ...coreOkf.extractMarkdownLinks(storedBody)];
|
|
14743
15037
|
const usesV1StatusRule = isProfile1 || isLegacyV1 || profile === void 0 && okfVersion === void 0;
|
|
14744
15038
|
if (route === "fact") {
|
|
14745
|
-
facts.push(frontmatterToFact(entityId, resolvedId, frontmatter, storedBody, now));
|
|
15039
|
+
facts.push(frontmatterToFact(entityId, resolvedId, frontmatter, storedBody, now, droppedPointerValues));
|
|
14746
15040
|
} else {
|
|
14747
15041
|
tasks.push(frontmatterToTask(entityId, resolvedId, frontmatter, now, usesV1StatusRule));
|
|
14748
15042
|
}
|
|
@@ -14809,7 +15103,8 @@ function parseOkfBundle(entityId, files, options) {
|
|
|
14809
15103
|
generatedAt: now,
|
|
14810
15104
|
entities: {
|
|
14811
15105
|
[entityId]: { facts, tasks, events, edges, summary: entitySummary }
|
|
14812
|
-
}
|
|
15106
|
+
},
|
|
15107
|
+
...droppedPointerValues.length > 0 ? { dropped_pointer_values: droppedPointerValues } : {}
|
|
14813
15108
|
};
|
|
14814
15109
|
}
|
|
14815
15110
|
|
|
@@ -14890,6 +15185,7 @@ exports.WikiSourceRefHashCollision = WikiSourceRefHashCollision;
|
|
|
14890
15185
|
exports.WikiStrictOntologyViolation = WikiStrictOntologyViolation;
|
|
14891
15186
|
exports.WikiSupersedeError = WikiSupersedeError;
|
|
14892
15187
|
exports.WikiTransactionError = WikiTransactionError;
|
|
15188
|
+
exports.buildOntologyPromptAppendix = buildOntologyPromptAppendix;
|
|
14893
15189
|
exports.chunkText = chunkText;
|
|
14894
15190
|
exports.configureRandomSource = configureRandomSource;
|
|
14895
15191
|
exports.createWiki = createWiki;
|