@equationalapplications/core-llm-wiki 9.20.2 → 9.21.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 +2 -2
- package/dist/{chunk-PLZNFRMM.mjs → chunk-EEVYPJCL.mjs} +1193 -83
- package/dist/chunk-EEVYPJCL.mjs.map +1 -0
- package/dist/index.d.mts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +2165 -1200
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +357 -502
- package/dist/index.mjs.map +1 -1
- package/dist/{testing-DS_d9qmP.d.mts → testing-DOFX_5lj.d.mts} +211 -31
- package/dist/{testing-DS_d9qmP.d.ts → testing-DOFX_5lj.d.ts} +211 -31
- package/dist/testing.d.mts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +552 -85
- package/dist/testing.js.map +1 -1
- package/dist/testing.mjs +1 -1
- package/package.json +7 -7
- package/dist/chunk-PLZNFRMM.mjs.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { latestVerified } from '@equationalapplications/core-okf';
|
|
1
|
+
import { isAllowedOkfPath, parseRootIndexMd, parseEntityIndexMd, parseConcept, splitRelatedSection, extractMarkdownLinks, parseLogMd, parseEventIdComment, createEventIdDeriver, parseFrontmatter, latestVerified, parseOkfTimestamp, parseVerifiedFlexible, parseSourcesFlexible, parseCitationsList } from '@equationalapplications/core-okf';
|
|
2
2
|
|
|
3
3
|
var __typeError = (msg) => {
|
|
4
4
|
throw TypeError(msg);
|
|
@@ -84,6 +84,7 @@ function resolveDefaultChunkLength(budget) {
|
|
|
84
84
|
// src/utils/engineDefaults.ts
|
|
85
85
|
var DEFAULT_LIBRARIAN_STRATEGY = "ops";
|
|
86
86
|
var DEFAULT_MAINTENANCE_MODE = "deferred";
|
|
87
|
+
var ENGINE_ACTOR = "process:llm-wiki";
|
|
87
88
|
function resolveLibrarianStrategy(config) {
|
|
88
89
|
return config?.librarian?.strategy ?? DEFAULT_LIBRARIAN_STRATEGY;
|
|
89
90
|
}
|
|
@@ -319,6 +320,8 @@ var SEVERITY = {
|
|
|
319
320
|
source_pointer_invalid: "warn",
|
|
320
321
|
source_event_gone: "warn",
|
|
321
322
|
derived_events_invalid: "warn",
|
|
323
|
+
okf_extra_invalid: "warn",
|
|
324
|
+
okf_bundle_metadata_invalid: "warn",
|
|
322
325
|
source_store_source_too_large: "warn",
|
|
323
326
|
source_store_budget_exceeded: "warn",
|
|
324
327
|
source_store_hash_mismatch: "warn",
|
|
@@ -381,6 +384,8 @@ var MESSAGE = {
|
|
|
381
384
|
source_pointer_invalid: "Import met a malformed source pointer value and stored a null pointer.",
|
|
382
385
|
source_event_gone: "A librarian candidate was dropped at apply time because the event it came from was no longer available: deleted (detail.reason gone) or forgotten with forget({ eventId }) (detail.reason forgotten) outside this instance while the pass ran.",
|
|
383
386
|
derived_events_invalid: "Import met a malformed derived_events value and stored null.",
|
|
387
|
+
okf_extra_invalid: "Import met a malformed or oversized okf_extra value and stored null, or dropped a raw-block entry no parse could have produced.",
|
|
388
|
+
okf_bundle_metadata_invalid: "Import met a malformed or oversized bundle metadata record and treated it as absent, or dropped a raw-block entry no parse could have produced.",
|
|
384
389
|
source_store_source_too_large: "A source document exceeded the per-document size cap and was not stored.",
|
|
385
390
|
source_store_budget_exceeded: "Storing a source document would exceed the store UTF-16 code-unit budget and it was not stored.",
|
|
386
391
|
source_store_hash_mismatch: "A source document text did not match its recorded hash and was not stored.",
|
|
@@ -2007,6 +2012,9 @@ var BaseRepository = class {
|
|
|
2007
2012
|
function entitySummaryMetaKey(entityId) {
|
|
2008
2013
|
return `entity_summary:${entityId}`;
|
|
2009
2014
|
}
|
|
2015
|
+
function bundleMetadataMetaKey(entityId) {
|
|
2016
|
+
return `okf_bundle_metadata:${entityId}`;
|
|
2017
|
+
}
|
|
2010
2018
|
var START_OF_LOG_WATERMARK = Object.freeze({ at: Number.MIN_SAFE_INTEGER, id: "" });
|
|
2011
2019
|
var CheckpointIncompleteError = class extends Error {
|
|
2012
2020
|
constructor() {
|
|
@@ -3646,7 +3654,7 @@ ${JSON.stringify(currentFacts, null, 2)}`,
|
|
|
3646
3654
|
const anchorsShown = !usesPlaceholders || hasDocumentAnchors;
|
|
3647
3655
|
const groundingCorpus = healGrounding ? buildGroundingCorpus([
|
|
3648
3656
|
...eventsShown ? effectiveEvents.map(summaryOf) : [],
|
|
3649
|
-
...anchorsShown ? effectiveAnchors.map((a, i) => ({ status: a?.lifecycle_status, shown: promptAnchors[i] })).filter((x) => x.status
|
|
3657
|
+
...anchorsShown ? effectiveAnchors.map((a, i) => ({ status: a?.lifecycle_status, shown: promptAnchors[i] })).filter((x) => x.status === void 0 || x.status === "stable" || x.status === "deprecated").map((x) => x.shown?.body) : []
|
|
3650
3658
|
]) : null;
|
|
3651
3659
|
const { shapedCandidates, degraded } = applyBodyTruncation(
|
|
3652
3660
|
healCandidates,
|
|
@@ -4182,7 +4190,7 @@ var IngestionService = class {
|
|
|
4182
4190
|
if (!sourceRef) throw new Error("Invalid sourceRef");
|
|
4183
4191
|
params = { ...params, sourceRef };
|
|
4184
4192
|
await this.assertGraphNodeOwnership(entityId, params.nodes, tx);
|
|
4185
|
-
const now = Date.now();
|
|
4193
|
+
const now = opts?.at !== void 0 && Number.isFinite(opts.at) ? opts.at : Date.now();
|
|
4186
4194
|
const ontologyState = await this.ontologyService?.getEffectiveState(entityId, tx) ?? { mode: "off", manifest: { node_types: [], edge_types: [] } };
|
|
4187
4195
|
let { mode, manifest } = ontologyState;
|
|
4188
4196
|
const strictEffective = opts?.strict === false ? false : opts?.strict === true || mode === "strict";
|
|
@@ -4229,6 +4237,9 @@ var IngestionService = class {
|
|
|
4229
4237
|
access_count: 0,
|
|
4230
4238
|
deleted_at: null,
|
|
4231
4239
|
okf_type: normalized.okf_type,
|
|
4240
|
+
// §C1: only the engine-authored path stamps; the host path passes no
|
|
4241
|
+
// flag and binds NULL (the COALESCE still protects any stored actor).
|
|
4242
|
+
...opts?.authoredByEngine ? { generated_by: ENGINE_ACTOR } : {},
|
|
4232
4243
|
...opts?.nodeTrust?.get(node.id)
|
|
4233
4244
|
};
|
|
4234
4245
|
wikiFacts.push(wikiFact);
|
|
@@ -4297,7 +4308,7 @@ var IngestionService = class {
|
|
|
4297
4308
|
await this.sourceRefIndexRepo.softDeleteByEntityAndSourceRef(entityId, params.sourceRef, tx);
|
|
4298
4309
|
await this.sourceRefIndexRepo.upsert(entityId, params.sourceHash, params.sourceRef, tx);
|
|
4299
4310
|
for (const wikiFact of wikiFacts) {
|
|
4300
|
-
await this.entryRepo.upsert(wikiFact, tx);
|
|
4311
|
+
await this.entryRepo.upsert(wikiFact, tx, now);
|
|
4301
4312
|
}
|
|
4302
4313
|
let edgesInsertedCount = 0;
|
|
4303
4314
|
for (const edge of validEdges) {
|
|
@@ -4440,7 +4451,10 @@ var IngestionService = class {
|
|
|
4440
4451
|
entityId,
|
|
4441
4452
|
{ sourceRef, sourceHash, nodes: hostNodes, edges: hostEdges },
|
|
4442
4453
|
tx,
|
|
4443
|
-
|
|
4454
|
+
// §C1: the engine authored every node here. §C5: `at` shares this pass's
|
|
4455
|
+
// clock read (used for the grounding events above) with the row writes,
|
|
4456
|
+
// so a grounded fact's verification stays current.
|
|
4457
|
+
{ strict: false, diag: { buffer: diagBuffer, operation: "ingest" }, authoredByEngine: true, at: now, ...nodeTrust.size > 0 ? { nodeTrust } : {} }
|
|
4444
4458
|
);
|
|
4445
4459
|
return { deletedSourceFactIds, insertedFacts };
|
|
4446
4460
|
}
|
|
@@ -4540,9 +4554,11 @@ var IngestionService = class {
|
|
|
4540
4554
|
access_count: 0,
|
|
4541
4555
|
deleted_at: null,
|
|
4542
4556
|
okf_type: normalized.okf_type,
|
|
4557
|
+
// §C1: the engine extracted this fact from the document.
|
|
4558
|
+
generated_by: ENGINE_ACTOR,
|
|
4543
4559
|
...outcome?.trust
|
|
4544
4560
|
};
|
|
4545
|
-
await this.entryRepo.upsert(wikiFact, tx);
|
|
4561
|
+
await this.entryRepo.upsert(wikiFact, tx, now);
|
|
4546
4562
|
titleIndex.set(normalizeTitleKey(fact.title), { id, okf_type: normalized.okf_type });
|
|
4547
4563
|
insertedDescriptors.push({
|
|
4548
4564
|
id,
|
|
@@ -5495,7 +5511,7 @@ var EdgeRepository = class extends BaseRepository {
|
|
|
5495
5511
|
END
|
|
5496
5512
|
) >= ?
|
|
5497
5513
|
AND n.source_type NOT IN (${excludeSourceTypesPlaceholders})
|
|
5498
|
-
AND (? = 0 OR n.lifecycle_status
|
|
5514
|
+
AND (? = 0 OR n.lifecycle_status IN ('stable','deprecated'))
|
|
5499
5515
|
AND ${liveAtSql(opts.live.mode, "n.")}
|
|
5500
5516
|
WHERE w.depth < ?
|
|
5501
5517
|
AND instr(w.visited, ',' || (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END) || ',') = 0
|
|
@@ -5634,7 +5650,9 @@ async function setupDatabase(db, prefix) {
|
|
|
5634
5650
|
superseded_at INTEGER,
|
|
5635
5651
|
prior_valid_to INTEGER,
|
|
5636
5652
|
source_pointer TEXT,
|
|
5637
|
-
derived_events TEXT
|
|
5653
|
+
derived_events TEXT,
|
|
5654
|
+
stale_after_raw TEXT,
|
|
5655
|
+
okf_extra TEXT
|
|
5638
5656
|
);
|
|
5639
5657
|
|
|
5640
5658
|
CREATE INDEX IF NOT EXISTS ${prefix}entries_entity_idx ON ${prefix}entries(entity_id);
|
|
@@ -5701,7 +5719,9 @@ async function setupDatabase(db, prefix) {
|
|
|
5701
5719
|
last_verified_by TEXT,
|
|
5702
5720
|
okf_sources TEXT,
|
|
5703
5721
|
okf_verified TEXT,
|
|
5704
|
-
okf_usage_window TEXT
|
|
5722
|
+
okf_usage_window TEXT,
|
|
5723
|
+
stale_after_raw TEXT,
|
|
5724
|
+
okf_extra TEXT
|
|
5705
5725
|
);
|
|
5706
5726
|
|
|
5707
5727
|
CREATE INDEX IF NOT EXISTS ${prefix}tasks_entity_idx ON ${prefix}tasks(entity_id, status);
|
|
@@ -6436,6 +6456,25 @@ var MIGRATIONS = [
|
|
|
6436
6456
|
await addEventsForgottenAtColumn(db, prefix);
|
|
6437
6457
|
await createEventsForgottenIndex(db, prefix);
|
|
6438
6458
|
}
|
|
6459
|
+
},
|
|
6460
|
+
{
|
|
6461
|
+
version: 20,
|
|
6462
|
+
description: "OKF v0.3: nullable stale_after_raw (unparseable wire stale_after, verbatim) and okf_extra (unmapped frontmatter keys, JSON) on entries and tasks (specs/okf-v03 \xA7F)",
|
|
6463
|
+
run: async (db, prefix) => {
|
|
6464
|
+
for (const table of ["entries", "tasks"]) {
|
|
6465
|
+
const cols = await db.getAllAsync(
|
|
6466
|
+
`PRAGMA table_info(${prefix}${table})`
|
|
6467
|
+
);
|
|
6468
|
+
const existing = new Set(cols.map((c) => c.name));
|
|
6469
|
+
const adds = [
|
|
6470
|
+
["stale_after_raw", `ALTER TABLE ${prefix}${table} ADD COLUMN stale_after_raw TEXT`],
|
|
6471
|
+
["okf_extra", `ALTER TABLE ${prefix}${table} ADD COLUMN okf_extra TEXT`]
|
|
6472
|
+
];
|
|
6473
|
+
for (const [name, sql] of adds) {
|
|
6474
|
+
if (!existing.has(name)) await db.execAsync(sql);
|
|
6475
|
+
}
|
|
6476
|
+
}
|
|
6477
|
+
}
|
|
6439
6478
|
}
|
|
6440
6479
|
];
|
|
6441
6480
|
async function addEventsForgottenAtColumn(db, prefix) {
|
|
@@ -6774,9 +6813,15 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
|
|
|
6774
6813
|
// Legacy writes no pointer (spec §Legacy path): the column stays null
|
|
6775
6814
|
// on every legacy fact, and the legacy prompt keeps its exact text.
|
|
6776
6815
|
source_pointer: null,
|
|
6816
|
+
// §C1 (specs/okf-v03): the engine authored this fact, so a NULL row
|
|
6817
|
+
// actor is stamped; the upsert's COALESCE never overwrites a stored
|
|
6818
|
+
// (explicit or imported foreign) actor. §C5: the pass's clock read
|
|
6819
|
+
// is shared with the grounding event, so the verification is current
|
|
6820
|
+
// by the `>=` currency test.
|
|
6821
|
+
generated_by: ENGINE_ACTOR,
|
|
6777
6822
|
...grounding?.trust
|
|
6778
6823
|
};
|
|
6779
|
-
await deps.entryRepo.upsert(factObj, tx);
|
|
6824
|
+
await deps.entryRepo.upsert(factObj, tx, now);
|
|
6780
6825
|
const volunteeredSourceEvent = facts[validFactItemIndexes[k]]?.source_event;
|
|
6781
6826
|
if (volunteeredSourceEvent !== void 0 && volunteeredSourceEvent !== null) {
|
|
6782
6827
|
diagBuffer.push({
|
|
@@ -6818,7 +6863,8 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
|
|
|
6818
6863
|
created_at: now,
|
|
6819
6864
|
updated_at: now,
|
|
6820
6865
|
resolved_at: null,
|
|
6821
|
-
deleted_at: null
|
|
6866
|
+
deleted_at: null,
|
|
6867
|
+
generated_by: ENGINE_ACTOR
|
|
6822
6868
|
};
|
|
6823
6869
|
await deps.taskRepo.upsert(taskObj, tx);
|
|
6824
6870
|
}
|
|
@@ -7453,13 +7499,19 @@ async function applyOps(deps, ctx, input) {
|
|
|
7453
7499
|
deleted_at: null,
|
|
7454
7500
|
okf_type: normalized.okf_type,
|
|
7455
7501
|
source_pointer: pointer,
|
|
7502
|
+
// §C1 (specs/okf-v03): the engine authored this text (ADD, the
|
|
7503
|
+
// supersede replacement and the contradicts draft all land here), so a
|
|
7504
|
+
// NULL row actor is stamped; the upsert's COALESCE never overwrites a
|
|
7505
|
+
// stored actor. §C5: the pass's clock read is shared with the
|
|
7506
|
+
// grounding event (§C5 currency, `>=`).
|
|
7507
|
+
generated_by: ENGINE_ACTOR,
|
|
7456
7508
|
// §2: only an UPDATE converted to SUPERSEDE inherits (the merged text
|
|
7457
7509
|
// rests on the target); ADD and plain SUPERSEDE carry no list.
|
|
7458
7510
|
...inheritedDerivedEvents(inheritFrom, pointer?.event_id ?? null),
|
|
7459
7511
|
...g2?.trust,
|
|
7460
7512
|
...draft ? { lifecycle_status: "draft" } : {}
|
|
7461
7513
|
};
|
|
7462
|
-
await deps.entryRepo.upsert(row, tx);
|
|
7514
|
+
await deps.entryRepo.upsert(row, tx, now);
|
|
7463
7515
|
await deps.entryRepo.setTemporal(id, entityId, { valid_from: validFrom }, tx);
|
|
7464
7516
|
if (g.candidate.pointerUnresolved !== null) {
|
|
7465
7517
|
input.diagnostics.push({
|
|
@@ -7534,7 +7586,18 @@ async function applyOps(deps, ctx, input) {
|
|
|
7534
7586
|
title: newTitle,
|
|
7535
7587
|
body: op.body ?? g.candidate.fact.body,
|
|
7536
7588
|
updated_at: now,
|
|
7589
|
+
// §C1: the engine authored the merged text, so a NULL stored actor
|
|
7590
|
+
// is filled; the upsert's COALESCE keeps a stored (foreign)
|
|
7591
|
+
// actor. The §C2 gate stamps only on a real content change.
|
|
7592
|
+
generated_by: existing.generated_by ?? ENGINE_ACTOR,
|
|
7537
7593
|
...derived ? { derived_events: derived } : {}
|
|
7594
|
+
// No shared `at`: this in-place rewrite carries no same-pass
|
|
7595
|
+
// verification, so §C5's shared-instant rationale does not apply —
|
|
7596
|
+
// the repo stamps its own instant inside the transaction (the heal
|
|
7597
|
+
// writeNow discipline). The pass-start read could predate a
|
|
7598
|
+
// concurrent verification commit (the rewritten row would then
|
|
7599
|
+
// out-stay its own replacement, §5.3) or move updated_at backwards
|
|
7600
|
+
// (review 2026-12-04).
|
|
7538
7601
|
}, tx);
|
|
7539
7602
|
titleIndex.delete(normalizeTitleKey(existing.title));
|
|
7540
7603
|
titleIndex.set(normalizeTitleKey(newTitle), { id: existing.id, okf_type: existing.okf_type ?? null });
|
|
@@ -7598,7 +7661,8 @@ async function applyOps(deps, ctx, input) {
|
|
|
7598
7661
|
created_at: now,
|
|
7599
7662
|
updated_at: now,
|
|
7600
7663
|
resolved_at: null,
|
|
7601
|
-
deleted_at: null
|
|
7664
|
+
deleted_at: null,
|
|
7665
|
+
generated_by: ENGINE_ACTOR
|
|
7602
7666
|
};
|
|
7603
7667
|
await deps.taskRepo.upsert(taskObj, tx);
|
|
7604
7668
|
}
|
|
@@ -8656,6 +8720,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
|
|
|
8656
8720
|
await this.metadataRepo.updateCheckpoint(entityId, { memory: 0, heal: 0 }, tx);
|
|
8657
8721
|
}
|
|
8658
8722
|
await this.metadataRepo.deleteMeta(entitySummaryMetaKey(entityId), tx);
|
|
8723
|
+
await this.metadataRepo.deleteMeta(bundleMetadataMetaKey(entityId), tx);
|
|
8659
8724
|
} else {
|
|
8660
8725
|
const hasIdSelectors = params.entryId !== void 0 || params.taskId !== void 0;
|
|
8661
8726
|
const hasSourceSelectors = params.sourceRef !== void 0 || params.sourceHash !== void 0;
|
|
@@ -9005,8 +9070,10 @@ DROP TRIGGER IF EXISTS ${ad};`);
|
|
|
9005
9070
|
* model-directed move emits a `heal_deleted` / `heal_downgraded` receipt
|
|
9006
9071
|
* after commit (`applied`, `applied_unscreened`, or `below_floor`), in every
|
|
9007
9072
|
* mode. An `applied` receipt records that the model VERDICT was applied
|
|
9008
|
-
* (`downgradeByIds` runs
|
|
9009
|
-
* reduced confidence still gets an `applied` receipt
|
|
9073
|
+
* (`downgradeByIds` runs for every applied id): a fact that was already at
|
|
9074
|
+
* reduced confidence still gets an `applied` receipt even though the row
|
|
9075
|
+
* write and its outbox UPDATE are skipped for an already-'tentative' fact
|
|
9076
|
+
* (specs/okf-v03 §C4). A withheld delete paired with a restating `newFact` leaves the fact
|
|
9010
9077
|
* live and the restatement is skipped as `fact_deduplicated`.
|
|
9011
9078
|
*/
|
|
9012
9079
|
async doRunHeal(entityId, options) {
|
|
@@ -9071,11 +9138,14 @@ DROP TRIGGER IF EXISTS ${ad};`);
|
|
|
9071
9138
|
...keywordUnavailable ? { searchUnavailable: true } : {}
|
|
9072
9139
|
};
|
|
9073
9140
|
}
|
|
9074
|
-
const allTasks = await this.taskRepo.findAllPending([entityId], HEAL_MAX_TASKS)
|
|
9141
|
+
const allTasks = (await this.taskRepo.findAllPending([entityId], HEAL_MAX_TASKS)).map((t) => {
|
|
9142
|
+
const { okf_extra: _extra, stale_after_raw: _sraw, ...rest } = t;
|
|
9143
|
+
return rest;
|
|
9144
|
+
});
|
|
9075
9145
|
const recentEvents = await this.eventRepo.getRecent(entityId, 20);
|
|
9076
9146
|
const healGrounding = this.promptService.groundingFor("heal");
|
|
9077
9147
|
const toPromptShape = (f) => {
|
|
9078
|
-
const { embedding: _embedding, embedding_blob: _blob, ...rest } = f;
|
|
9148
|
+
const { embedding: _embedding, embedding_blob: _blob, okf_extra: _extra, stale_after_raw: _sraw, ...rest } = f;
|
|
9079
9149
|
const shown = healGrounding ? (({ lifecycle_status: _l, okf_verified: _v, last_verified_at: _a, last_verified_by: _b, ...r }) => r)(rest) : rest;
|
|
9080
9150
|
return { ...shown, tags: typeof shown.tags === "string" ? JSON.parse(shown.tags) : shown.tags };
|
|
9081
9151
|
};
|
|
@@ -9251,7 +9321,8 @@ DROP TRIGGER IF EXISTS ${ad};`);
|
|
|
9251
9321
|
continue;
|
|
9252
9322
|
}
|
|
9253
9323
|
const id = generateId("fact_");
|
|
9254
|
-
const
|
|
9324
|
+
const writeNow = Date.now();
|
|
9325
|
+
const grounding = healGrounding ? groundingOutcome(checkGrounding(fact.evidence, validNewFactCorpora[k] ?? [], healGrounding), writeNow) : null;
|
|
9255
9326
|
if (grounding?.diagnostic) {
|
|
9256
9327
|
diagBuffer.push({ ...diagBase, code: grounding.diagnostic.code, detail: { factId: id, itemIndex: validNewFactItemIndexes[k], reason: grounding.diagnostic.reason } });
|
|
9257
9328
|
}
|
|
@@ -9266,14 +9337,17 @@ DROP TRIGGER IF EXISTS ${ad};`);
|
|
|
9266
9337
|
source_hash: null,
|
|
9267
9338
|
source_ref: null,
|
|
9268
9339
|
source_pointer: null,
|
|
9269
|
-
created_at:
|
|
9270
|
-
updated_at:
|
|
9340
|
+
created_at: writeNow,
|
|
9341
|
+
updated_at: writeNow,
|
|
9271
9342
|
last_accessed_at: null,
|
|
9272
9343
|
access_count: 0,
|
|
9273
9344
|
deleted_at: null,
|
|
9345
|
+
// §C1: the engine authored this restatement, so a NULL row actor is
|
|
9346
|
+
// stamped; the upsert's COALESCE never overwrites a stored actor.
|
|
9347
|
+
generated_by: ENGINE_ACTOR,
|
|
9274
9348
|
...grounding?.trust
|
|
9275
9349
|
};
|
|
9276
|
-
await this.entryRepo.upsert(factObj, tx);
|
|
9350
|
+
await this.entryRepo.upsert(factObj, tx, writeNow);
|
|
9277
9351
|
insertedFacts.push({ id, entity_id: entityId, title: fact.title, body: fact.body, tags: JSON.stringify(fact.tags) });
|
|
9278
9352
|
healFactsForDedupe.push({ id, title: fact.title });
|
|
9279
9353
|
}
|
|
@@ -10047,6 +10121,752 @@ DROP TRIGGER IF EXISTS ${ad};`);
|
|
|
10047
10121
|
_MaintenanceService.FTS_SHADOW_SUFFIXES = ["_content", "_data", "_idx", "_docsize", "_config"];
|
|
10048
10122
|
var MaintenanceService = _MaintenanceService;
|
|
10049
10123
|
|
|
10124
|
+
// src/utils/sourcePointer.ts
|
|
10125
|
+
var POINTER_SLOTS = ["event_id", "ref", "quote", "position"];
|
|
10126
|
+
function isStringOrNull(v) {
|
|
10127
|
+
return v === null || typeof v === "string";
|
|
10128
|
+
}
|
|
10129
|
+
function isValidPosition(v) {
|
|
10130
|
+
if (v === null) return true;
|
|
10131
|
+
if (typeof v !== "object" || v === null || Array.isArray(v)) return false;
|
|
10132
|
+
const o = v;
|
|
10133
|
+
const keys = Object.keys(o);
|
|
10134
|
+
if (keys.length !== 2 || !("start" in o) || !("length" in o)) return false;
|
|
10135
|
+
const { start, length } = o;
|
|
10136
|
+
return typeof start === "number" && Number.isInteger(start) && start >= 0 && typeof length === "number" && Number.isInteger(length) && length >= 0;
|
|
10137
|
+
}
|
|
10138
|
+
function validateSourcePointerValue(v) {
|
|
10139
|
+
if (v === null) return null;
|
|
10140
|
+
if (typeof v !== "object" || Array.isArray(v)) return void 0;
|
|
10141
|
+
const o = v;
|
|
10142
|
+
const keys = Object.keys(o);
|
|
10143
|
+
for (const k of keys) {
|
|
10144
|
+
if (!POINTER_SLOTS.includes(k)) return void 0;
|
|
10145
|
+
}
|
|
10146
|
+
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"])) {
|
|
10147
|
+
return void 0;
|
|
10148
|
+
}
|
|
10149
|
+
if (!isValidPosition(o["position"] === void 0 ? null : o["position"])) return void 0;
|
|
10150
|
+
const normalized = {
|
|
10151
|
+
event_id: o["event_id"] ?? null,
|
|
10152
|
+
ref: o["ref"] ?? null,
|
|
10153
|
+
quote: o["quote"] ?? null,
|
|
10154
|
+
position: o["position"] ?? null
|
|
10155
|
+
};
|
|
10156
|
+
if (normalized.event_id === null && normalized.ref === null && normalized.quote === null && normalized.position === null) {
|
|
10157
|
+
return null;
|
|
10158
|
+
}
|
|
10159
|
+
return normalized;
|
|
10160
|
+
}
|
|
10161
|
+
function parseStoredSourcePointer(raw) {
|
|
10162
|
+
if (raw === null || raw === void 0) return null;
|
|
10163
|
+
if (typeof raw !== "string") return null;
|
|
10164
|
+
let parsed;
|
|
10165
|
+
try {
|
|
10166
|
+
parsed = JSON.parse(raw);
|
|
10167
|
+
} catch {
|
|
10168
|
+
return null;
|
|
10169
|
+
}
|
|
10170
|
+
const v = validateSourcePointerValue(parsed);
|
|
10171
|
+
return v === void 0 ? null : v;
|
|
10172
|
+
}
|
|
10173
|
+
function serializeSourcePointer(p) {
|
|
10174
|
+
return p ? JSON.stringify(p) : null;
|
|
10175
|
+
}
|
|
10176
|
+
var CONFIDENCE_VALUES = /* @__PURE__ */ new Set(["certain", "inferred", "tentative"]);
|
|
10177
|
+
var SOURCE_TYPES = /* @__PURE__ */ new Set([
|
|
10178
|
+
"user_stated",
|
|
10179
|
+
"librarian_inferred",
|
|
10180
|
+
"user_confirmed",
|
|
10181
|
+
"immutable_document"
|
|
10182
|
+
]);
|
|
10183
|
+
var TASK_STATUSES = /* @__PURE__ */ new Set(["pending", "in_progress", "done", "abandoned"]);
|
|
10184
|
+
var LIFECYCLE_VALUES = /* @__PURE__ */ new Set(["draft", "stable", "deprecated"]);
|
|
10185
|
+
var EVENT_TYPES = /* @__PURE__ */ new Set(["observation", "decision", "action", "outcome"]);
|
|
10186
|
+
var FACT_MAPPED_KEYS = [
|
|
10187
|
+
"type",
|
|
10188
|
+
"title",
|
|
10189
|
+
"tags",
|
|
10190
|
+
"timestamp",
|
|
10191
|
+
"resource",
|
|
10192
|
+
"id",
|
|
10193
|
+
"entity_id",
|
|
10194
|
+
"confidence",
|
|
10195
|
+
"source_type",
|
|
10196
|
+
"source_hash",
|
|
10197
|
+
"created_at",
|
|
10198
|
+
"updated_at",
|
|
10199
|
+
"access_count",
|
|
10200
|
+
"last_accessed_at",
|
|
10201
|
+
"deleted_at",
|
|
10202
|
+
"status",
|
|
10203
|
+
"stale_after",
|
|
10204
|
+
"generated",
|
|
10205
|
+
"verified",
|
|
10206
|
+
"sources",
|
|
10207
|
+
"usage_window",
|
|
10208
|
+
"valid_from",
|
|
10209
|
+
"valid_to",
|
|
10210
|
+
"superseded_by",
|
|
10211
|
+
"superseded_at",
|
|
10212
|
+
"prior_valid_to",
|
|
10213
|
+
"source_pointer",
|
|
10214
|
+
"derived_events",
|
|
10215
|
+
"x-llm-wiki-lifecycle"
|
|
10216
|
+
];
|
|
10217
|
+
var TASK_MAPPED_KEYS = [
|
|
10218
|
+
"type",
|
|
10219
|
+
"title",
|
|
10220
|
+
"timestamp",
|
|
10221
|
+
"id",
|
|
10222
|
+
"entity_id",
|
|
10223
|
+
"status",
|
|
10224
|
+
"execution_status",
|
|
10225
|
+
"priority",
|
|
10226
|
+
"created_at",
|
|
10227
|
+
"updated_at",
|
|
10228
|
+
"resolved_at",
|
|
10229
|
+
"deleted_at",
|
|
10230
|
+
"stale_after",
|
|
10231
|
+
"generated",
|
|
10232
|
+
"verified",
|
|
10233
|
+
"sources",
|
|
10234
|
+
"usage_window"
|
|
10235
|
+
];
|
|
10236
|
+
var FACT_MAPPED = new Set(FACT_MAPPED_KEYS);
|
|
10237
|
+
var TASK_MAPPED = new Set(TASK_MAPPED_KEYS);
|
|
10238
|
+
var RAW_SLOT_KEY = "x-llm-wiki-raw";
|
|
10239
|
+
function basenameMd(filePath) {
|
|
10240
|
+
const name = filePath.slice(filePath.lastIndexOf("/") + 1);
|
|
10241
|
+
return name.endsWith(".md") ? name.slice(0, -3) : name;
|
|
10242
|
+
}
|
|
10243
|
+
function isConceptFile(filePath) {
|
|
10244
|
+
if (!filePath.endsWith(".md")) return false;
|
|
10245
|
+
if (filePath.endsWith("/index.md") || filePath === "index.md") return false;
|
|
10246
|
+
if (filePath.endsWith("/log.md") || filePath === "log.md") return false;
|
|
10247
|
+
return true;
|
|
10248
|
+
}
|
|
10249
|
+
function isStructuralPath(filePath) {
|
|
10250
|
+
return filePath.endsWith("/index.md") || filePath === "index.md" || filePath.endsWith("/log.md") || filePath === "log.md";
|
|
10251
|
+
}
|
|
10252
|
+
function posixDirname(filePath) {
|
|
10253
|
+
const idx = filePath.lastIndexOf("/");
|
|
10254
|
+
return idx === -1 ? "" : filePath.slice(0, idx);
|
|
10255
|
+
}
|
|
10256
|
+
function resolveRelativePath(fromFile, linkPath) {
|
|
10257
|
+
const baseDir = posixDirname(fromFile);
|
|
10258
|
+
const segments = [...baseDir ? baseDir.split("/") : [], ...linkPath.split("/")];
|
|
10259
|
+
const resolved = [];
|
|
10260
|
+
for (const seg of segments) {
|
|
10261
|
+
if (seg === "" || seg === ".") continue;
|
|
10262
|
+
if (seg === "..") {
|
|
10263
|
+
resolved.pop();
|
|
10264
|
+
continue;
|
|
10265
|
+
}
|
|
10266
|
+
resolved.push(seg);
|
|
10267
|
+
}
|
|
10268
|
+
return resolved.join("/");
|
|
10269
|
+
}
|
|
10270
|
+
function strictTargetPath(fromFile, strippedPath) {
|
|
10271
|
+
return strippedPath.startsWith("/") ? strippedPath.slice(1) : resolveRelativePath(fromFile, strippedPath);
|
|
10272
|
+
}
|
|
10273
|
+
function resolveSupersededBy(raw, filePath, isV3Bundle, bundleRootPathToId) {
|
|
10274
|
+
if (!isV3Bundle) return raw;
|
|
10275
|
+
return bundleRootPathToId.get(strictTargetPath(filePath, raw)) ?? raw;
|
|
10276
|
+
}
|
|
10277
|
+
function decodeLinkPath(path) {
|
|
10278
|
+
if (!path.includes("%")) return path;
|
|
10279
|
+
try {
|
|
10280
|
+
return decodeURIComponent(path);
|
|
10281
|
+
} catch {
|
|
10282
|
+
return path;
|
|
10283
|
+
}
|
|
10284
|
+
}
|
|
10285
|
+
function addPathAliases(map, filePath, resolvedId) {
|
|
10286
|
+
map.set(filePath, resolvedId);
|
|
10287
|
+
const withoutDot = filePath.replace(/^\.\//, "");
|
|
10288
|
+
if (withoutDot !== filePath) map.set(withoutDot, resolvedId);
|
|
10289
|
+
const entityRelative = filePath.replace(/^entities\/[^/]+\//, "");
|
|
10290
|
+
if (entityRelative !== filePath) {
|
|
10291
|
+
map.set(entityRelative, resolvedId);
|
|
10292
|
+
map.set(`./${entityRelative}`, resolvedId);
|
|
10293
|
+
}
|
|
10294
|
+
}
|
|
10295
|
+
function lookupResolvedId(map, path) {
|
|
10296
|
+
const normalized = path.replace(/^\.\//, "");
|
|
10297
|
+
return map.get(path) ?? map.get(normalized) ?? map.get(`./${normalized}`);
|
|
10298
|
+
}
|
|
10299
|
+
function stripLinkSuffix(linkPath) {
|
|
10300
|
+
const hashIdx = linkPath.indexOf("#");
|
|
10301
|
+
const queryIdx = linkPath.indexOf("?");
|
|
10302
|
+
if (hashIdx === -1 && queryIdx === -1) return linkPath;
|
|
10303
|
+
const cut = hashIdx === -1 ? queryIdx : queryIdx === -1 ? hashIdx : Math.min(hashIdx, queryIdx);
|
|
10304
|
+
return linkPath.slice(0, cut);
|
|
10305
|
+
}
|
|
10306
|
+
function resolveRoute(filePath, frontmatterType, options) {
|
|
10307
|
+
if (options?.typeMapping && Object.prototype.hasOwnProperty.call(options.typeMapping, frontmatterType)) {
|
|
10308
|
+
return options.typeMapping[frontmatterType];
|
|
10309
|
+
}
|
|
10310
|
+
if (filePath.includes("/facts/")) return "fact";
|
|
10311
|
+
if (filePath.includes("/tasks/")) return "task";
|
|
10312
|
+
return options?.defaultSchema ?? "fact";
|
|
10313
|
+
}
|
|
10314
|
+
function parseFrontmatterTimestamp(value, fallback) {
|
|
10315
|
+
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
10316
|
+
if (typeof value === "string") {
|
|
10317
|
+
const parsed = Date.parse(value);
|
|
10318
|
+
if (Number.isFinite(parsed)) return parsed;
|
|
10319
|
+
}
|
|
10320
|
+
return fallback;
|
|
10321
|
+
}
|
|
10322
|
+
function parseStaleAfterPair(raw, parserUnreadable) {
|
|
10323
|
+
if (parserUnreadable) {
|
|
10324
|
+
return { stale_after: null, stale_after_raw: "unreadable" };
|
|
10325
|
+
}
|
|
10326
|
+
if (raw === void 0 || raw === null || Array.isArray(raw) && raw.length === 0) {
|
|
10327
|
+
return { stale_after: null, stale_after_raw: null };
|
|
10328
|
+
}
|
|
10329
|
+
if (typeof raw === "string" && raw.trim() === "") {
|
|
10330
|
+
return { stale_after: null, stale_after_raw: null };
|
|
10331
|
+
}
|
|
10332
|
+
if (typeof raw === "string") {
|
|
10333
|
+
const epoch = parseOkfTimestamp(raw);
|
|
10334
|
+
return epoch != null ? { stale_after: epoch, stale_after_raw: null } : { stale_after: null, stale_after_raw: raw };
|
|
10335
|
+
}
|
|
10336
|
+
if (typeof raw === "object") {
|
|
10337
|
+
return { stale_after: null, stale_after_raw: JSON.stringify(raw) };
|
|
10338
|
+
}
|
|
10339
|
+
return { stale_after: null, stale_after_raw: String(raw) };
|
|
10340
|
+
}
|
|
10341
|
+
function parseTagsList(raw) {
|
|
10342
|
+
if (typeof raw === "string") return raw === "" ? [] : [raw];
|
|
10343
|
+
if (Array.isArray(raw)) return raw.filter((t) => typeof t === "string");
|
|
10344
|
+
return [];
|
|
10345
|
+
}
|
|
10346
|
+
function replaceLoneSurrogates(s) {
|
|
10347
|
+
let out = "";
|
|
10348
|
+
for (let i = 0; i < s.length; i++) {
|
|
10349
|
+
const c = s.charCodeAt(i);
|
|
10350
|
+
if (c >= 55296 && c <= 56319) {
|
|
10351
|
+
const n = i + 1 < s.length ? s.charCodeAt(i + 1) : 0;
|
|
10352
|
+
if (n >= 56320 && n <= 57343) {
|
|
10353
|
+
out += s[i] + s[i + 1];
|
|
10354
|
+
i++;
|
|
10355
|
+
} else out += "\uFFFD";
|
|
10356
|
+
} else if (c >= 56320 && c <= 57343) {
|
|
10357
|
+
out += "\uFFFD";
|
|
10358
|
+
} else {
|
|
10359
|
+
out += s[i];
|
|
10360
|
+
}
|
|
10361
|
+
}
|
|
10362
|
+
return out;
|
|
10363
|
+
}
|
|
10364
|
+
function unescapeLogSummary(summary) {
|
|
10365
|
+
return summary.replace(/\\\]/g, "]").replace(/\\\[/g, "[").replace(/\\\\/g, "\\");
|
|
10366
|
+
}
|
|
10367
|
+
var LOG_LINE_PATTERN = /^\(([^)]+)\)\s*(?:\[((?:\\.|[^\[\]\\])*)\]\(([^)]+)\)|(\S.*))$/;
|
|
10368
|
+
function parseLogEntryText(text) {
|
|
10369
|
+
const match = LOG_LINE_PATTERN.exec(text.trim());
|
|
10370
|
+
if (!match) return null;
|
|
10371
|
+
const [, rawType, linkedSummary, linkPath, plainSummary] = match;
|
|
10372
|
+
const event_type = EVENT_TYPES.has(rawType) ? rawType : "observation";
|
|
10373
|
+
if (linkPath) {
|
|
10374
|
+
return { event_type, summary: unescapeLogSummary(linkedSummary), linkPath };
|
|
10375
|
+
}
|
|
10376
|
+
return { event_type, summary: unescapeLogSummary((plainSummary ?? "").trim()) };
|
|
10377
|
+
}
|
|
10378
|
+
function parseLifecycleStatus(raw) {
|
|
10379
|
+
if (typeof raw === "string") {
|
|
10380
|
+
if (LIFECYCLE_VALUES.has(raw)) return raw;
|
|
10381
|
+
return raw === "" ? "stable" : raw;
|
|
10382
|
+
}
|
|
10383
|
+
if (raw === null || raw === void 0) return "stable";
|
|
10384
|
+
if (typeof raw === "object") return JSON.stringify(raw);
|
|
10385
|
+
return String(raw);
|
|
10386
|
+
}
|
|
10387
|
+
function isUnreadable(frontmatter, issues, key) {
|
|
10388
|
+
return issues.some((i) => i.key === key) && !Object.prototype.hasOwnProperty.call(frontmatter, key);
|
|
10389
|
+
}
|
|
10390
|
+
function extractOkfExtra(mapped, frontmatter, unparsed) {
|
|
10391
|
+
const extras = {};
|
|
10392
|
+
for (const [key, value] of Object.entries(frontmatter)) {
|
|
10393
|
+
if (mapped.has(key) || key === RAW_SLOT_KEY) continue;
|
|
10394
|
+
if (Object.prototype.hasOwnProperty.call(unparsed.raw, key)) continue;
|
|
10395
|
+
extras[key] = value;
|
|
10396
|
+
}
|
|
10397
|
+
const rawSlot = {};
|
|
10398
|
+
for (const [key, lines] of Object.entries(unparsed.raw)) {
|
|
10399
|
+
if (mapped.has(key) || key === RAW_SLOT_KEY) continue;
|
|
10400
|
+
rawSlot[key] = lines;
|
|
10401
|
+
}
|
|
10402
|
+
if (Object.keys(rawSlot).length > 0) extras[RAW_SLOT_KEY] = rawSlot;
|
|
10403
|
+
const generated = frontmatter.generated;
|
|
10404
|
+
if (generated !== null && typeof generated === "object" && !Array.isArray(generated)) {
|
|
10405
|
+
const nested = {};
|
|
10406
|
+
for (const [k, v] of Object.entries(generated)) {
|
|
10407
|
+
if (k === "by" || k === "at") continue;
|
|
10408
|
+
nested[k] = v;
|
|
10409
|
+
}
|
|
10410
|
+
if (Object.keys(nested).length > 0) extras.generated = nested;
|
|
10411
|
+
}
|
|
10412
|
+
return Object.keys(extras).length > 0 ? extras : void 0;
|
|
10413
|
+
}
|
|
10414
|
+
var SKIPPED_FILES_CAP = 100;
|
|
10415
|
+
function reportDroppedValues(mapped, filePath, frontmatter, unparsed, droppedValues) {
|
|
10416
|
+
for (const issue of unparsed.issues) {
|
|
10417
|
+
if (issue.key === RAW_SLOT_KEY) continue;
|
|
10418
|
+
if (Object.prototype.hasOwnProperty.call(frontmatter, issue.key)) continue;
|
|
10419
|
+
if (issue.reason !== "anchor_or_alias" && !mapped.has(issue.key)) continue;
|
|
10420
|
+
if (issue.reason === "anchor_or_alias" && Object.prototype.hasOwnProperty.call(unparsed.raw, issue.key)) continue;
|
|
10421
|
+
droppedValues.push({ path: filePath, key: issue.key, reason: issue.reason });
|
|
10422
|
+
}
|
|
10423
|
+
if (Object.prototype.hasOwnProperty.call(frontmatter, RAW_SLOT_KEY) || Object.prototype.hasOwnProperty.call(unparsed.raw, RAW_SLOT_KEY)) {
|
|
10424
|
+
droppedValues.push({ path: filePath, key: RAW_SLOT_KEY, reason: "reserved_key" });
|
|
10425
|
+
}
|
|
10426
|
+
const statusRaw = frontmatter.status;
|
|
10427
|
+
if (statusRaw !== null && statusRaw !== void 0 && typeof statusRaw === "object") {
|
|
10428
|
+
droppedValues.push({ path: filePath, key: "status", reason: "not_scalar" });
|
|
10429
|
+
}
|
|
10430
|
+
const { ignored } = parseSourcesFlexible(frontmatter.sources);
|
|
10431
|
+
if (ignored > 0) {
|
|
10432
|
+
droppedValues.push({ path: filePath, key: "sources", reason: `sources_entry_invalid:${ignored}` });
|
|
10433
|
+
}
|
|
10434
|
+
const rawVerified = frontmatter.verified;
|
|
10435
|
+
const verifiedTotal = Array.isArray(rawVerified) ? rawVerified.length : rawVerified !== null && typeof rawVerified === "object" ? 1 : 0;
|
|
10436
|
+
const verifiedInvalid = verifiedTotal - parseVerifiedFlexible(rawVerified).length;
|
|
10437
|
+
if (verifiedInvalid > 0) {
|
|
10438
|
+
droppedValues.push({ path: filePath, key: "verified", reason: `verified_entry_invalid:${verifiedInvalid}` });
|
|
10439
|
+
}
|
|
10440
|
+
const title = frontmatter.title;
|
|
10441
|
+
if (title !== null && title !== void 0 && typeof title !== "string" && !(Array.isArray(title) && title.length === 0)) {
|
|
10442
|
+
droppedValues.push({ path: filePath, key: "title", reason: "wrong_type" });
|
|
10443
|
+
}
|
|
10444
|
+
const usageWindow = frontmatter.usage_window;
|
|
10445
|
+
if (usageWindow !== null && usageWindow !== void 0 && usageWindow !== "" && typeof usageWindow !== "object") {
|
|
10446
|
+
droppedValues.push({ path: filePath, key: "usage_window", reason: "wrong_type" });
|
|
10447
|
+
}
|
|
10448
|
+
const generated = frontmatter.generated;
|
|
10449
|
+
if (generated !== null && generated !== void 0 && !(Array.isArray(generated) && generated.length === 0)) {
|
|
10450
|
+
if (typeof generated !== "object" || Array.isArray(generated)) {
|
|
10451
|
+
droppedValues.push({ path: filePath, key: "generated", reason: "wrong_type" });
|
|
10452
|
+
} else if (generated.by == null) {
|
|
10453
|
+
droppedValues.push({ path: filePath, key: "generated", reason: "generated_without_by" });
|
|
10454
|
+
}
|
|
10455
|
+
}
|
|
10456
|
+
}
|
|
10457
|
+
function frontmatterToFact(entityId, id, frontmatter, body, now, droppedPointerValues, isV3Bundle, unparsed, filePath, droppedValues, bundleRootPathToId) {
|
|
10458
|
+
reportDroppedValues(FACT_MAPPED, filePath, frontmatter, unparsed, droppedValues);
|
|
10459
|
+
const hasLifecycleKey = Object.prototype.hasOwnProperty.call(frontmatter, "x-llm-wiki-lifecycle");
|
|
10460
|
+
const lifecycleKeyValue = frontmatter["x-llm-wiki-lifecycle"];
|
|
10461
|
+
const restoreLifecycle = hasLifecycleKey && isV3Bundle && typeof lifecycleKeyValue === "string" && lifecycleKeyValue !== "" && parseLifecycleStatus(frontmatter.status) === "deprecated";
|
|
10462
|
+
if (hasLifecycleKey && !restoreLifecycle) {
|
|
10463
|
+
droppedValues.push({ path: filePath, key: "x-llm-wiki-lifecycle", reason: "not_applicable" });
|
|
10464
|
+
}
|
|
10465
|
+
const created_at = parseFrontmatterTimestamp(frontmatter.created_at, now);
|
|
10466
|
+
const generatedAt = parseOkfTimestamp(frontmatter.generated?.at);
|
|
10467
|
+
const updated_at = generatedAt ?? parseFrontmatterTimestamp(
|
|
10468
|
+
frontmatter.timestamp,
|
|
10469
|
+
parseFrontmatterTimestamp(frontmatter.updated_at, now)
|
|
10470
|
+
);
|
|
10471
|
+
const verified = parseVerifiedFlexible(frontmatter.verified);
|
|
10472
|
+
const rawSources = frontmatter.sources;
|
|
10473
|
+
const hasSourcesKey = rawSources !== void 0 || isUnreadable(frontmatter, unparsed.issues, "sources");
|
|
10474
|
+
const { sources } = parseSourcesFlexible(rawSources);
|
|
10475
|
+
const usageWindow = frontmatter.usage_window && typeof frontmatter.usage_window === "object" ? frontmatter.usage_window : null;
|
|
10476
|
+
const lastV = latestVerified(verified, now);
|
|
10477
|
+
const lifecycle_status = isUnreadable(frontmatter, unparsed.issues, "status") ? "unreadable" : restoreLifecycle ? parseLifecycleStatus(lifecycleKeyValue) : parseLifecycleStatus(frontmatter.status);
|
|
10478
|
+
const { stale_after, stale_after_raw } = parseStaleAfterPair(
|
|
10479
|
+
frontmatter.stale_after,
|
|
10480
|
+
isUnreadable(frontmatter, unparsed.issues, "stale_after")
|
|
10481
|
+
);
|
|
10482
|
+
const generated_by = frontmatter.generated?.by ?? null;
|
|
10483
|
+
const okf_extra = extractOkfExtra(FACT_MAPPED, frontmatter, unparsed);
|
|
10484
|
+
if (!hasSourcesKey && !isV3Bundle) {
|
|
10485
|
+
const urls = parseCitationsList(body);
|
|
10486
|
+
for (const url of urls) {
|
|
10487
|
+
sources.push({ resource: url });
|
|
10488
|
+
}
|
|
10489
|
+
}
|
|
10490
|
+
return {
|
|
10491
|
+
id,
|
|
10492
|
+
entity_id: entityId,
|
|
10493
|
+
title: typeof frontmatter.title === "string" ? frontmatter.title : "",
|
|
10494
|
+
body,
|
|
10495
|
+
tags: parseTagsList(frontmatter.tags),
|
|
10496
|
+
confidence: CONFIDENCE_VALUES.has(String(frontmatter.confidence)) ? frontmatter.confidence : "tentative",
|
|
10497
|
+
source_type: SOURCE_TYPES.has(String(frontmatter.source_type)) ? frontmatter.source_type : "user_stated",
|
|
10498
|
+
source_hash: typeof frontmatter.source_hash === "string" ? frontmatter.source_hash : null,
|
|
10499
|
+
source_ref: typeof frontmatter.resource === "string" ? frontmatter.resource : null,
|
|
10500
|
+
created_at,
|
|
10501
|
+
updated_at,
|
|
10502
|
+
last_accessed_at: frontmatter.last_accessed_at != null ? parseFrontmatterTimestamp(frontmatter.last_accessed_at, now) : null,
|
|
10503
|
+
access_count: typeof frontmatter.access_count === "number" ? frontmatter.access_count : 0,
|
|
10504
|
+
deleted_at: frontmatter.deleted_at != null ? parseFrontmatterTimestamp(frontmatter.deleted_at, 0) : null,
|
|
10505
|
+
okf_type: frontmatter.type,
|
|
10506
|
+
// OKF v0.2
|
|
10507
|
+
lifecycle_status,
|
|
10508
|
+
stale_after,
|
|
10509
|
+
// OKF v0.3 §B3: the sibling raw slot of the pair above — verbatim wire
|
|
10510
|
+
// text when the value would not parse, NULL when it did (or was absent).
|
|
10511
|
+
stale_after_raw,
|
|
10512
|
+
generated_by,
|
|
10513
|
+
okf_sources: sources,
|
|
10514
|
+
okf_verified: verified,
|
|
10515
|
+
okf_usage_window: usageWindow,
|
|
10516
|
+
last_verified_at: lastV?.at ?? null,
|
|
10517
|
+
last_verified_by: lastV?.by ?? null,
|
|
10518
|
+
...okf_extra ? { okf_extra } : {},
|
|
10519
|
+
...optionalEpoch("valid_from", frontmatter.valid_from),
|
|
10520
|
+
...optionalEpoch("valid_to", frontmatter.valid_to),
|
|
10521
|
+
...typeof frontmatter.superseded_by === "string" ? {
|
|
10522
|
+
superseded_by: resolveSupersededBy(
|
|
10523
|
+
frontmatter.superseded_by,
|
|
10524
|
+
filePath,
|
|
10525
|
+
isV3Bundle,
|
|
10526
|
+
bundleRootPathToId
|
|
10527
|
+
)
|
|
10528
|
+
} : {},
|
|
10529
|
+
...optionalEpoch("superseded_at", frontmatter.superseded_at),
|
|
10530
|
+
...optionalEpoch("prior_valid_to", frontmatter.prior_valid_to),
|
|
10531
|
+
// Source pointer (specs/source-pointers §Export, import, and OKF): the
|
|
10532
|
+
// parse path has no diagnostic channel, so it reports through the result.
|
|
10533
|
+
// ABSENT key → the property is omitted (not null), so the import
|
|
10534
|
+
// presence guard survives the parse. Malformed → the property is omitted
|
|
10535
|
+
// AND the drop is reported as entry id + reason slug — never the raw
|
|
10536
|
+
// value, which can carry quote text.
|
|
10537
|
+
...(() => {
|
|
10538
|
+
const raw = frontmatter.source_pointer;
|
|
10539
|
+
if (raw === void 0) return {};
|
|
10540
|
+
const v = validateSourcePointerValue(raw);
|
|
10541
|
+
if (v === void 0) {
|
|
10542
|
+
droppedPointerValues.push({ factId: id, reason: "malformed" });
|
|
10543
|
+
return {};
|
|
10544
|
+
}
|
|
10545
|
+
return { source_pointer: v };
|
|
10546
|
+
})(),
|
|
10547
|
+
// derived_events (specs/inplace-update-provenance §5): a well-formed list
|
|
10548
|
+
// is restored; absent or empty omits the property (import presence rule);
|
|
10549
|
+
// malformed omits it AND is reported by id + slug, never the raw value.
|
|
10550
|
+
...(() => {
|
|
10551
|
+
const raw = frontmatter.derived_events;
|
|
10552
|
+
if (raw === void 0) return {};
|
|
10553
|
+
const v = validateDerivedEventsValue(raw);
|
|
10554
|
+
if (v === void 0) {
|
|
10555
|
+
droppedPointerValues.push({ factId: id, reason: "derived_events_malformed" });
|
|
10556
|
+
return {};
|
|
10557
|
+
}
|
|
10558
|
+
return v ? { derived_events: v } : {};
|
|
10559
|
+
})()
|
|
10560
|
+
};
|
|
10561
|
+
}
|
|
10562
|
+
function optionalEpoch(key, v) {
|
|
10563
|
+
return typeof v === "number" && Number.isFinite(v) && v >= 0 ? { [key]: Math.trunc(v) } : {};
|
|
10564
|
+
}
|
|
10565
|
+
function frontmatterToTask(entityId, id, frontmatter, now, usesV1StatusRule, unparsed, filePath, droppedValues) {
|
|
10566
|
+
reportDroppedValues(TASK_MAPPED, filePath, frontmatter, unparsed, droppedValues);
|
|
10567
|
+
const created_at = parseFrontmatterTimestamp(frontmatter.created_at, now);
|
|
10568
|
+
const generatedAt = parseOkfTimestamp(frontmatter.generated?.at);
|
|
10569
|
+
const updated_at = generatedAt ?? parseFrontmatterTimestamp(
|
|
10570
|
+
frontmatter.timestamp,
|
|
10571
|
+
parseFrontmatterTimestamp(frontmatter.updated_at, now)
|
|
10572
|
+
);
|
|
10573
|
+
const verified = parseVerifiedFlexible(frontmatter.verified);
|
|
10574
|
+
const { sources } = parseSourcesFlexible(frontmatter.sources);
|
|
10575
|
+
const usageWindow = frontmatter.usage_window && typeof frontmatter.usage_window === "object" ? frontmatter.usage_window : null;
|
|
10576
|
+
const lastV = latestVerified(verified, now);
|
|
10577
|
+
const lifecycleRaw = frontmatter.status;
|
|
10578
|
+
const executionRaw = frontmatter.execution_status;
|
|
10579
|
+
const isExecutionStatus = (v) => typeof v === "string" && TASK_STATUSES.has(v);
|
|
10580
|
+
const executionFromWire = !isExecutionStatus(executionRaw) && isExecutionStatus(lifecycleRaw);
|
|
10581
|
+
const lifecycle_status = usesV1StatusRule || executionFromWire ? "stable" : isUnreadable(frontmatter, unparsed.issues, "status") ? "unreadable" : parseLifecycleStatus(lifecycleRaw);
|
|
10582
|
+
const { stale_after, stale_after_raw } = parseStaleAfterPair(
|
|
10583
|
+
frontmatter.stale_after,
|
|
10584
|
+
isUnreadable(frontmatter, unparsed.issues, "stale_after")
|
|
10585
|
+
);
|
|
10586
|
+
const okf_extra = extractOkfExtra(TASK_MAPPED, frontmatter, unparsed);
|
|
10587
|
+
let executionState;
|
|
10588
|
+
if (usesV1StatusRule) {
|
|
10589
|
+
executionState = isExecutionStatus(lifecycleRaw) ? lifecycleRaw : "pending";
|
|
10590
|
+
} else {
|
|
10591
|
+
executionState = isExecutionStatus(executionRaw) ? executionRaw : isExecutionStatus(lifecycleRaw) ? lifecycleRaw : "pending";
|
|
10592
|
+
}
|
|
10593
|
+
return {
|
|
10594
|
+
id,
|
|
10595
|
+
entity_id: entityId,
|
|
10596
|
+
description: typeof frontmatter.title === "string" ? frontmatter.title : "",
|
|
10597
|
+
status: executionState,
|
|
10598
|
+
priority: typeof frontmatter.priority === "number" ? frontmatter.priority : 0,
|
|
10599
|
+
created_at,
|
|
10600
|
+
updated_at,
|
|
10601
|
+
resolved_at: frontmatter.resolved_at != null ? parseFrontmatterTimestamp(frontmatter.resolved_at, now) : null,
|
|
10602
|
+
deleted_at: frontmatter.deleted_at != null ? parseFrontmatterTimestamp(frontmatter.deleted_at, 0) : null,
|
|
10603
|
+
okf_type: frontmatter.type,
|
|
10604
|
+
// OKF v0.2
|
|
10605
|
+
lifecycle_status,
|
|
10606
|
+
stale_after,
|
|
10607
|
+
// OKF v0.3 §B3: symmetric with facts — verbatim wire text when the value
|
|
10608
|
+
// would not parse, NULL when it did (or was absent).
|
|
10609
|
+
stale_after_raw,
|
|
10610
|
+
generated_by: frontmatter.generated?.by ?? null,
|
|
10611
|
+
okf_sources: sources,
|
|
10612
|
+
okf_verified: verified,
|
|
10613
|
+
okf_usage_window: usageWindow,
|
|
10614
|
+
last_verified_at: lastV?.at ?? null,
|
|
10615
|
+
last_verified_by: lastV?.by ?? null,
|
|
10616
|
+
...okf_extra ? { okf_extra } : {}
|
|
10617
|
+
};
|
|
10618
|
+
}
|
|
10619
|
+
function findLogMdPath(files) {
|
|
10620
|
+
return files.find((f) => f.path.endsWith("/log.md") || f.path === "log.md")?.path;
|
|
10621
|
+
}
|
|
10622
|
+
function extractEdgesFromLinks(filePath, resolvedId, links, pathToResolvedId, bundleRootPathToId, entityId, now, seenEdges, edges, isV3Bundle) {
|
|
10623
|
+
for (const link of links) {
|
|
10624
|
+
const strippedPath = stripLinkSuffix(decodeLinkPath(link.path));
|
|
10625
|
+
const resolvedTargetPath = resolveRelativePath(filePath, strippedPath);
|
|
10626
|
+
if (isStructuralPath(strippedPath) || isStructuralPath(resolvedTargetPath)) continue;
|
|
10627
|
+
const targetId = isV3Bundle ? bundleRootPathToId.get(strictTargetPath(filePath, strippedPath)) : lookupResolvedId(pathToResolvedId, strippedPath) ?? lookupResolvedId(pathToResolvedId, resolvedTargetPath);
|
|
10628
|
+
if (!targetId) continue;
|
|
10629
|
+
const edgeKey = `${resolvedId}\0${targetId}\0${link.text}`;
|
|
10630
|
+
if (seenEdges.has(edgeKey)) continue;
|
|
10631
|
+
seenEdges.add(edgeKey);
|
|
10632
|
+
edges.push({
|
|
10633
|
+
id: generateId(),
|
|
10634
|
+
entity_id: entityId,
|
|
10635
|
+
source_id: resolvedId,
|
|
10636
|
+
target_id: targetId,
|
|
10637
|
+
edge_type: link.text,
|
|
10638
|
+
created_at: now
|
|
10639
|
+
});
|
|
10640
|
+
}
|
|
10641
|
+
}
|
|
10642
|
+
function parseOkfVersionInts(raw) {
|
|
10643
|
+
if (typeof raw !== "string") return void 0;
|
|
10644
|
+
const m = /^(\d+)\.(\d+)$/.exec(raw);
|
|
10645
|
+
if (!m) return void 0;
|
|
10646
|
+
return { major: Number(m[1]), minor: Number(m[2]) };
|
|
10647
|
+
}
|
|
10648
|
+
function isVersion(v, major, minor) {
|
|
10649
|
+
return v !== void 0 && v.major === major && v.minor === minor;
|
|
10650
|
+
}
|
|
10651
|
+
function versionAtLeast(v, major, minor) {
|
|
10652
|
+
return v !== void 0 && (v.major > major || v.major === major && v.minor >= minor);
|
|
10653
|
+
}
|
|
10654
|
+
function detectOkfBundleLayout(meta) {
|
|
10655
|
+
const profile = meta.profile;
|
|
10656
|
+
const version = parseOkfVersionInts(meta.okf_version);
|
|
10657
|
+
const isProfile1 = profile === "llm-wiki/1";
|
|
10658
|
+
const isProfile2 = profile === "llm-wiki/2";
|
|
10659
|
+
const isProfile3 = profile === "llm-wiki/3";
|
|
10660
|
+
const isLegacyV1 = profile === void 0 && isVersion(version, 0, 1);
|
|
10661
|
+
const isVersionOnlyV2 = profile === void 0 && isVersion(version, 0, 2);
|
|
10662
|
+
const isUnknownProfileV2 = profile !== void 0 && !isProfile1 && !isProfile2 && !isProfile3 && isVersion(version, 0, 2);
|
|
10663
|
+
const isVersionOnlyV3 = profile === void 0 && versionAtLeast(version, 0, 3);
|
|
10664
|
+
const isUnknownProfileV3 = profile !== void 0 && !isProfile1 && !isProfile2 && !isProfile3 && versionAtLeast(version, 0, 3);
|
|
10665
|
+
const isV3Bundle = isProfile3 || isVersionOnlyV3 || isUnknownProfileV3;
|
|
10666
|
+
const summaryEligible = isProfile1 || isProfile2 || isLegacyV1 || isVersionOnlyV2 || isUnknownProfileV2 || isV3Bundle;
|
|
10667
|
+
return {
|
|
10668
|
+
isProfile1,
|
|
10669
|
+
isProfile2,
|
|
10670
|
+
isProfile3,
|
|
10671
|
+
isLegacyV1,
|
|
10672
|
+
isVersionOnlyV2,
|
|
10673
|
+
isUnknownProfileV2,
|
|
10674
|
+
isVersionOnlyV3,
|
|
10675
|
+
isUnknownProfileV3,
|
|
10676
|
+
isV3Bundle,
|
|
10677
|
+
summaryEligible
|
|
10678
|
+
};
|
|
10679
|
+
}
|
|
10680
|
+
function parseOkfBundle(entityId, files, options) {
|
|
10681
|
+
const now = Date.now();
|
|
10682
|
+
const normalizeOkfPath = (p) => p.replace(/^\.\//, "").replace(/\\/g, "/");
|
|
10683
|
+
const normalizedFiles = files.map((f) => ({ ...f, path: normalizeOkfPath(f.path) }));
|
|
10684
|
+
const allowlistedFiles = normalizedFiles.filter((f) => isAllowedOkfPath(f.path));
|
|
10685
|
+
const skippedFiles = [];
|
|
10686
|
+
for (const f of normalizedFiles) {
|
|
10687
|
+
if (!isAllowedOkfPath(f.path)) skippedFiles.push({ path: f.path, reason: "path_not_allowed" });
|
|
10688
|
+
}
|
|
10689
|
+
const entityDirs = new Set(
|
|
10690
|
+
allowlistedFiles.map((f) => /^entities\/([^/]+)\//.exec(f.path)?.[1]).filter((dir) => !!dir)
|
|
10691
|
+
);
|
|
10692
|
+
if (entityDirs.size > 1) {
|
|
10693
|
+
throw new Error(
|
|
10694
|
+
`parseOkfBundle: expected a single-entity bundle for "${entityId}", found entities: ${Array.from(entityDirs).join(", ")}`
|
|
10695
|
+
);
|
|
10696
|
+
}
|
|
10697
|
+
const entityDir = entityDirs.values().next().value ?? entityId;
|
|
10698
|
+
const entityPrefix = `entities/${entityDir}/`;
|
|
10699
|
+
const allowedFiles = allowlistedFiles.filter(
|
|
10700
|
+
(f) => f.path === "index.md" || f.path.startsWith(entityPrefix)
|
|
10701
|
+
);
|
|
10702
|
+
const rootIndex = allowedFiles.find((f) => f.path === "index.md");
|
|
10703
|
+
const profileMeta = rootIndex ? parseRootIndexMd(rootIndex.content) : {};
|
|
10704
|
+
const okfVersion = profileMeta.okf_version;
|
|
10705
|
+
const profile = profileMeta.profile;
|
|
10706
|
+
const { isProfile1, isLegacyV1, isV3Bundle, summaryEligible } = detectOkfBundleLayout(profileMeta);
|
|
10707
|
+
const droppedValues = [];
|
|
10708
|
+
if (rootIndex) {
|
|
10709
|
+
for (const issue of profileMeta.issues ?? []) {
|
|
10710
|
+
if (issue.reason === "anchor_or_alias") {
|
|
10711
|
+
droppedValues.push({ path: rootIndex.path, key: issue.key, reason: issue.reason });
|
|
10712
|
+
}
|
|
10713
|
+
}
|
|
10714
|
+
if (profileMeta.issues?.some((issue) => issue.key === RAW_SLOT_KEY && issue.reason === "reserved_key") || Object.prototype.hasOwnProperty.call(profileMeta.raw, RAW_SLOT_KEY)) {
|
|
10715
|
+
droppedValues.push({ path: rootIndex.path, key: RAW_SLOT_KEY, reason: "reserved_key" });
|
|
10716
|
+
}
|
|
10717
|
+
}
|
|
10718
|
+
const isTypeLessConcept = (filePath, type) => isV3Bundle && (filePath.includes("/facts/") || filePath.includes("/tasks/")) && (type === void 0 || type === "");
|
|
10719
|
+
let entitySummary;
|
|
10720
|
+
const entityIndex = allowedFiles.find((f) => f.path === `${entityPrefix}index.md`);
|
|
10721
|
+
if (summaryEligible && entityIndex) {
|
|
10722
|
+
const summary = parseEntityIndexMd(entityIndex.content).summary;
|
|
10723
|
+
entitySummary = summary || void 0;
|
|
10724
|
+
}
|
|
10725
|
+
const pathToResolvedId = /* @__PURE__ */ new Map();
|
|
10726
|
+
const bundleRootPathToId = /* @__PURE__ */ new Map();
|
|
10727
|
+
for (const file of allowedFiles) {
|
|
10728
|
+
if (!isConceptFile(file.path)) continue;
|
|
10729
|
+
const { frontmatter } = parseConcept(file.content);
|
|
10730
|
+
if (isTypeLessConcept(file.path, frontmatter.type)) {
|
|
10731
|
+
skippedFiles.push({ path: file.path, reason: "no_type" });
|
|
10732
|
+
continue;
|
|
10733
|
+
}
|
|
10734
|
+
const route = resolveRoute(file.path, frontmatter.type ?? "", options);
|
|
10735
|
+
if (route === "ignore") continue;
|
|
10736
|
+
const resolvedId = typeof frontmatter.id === "string" && frontmatter.id ? frontmatter.id : basenameMd(file.path);
|
|
10737
|
+
addPathAliases(pathToResolvedId, file.path, resolvedId);
|
|
10738
|
+
bundleRootPathToId.set(file.path, resolvedId);
|
|
10739
|
+
}
|
|
10740
|
+
const facts = [];
|
|
10741
|
+
const tasks = [];
|
|
10742
|
+
const droppedPointerValues = [];
|
|
10743
|
+
const edges = [];
|
|
10744
|
+
let logContent = null;
|
|
10745
|
+
const logMdPath = findLogMdPath(allowedFiles);
|
|
10746
|
+
for (const file of allowedFiles) {
|
|
10747
|
+
if (file.path.endsWith("/log.md") || file.path === "log.md") {
|
|
10748
|
+
logContent = file.content;
|
|
10749
|
+
continue;
|
|
10750
|
+
}
|
|
10751
|
+
if (!isConceptFile(file.path)) continue;
|
|
10752
|
+
const { frontmatter, body, raw: unparsedRaw, issues } = parseConcept(file.content);
|
|
10753
|
+
if (isTypeLessConcept(file.path, frontmatter.type)) continue;
|
|
10754
|
+
const route = resolveRoute(file.path, frontmatter.type ?? "", options);
|
|
10755
|
+
if (route === "ignore") continue;
|
|
10756
|
+
const resolvedId = typeof frontmatter.id === "string" && frontmatter.id ? frontmatter.id : basenameMd(file.path);
|
|
10757
|
+
const { body: storedBody, relatedLinks } = splitRelatedSection(body);
|
|
10758
|
+
const edgeLinks = isProfile1 || isLegacyV1 ? relatedLinks : [...relatedLinks, ...extractMarkdownLinks(storedBody)];
|
|
10759
|
+
const usesV1StatusRule = isProfile1 || isLegacyV1 || profile === void 0 && okfVersion === void 0;
|
|
10760
|
+
if (route === "fact") {
|
|
10761
|
+
facts.push(
|
|
10762
|
+
frontmatterToFact(entityId, resolvedId, frontmatter, storedBody, now, droppedPointerValues, isV3Bundle, {
|
|
10763
|
+
raw: unparsedRaw,
|
|
10764
|
+
issues
|
|
10765
|
+
}, file.path, droppedValues, bundleRootPathToId)
|
|
10766
|
+
);
|
|
10767
|
+
} else {
|
|
10768
|
+
tasks.push(
|
|
10769
|
+
frontmatterToTask(entityId, resolvedId, frontmatter, now, usesV1StatusRule, {
|
|
10770
|
+
raw: unparsedRaw,
|
|
10771
|
+
issues
|
|
10772
|
+
}, file.path, droppedValues)
|
|
10773
|
+
);
|
|
10774
|
+
}
|
|
10775
|
+
const seenEdges = /* @__PURE__ */ new Set();
|
|
10776
|
+
extractEdgesFromLinks(
|
|
10777
|
+
file.path,
|
|
10778
|
+
resolvedId,
|
|
10779
|
+
edgeLinks,
|
|
10780
|
+
pathToResolvedId,
|
|
10781
|
+
bundleRootPathToId,
|
|
10782
|
+
entityId,
|
|
10783
|
+
now,
|
|
10784
|
+
seenEdges,
|
|
10785
|
+
edges,
|
|
10786
|
+
isV3Bundle
|
|
10787
|
+
);
|
|
10788
|
+
}
|
|
10789
|
+
const events = [];
|
|
10790
|
+
if (logContent != null) {
|
|
10791
|
+
const pending = [];
|
|
10792
|
+
const logPath = logMdPath ?? `entities/${entityId}/log.md`;
|
|
10793
|
+
for (const entry of parseLogMd(logContent)) {
|
|
10794
|
+
const { text, eventId } = parseEventIdComment(entry.text);
|
|
10795
|
+
const parsed = parseLogEntryText(text);
|
|
10796
|
+
if (!parsed) continue;
|
|
10797
|
+
let related_entry_id = null;
|
|
10798
|
+
if (parsed.linkPath) {
|
|
10799
|
+
const strippedLink = stripLinkSuffix(decodeLinkPath(parsed.linkPath));
|
|
10800
|
+
let targetPath;
|
|
10801
|
+
if (isV3Bundle) {
|
|
10802
|
+
targetPath = strictTargetPath(logPath, strippedLink);
|
|
10803
|
+
} else if (strippedLink.startsWith("/") && bundleRootPathToId.has(strippedLink.slice(1))) {
|
|
10804
|
+
targetPath = strippedLink.slice(1);
|
|
10805
|
+
} else {
|
|
10806
|
+
targetPath = resolveRelativePath(logPath, strippedLink);
|
|
10807
|
+
}
|
|
10808
|
+
if (!isStructuralPath(targetPath) && targetPath.includes("/facts/")) {
|
|
10809
|
+
related_entry_id = isV3Bundle ? bundleRootPathToId.get(targetPath) ?? null : lookupResolvedId(pathToResolvedId, targetPath) ?? null;
|
|
10810
|
+
}
|
|
10811
|
+
}
|
|
10812
|
+
const created_at = (/* @__PURE__ */ new Date(`${entry.date}T00:00:00.000Z`)).getTime();
|
|
10813
|
+
if (!Number.isFinite(created_at)) continue;
|
|
10814
|
+
if (eventId === void 0) pending.push({ index: events.length, date: entry.date });
|
|
10815
|
+
events.push({
|
|
10816
|
+
id: eventId ?? "",
|
|
10817
|
+
entity_id: entityId,
|
|
10818
|
+
event_type: parsed.event_type,
|
|
10819
|
+
summary: parsed.summary,
|
|
10820
|
+
related_entry_id,
|
|
10821
|
+
created_at
|
|
10822
|
+
});
|
|
10823
|
+
}
|
|
10824
|
+
const taken = new Set(events.map((e) => e.id).filter((id) => id !== ""));
|
|
10825
|
+
const nextOccurrence = /* @__PURE__ */ new Map();
|
|
10826
|
+
for (const { index, date } of pending) {
|
|
10827
|
+
const e = events[index];
|
|
10828
|
+
const key = JSON.stringify([date, e.event_type, replaceLoneSurrogates(e.summary)]);
|
|
10829
|
+
let occurrence = nextOccurrence.get(key) ?? 0;
|
|
10830
|
+
const derive = createEventIdDeriver({ entityId, date, eventType: e.event_type, summary: e.summary });
|
|
10831
|
+
let id = derive(occurrence);
|
|
10832
|
+
while (taken.has(id)) {
|
|
10833
|
+
occurrence += 1;
|
|
10834
|
+
id = derive(occurrence);
|
|
10835
|
+
}
|
|
10836
|
+
taken.add(id);
|
|
10837
|
+
nextOccurrence.set(key, occurrence + 1);
|
|
10838
|
+
e.id = id;
|
|
10839
|
+
}
|
|
10840
|
+
}
|
|
10841
|
+
const okfParseReport = {};
|
|
10842
|
+
if (skippedFiles.length > 0) {
|
|
10843
|
+
okfParseReport.skippedFiles = skippedFiles.slice(0, SKIPPED_FILES_CAP);
|
|
10844
|
+
if (skippedFiles.length > SKIPPED_FILES_CAP) {
|
|
10845
|
+
okfParseReport.skippedFilesOmitted = skippedFiles.length - SKIPPED_FILES_CAP;
|
|
10846
|
+
}
|
|
10847
|
+
}
|
|
10848
|
+
if (droppedValues.length > 0) okfParseReport.droppedValues = droppedValues;
|
|
10849
|
+
return {
|
|
10850
|
+
generatedAt: now,
|
|
10851
|
+
entities: {
|
|
10852
|
+
// §B7: the root-index metadata record (A5) rides the entity object
|
|
10853
|
+
// beside `summary`, so the exportDump/importDump JSON round-trip and
|
|
10854
|
+
// the §B7 `{prefix}meta` persistence carry it. Undefined when the
|
|
10855
|
+
// bundle has no root index; `{}` when it has one without extra keys.
|
|
10856
|
+
[entityId]: {
|
|
10857
|
+
facts,
|
|
10858
|
+
tasks,
|
|
10859
|
+
events,
|
|
10860
|
+
edges,
|
|
10861
|
+
summary: entitySummary,
|
|
10862
|
+
bundleMetadata: profileMeta.metadata
|
|
10863
|
+
}
|
|
10864
|
+
},
|
|
10865
|
+
...droppedPointerValues.length > 0 ? { dropped_pointer_values: droppedPointerValues } : {},
|
|
10866
|
+
...okfParseReport.skippedFiles || okfParseReport.droppedValues ? { okf_parse_report: okfParseReport } : {}
|
|
10867
|
+
};
|
|
10868
|
+
}
|
|
10869
|
+
|
|
10050
10870
|
// src/utils/passageCutter.ts
|
|
10051
10871
|
var MAX_PASSAGE_UNITS = 12e3;
|
|
10052
10872
|
var WHITESPACE = /\s/;
|
|
@@ -10442,58 +11262,46 @@ var SourceStoreService = class {
|
|
|
10442
11262
|
}));
|
|
10443
11263
|
}
|
|
10444
11264
|
};
|
|
10445
|
-
|
|
10446
|
-
|
|
10447
|
-
|
|
10448
|
-
|
|
10449
|
-
return
|
|
10450
|
-
}
|
|
10451
|
-
function
|
|
10452
|
-
|
|
10453
|
-
|
|
10454
|
-
|
|
10455
|
-
const keys = Object.keys(
|
|
10456
|
-
if (keys
|
|
10457
|
-
|
|
10458
|
-
|
|
10459
|
-
|
|
10460
|
-
|
|
10461
|
-
if (
|
|
10462
|
-
|
|
10463
|
-
const
|
|
10464
|
-
const
|
|
10465
|
-
|
|
10466
|
-
|
|
10467
|
-
|
|
10468
|
-
|
|
10469
|
-
|
|
10470
|
-
|
|
10471
|
-
|
|
10472
|
-
|
|
10473
|
-
|
|
10474
|
-
|
|
10475
|
-
|
|
10476
|
-
position: o["position"] ?? null
|
|
10477
|
-
};
|
|
10478
|
-
if (normalized.event_id === null && normalized.ref === null && normalized.quote === null && normalized.position === null) {
|
|
10479
|
-
return null;
|
|
11265
|
+
var OKF_RAW_SLOT = "x-llm-wiki-raw";
|
|
11266
|
+
function matchRawBlockKeyText(line) {
|
|
11267
|
+
const keyMatch = /^(?:"(?:\\.|[^"\\])*"|'(?:''|[^'])*'|[^:]+)/.exec(line);
|
|
11268
|
+
if (!keyMatch || keyMatch[0].length === 0 || line[keyMatch[0].length] !== ":") return null;
|
|
11269
|
+
return keyMatch[0];
|
|
11270
|
+
}
|
|
11271
|
+
function probeParseKey(keyText) {
|
|
11272
|
+
const parsed = parseFrontmatter(`---
|
|
11273
|
+
${keyText}: __probe__
|
|
11274
|
+
---`);
|
|
11275
|
+
const keys = Object.keys(parsed.frontmatter);
|
|
11276
|
+
if (keys[0] !== "type") return keys[0] ?? null;
|
|
11277
|
+
return parsed.frontmatter["type"] === "__probe__" ? "type" : null;
|
|
11278
|
+
}
|
|
11279
|
+
function isValidRawBlockEntry(key, lines, mappedKeys) {
|
|
11280
|
+
if (mappedKeys.has(key) || key === OKF_RAW_SLOT) return false;
|
|
11281
|
+
if (lines.includes("\r")) return false;
|
|
11282
|
+
const allLines = lines.split(/\r?\n/);
|
|
11283
|
+
const first = allLines[0] ?? "";
|
|
11284
|
+
const keyText = matchRawBlockKeyText(first);
|
|
11285
|
+
if (keyText === null || probeParseKey(keyText) !== key) return false;
|
|
11286
|
+
const afterColon = first.slice(keyText.length + 1);
|
|
11287
|
+
const trimmedAfter = afterColon.trim();
|
|
11288
|
+
const blockOpening = trimmedAfter === "" || /^[ \t]/.test(afterColon) && trimmedAfter.startsWith("#");
|
|
11289
|
+
for (const line of allLines.slice(1)) {
|
|
11290
|
+
const trimmed = line.trim();
|
|
11291
|
+
if (trimmed === "---") return false;
|
|
11292
|
+
if (/^[ \t]*#/.test(line)) continue;
|
|
11293
|
+
if (line.trim() === "" || /^[ \t]/.test(line)) continue;
|
|
11294
|
+
if (blockOpening && /^-\s/.test(line)) continue;
|
|
11295
|
+
return false;
|
|
10480
11296
|
}
|
|
10481
|
-
return normalized;
|
|
10482
|
-
}
|
|
10483
|
-
function parseStoredSourcePointer(raw) {
|
|
10484
|
-
if (raw === null || raw === void 0) return null;
|
|
10485
|
-
if (typeof raw !== "string") return null;
|
|
10486
|
-
let parsed;
|
|
10487
11297
|
try {
|
|
10488
|
-
|
|
11298
|
+
const { issues } = parseFrontmatter(`---
|
|
11299
|
+
${lines}
|
|
11300
|
+
---`);
|
|
11301
|
+
return !issues.some((issue) => issue.reason === "anchor_or_alias");
|
|
10489
11302
|
} catch {
|
|
10490
|
-
return
|
|
11303
|
+
return false;
|
|
10491
11304
|
}
|
|
10492
|
-
const v = validateSourcePointerValue(parsed);
|
|
10493
|
-
return v === void 0 ? null : v;
|
|
10494
|
-
}
|
|
10495
|
-
function serializeSourcePointer(p) {
|
|
10496
|
-
return p ? JSON.stringify(p) : null;
|
|
10497
11305
|
}
|
|
10498
11306
|
|
|
10499
11307
|
// src/services/importEventStamps.ts
|
|
@@ -10557,6 +11365,224 @@ function planEventStamps(events, ctx) {
|
|
|
10557
11365
|
var MAX_EMBEDDING_BLOB_BYTES = 32 * 1024;
|
|
10558
11366
|
var IMPORT_TITLE_MAX = 500;
|
|
10559
11367
|
var IMPORT_BODY_MAX = 8e3;
|
|
11368
|
+
var OKF_EXTRA_MAX_CHARS = 2 * IMPORT_BODY_MAX;
|
|
11369
|
+
var OKF_GENERATED_SLOT = "generated";
|
|
11370
|
+
var BUNDLE_METADATA_OWNED_KEYS = ["okf_version", "profile"];
|
|
11371
|
+
function isStorableScalar(value) {
|
|
11372
|
+
return typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value) || value === null;
|
|
11373
|
+
}
|
|
11374
|
+
function isSerializableWithinBound(value, depth) {
|
|
11375
|
+
if (isStorableScalar(value)) return true;
|
|
11376
|
+
if (Array.isArray(value)) {
|
|
11377
|
+
for (const item of value) {
|
|
11378
|
+
if (isStorableScalar(item)) continue;
|
|
11379
|
+
if (Array.isArray(item)) {
|
|
11380
|
+
if (depth >= 1) return false;
|
|
11381
|
+
if (!isSerializableWithinBound(item, depth + 1)) return false;
|
|
11382
|
+
} else if (typeof item === "object") {
|
|
11383
|
+
if (!isSerializableWithinBound(item, depth)) return false;
|
|
11384
|
+
} else {
|
|
11385
|
+
return false;
|
|
11386
|
+
}
|
|
11387
|
+
}
|
|
11388
|
+
return true;
|
|
11389
|
+
}
|
|
11390
|
+
if (value !== null && typeof value === "object") {
|
|
11391
|
+
for (const member of Object.values(value)) {
|
|
11392
|
+
if (member === void 0) continue;
|
|
11393
|
+
if (isStorableScalar(member)) continue;
|
|
11394
|
+
if (Array.isArray(member) || typeof member === "object") {
|
|
11395
|
+
if (depth >= 1) return false;
|
|
11396
|
+
if (!isSerializableWithinBound(member, depth + 1)) return false;
|
|
11397
|
+
} else {
|
|
11398
|
+
return false;
|
|
11399
|
+
}
|
|
11400
|
+
}
|
|
11401
|
+
return true;
|
|
11402
|
+
}
|
|
11403
|
+
return false;
|
|
11404
|
+
}
|
|
11405
|
+
function plainObjectOrNull(value) {
|
|
11406
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) return null;
|
|
11407
|
+
return value;
|
|
11408
|
+
}
|
|
11409
|
+
function sanitizeRawSlot(value, mappedKeys, reasons) {
|
|
11410
|
+
const slot = plainObjectOrNull(value);
|
|
11411
|
+
if (slot === null) {
|
|
11412
|
+
reasons.push("not_object");
|
|
11413
|
+
return { ok: false };
|
|
11414
|
+
}
|
|
11415
|
+
const clean = {};
|
|
11416
|
+
for (const [entryKey, entryLines] of Object.entries(slot)) {
|
|
11417
|
+
if (entryKey === "__proto__") {
|
|
11418
|
+
reasons.push("raw_block_invalid");
|
|
11419
|
+
continue;
|
|
11420
|
+
}
|
|
11421
|
+
if (typeof entryLines !== "string") {
|
|
11422
|
+
reasons.push("not_object");
|
|
11423
|
+
return { ok: false };
|
|
11424
|
+
}
|
|
11425
|
+
if (entryLines.length > OKF_EXTRA_MAX_CHARS) {
|
|
11426
|
+
reasons.push("raw_block_invalid");
|
|
11427
|
+
continue;
|
|
11428
|
+
}
|
|
11429
|
+
if (isValidRawBlockEntry(entryKey, entryLines, mappedKeys)) clean[entryKey] = entryLines;
|
|
11430
|
+
else reasons.push("raw_block_invalid");
|
|
11431
|
+
}
|
|
11432
|
+
return { ok: true, slot: clean };
|
|
11433
|
+
}
|
|
11434
|
+
function validateOkfExtra(raw, mappedKeys) {
|
|
11435
|
+
if (raw === void 0) return { value: null, reasons: [] };
|
|
11436
|
+
const input = plainObjectOrNull(raw);
|
|
11437
|
+
if (input === null) return { value: null, reasons: ["not_object"] };
|
|
11438
|
+
const mapped = new Set(mappedKeys);
|
|
11439
|
+
const out = {};
|
|
11440
|
+
const reasons = [];
|
|
11441
|
+
for (const [key, value] of Object.entries(input)) {
|
|
11442
|
+
if (key === OKF_RAW_SLOT) {
|
|
11443
|
+
const slot = sanitizeRawSlot(value, mapped, reasons);
|
|
11444
|
+
if (!slot.ok) return { value: null, reasons };
|
|
11445
|
+
if (slot.slot && Object.keys(slot.slot).length > 0) out[OKF_RAW_SLOT] = slot.slot;
|
|
11446
|
+
continue;
|
|
11447
|
+
}
|
|
11448
|
+
if (key === OKF_GENERATED_SLOT) {
|
|
11449
|
+
const plain = plainObjectOrNull(value);
|
|
11450
|
+
if (plain === null || Object.prototype.hasOwnProperty.call(plain, "__proto__")) {
|
|
11451
|
+
reasons.push("not_object");
|
|
11452
|
+
return { value: null, reasons };
|
|
11453
|
+
}
|
|
11454
|
+
out[key] = value;
|
|
11455
|
+
continue;
|
|
11456
|
+
}
|
|
11457
|
+
if (mapped.has(key)) continue;
|
|
11458
|
+
if (key === "__proto__") {
|
|
11459
|
+
reasons.push("raw_block_invalid");
|
|
11460
|
+
continue;
|
|
11461
|
+
}
|
|
11462
|
+
out[key] = value;
|
|
11463
|
+
}
|
|
11464
|
+
if (Object.keys(out).length === 0) return { value: null, reasons };
|
|
11465
|
+
const slotRecord = out[OKF_RAW_SLOT];
|
|
11466
|
+
if (slotRecord) {
|
|
11467
|
+
for (const rk of Object.keys(slotRecord)) {
|
|
11468
|
+
if (rk !== OKF_RAW_SLOT && Object.prototype.hasOwnProperty.call(out, rk)) {
|
|
11469
|
+
delete slotRecord[rk];
|
|
11470
|
+
reasons.push("raw_block_invalid");
|
|
11471
|
+
}
|
|
11472
|
+
}
|
|
11473
|
+
if (Object.keys(slotRecord).length === 0) delete out[OKF_RAW_SLOT];
|
|
11474
|
+
}
|
|
11475
|
+
if (!Object.values(out).every((value) => isSerializableWithinBound(value, 0))) {
|
|
11476
|
+
return { value: null, reasons: [...reasons, "not_serializable"] };
|
|
11477
|
+
}
|
|
11478
|
+
let serialized;
|
|
11479
|
+
try {
|
|
11480
|
+
serialized = JSON.stringify(out) ?? "";
|
|
11481
|
+
} catch {
|
|
11482
|
+
return { value: null, reasons: [...reasons, "not_serializable"] };
|
|
11483
|
+
}
|
|
11484
|
+
if (serialized.length > OKF_EXTRA_MAX_CHARS) return { value: null, reasons: [...reasons, "too_large"] };
|
|
11485
|
+
return { value: out, reasons };
|
|
11486
|
+
}
|
|
11487
|
+
function validateBundleMetadata(raw) {
|
|
11488
|
+
if (raw === void 0) return { value: void 0, reasons: [] };
|
|
11489
|
+
const input = plainObjectOrNull(raw);
|
|
11490
|
+
if (input === null) return { value: void 0, reasons: ["not_object"] };
|
|
11491
|
+
const owned = new Set(BUNDLE_METADATA_OWNED_KEYS);
|
|
11492
|
+
const out = {};
|
|
11493
|
+
const reasons = [];
|
|
11494
|
+
for (const [key, value] of Object.entries(input)) {
|
|
11495
|
+
if (owned.has(key) || key === "__proto__") continue;
|
|
11496
|
+
if (key === OKF_RAW_SLOT) {
|
|
11497
|
+
const slot = sanitizeRawSlot(value, owned, reasons);
|
|
11498
|
+
if (!slot.ok) return { value: void 0, reasons };
|
|
11499
|
+
if (slot.slot && Object.keys(slot.slot).length > 0) out[OKF_RAW_SLOT] = slot.slot;
|
|
11500
|
+
continue;
|
|
11501
|
+
}
|
|
11502
|
+
out[key] = value;
|
|
11503
|
+
}
|
|
11504
|
+
const metaSlot = out[OKF_RAW_SLOT];
|
|
11505
|
+
if (metaSlot) {
|
|
11506
|
+
for (const rk of Object.keys(metaSlot)) {
|
|
11507
|
+
if (rk !== OKF_RAW_SLOT && Object.prototype.hasOwnProperty.call(out, rk)) {
|
|
11508
|
+
delete metaSlot[rk];
|
|
11509
|
+
reasons.push("raw_block_invalid");
|
|
11510
|
+
}
|
|
11511
|
+
}
|
|
11512
|
+
if (Object.keys(metaSlot).length === 0) delete out[OKF_RAW_SLOT];
|
|
11513
|
+
}
|
|
11514
|
+
if (!Object.values(out).every((value) => isSerializableWithinBound(value, 0))) {
|
|
11515
|
+
return { value: void 0, reasons: [...reasons, "not_serializable"] };
|
|
11516
|
+
}
|
|
11517
|
+
let serialized;
|
|
11518
|
+
try {
|
|
11519
|
+
serialized = JSON.stringify(out) ?? "";
|
|
11520
|
+
} catch {
|
|
11521
|
+
return { value: void 0, reasons: [...reasons, "not_serializable"] };
|
|
11522
|
+
}
|
|
11523
|
+
if (serialized.length > OKF_EXTRA_MAX_CHARS) return { value: void 0, reasons: [...reasons, "too_large"] };
|
|
11524
|
+
return { value: out, reasons };
|
|
11525
|
+
}
|
|
11526
|
+
function sanitizeStaleAfterRaw(raw, staleAfter) {
|
|
11527
|
+
if (raw === void 0 || raw === null) return null;
|
|
11528
|
+
if (typeof raw === "string" && raw.trim() === "") return null;
|
|
11529
|
+
if (typeof staleAfter === "number" && Number.isFinite(staleAfter)) return null;
|
|
11530
|
+
let text;
|
|
11531
|
+
if (typeof raw === "string") {
|
|
11532
|
+
text = raw;
|
|
11533
|
+
} else if (typeof raw === "number" || typeof raw === "boolean" || typeof raw === "bigint") {
|
|
11534
|
+
text = String(raw);
|
|
11535
|
+
} else {
|
|
11536
|
+
try {
|
|
11537
|
+
const json = JSON.stringify(raw);
|
|
11538
|
+
text = json === void 0 ? String(raw) : json;
|
|
11539
|
+
} catch {
|
|
11540
|
+
text = String(raw);
|
|
11541
|
+
}
|
|
11542
|
+
}
|
|
11543
|
+
let out = text;
|
|
11544
|
+
if (text.length > IMPORT_TITLE_MAX) {
|
|
11545
|
+
out = text.slice(0, IMPORT_TITLE_MAX);
|
|
11546
|
+
while (out.length > 0 && parseOkfTimestamp(out) !== null) out = out.slice(0, -1);
|
|
11547
|
+
}
|
|
11548
|
+
return out;
|
|
11549
|
+
}
|
|
11550
|
+
function sanitizeStaleAfterPair(raw, staleAfter) {
|
|
11551
|
+
if (typeof staleAfter === "number" && Number.isFinite(staleAfter)) {
|
|
11552
|
+
return { stale_after: staleAfter, stale_after_raw: null };
|
|
11553
|
+
}
|
|
11554
|
+
if (typeof staleAfter === "string") {
|
|
11555
|
+
const parsed = parseOkfTimestamp(staleAfter);
|
|
11556
|
+
if (parsed !== null) return { stale_after: parsed, stale_after_raw: null };
|
|
11557
|
+
const rawText = sanitizeStaleAfterRaw(raw, void 0);
|
|
11558
|
+
if (rawText !== null) return { stale_after: null, stale_after_raw: rawText };
|
|
11559
|
+
return { stale_after: null, stale_after_raw: sanitizeStaleAfterRaw(staleAfter, void 0) };
|
|
11560
|
+
}
|
|
11561
|
+
if (typeof raw === "string" && raw.trim() !== "") {
|
|
11562
|
+
const parsed = parseOkfTimestamp(raw);
|
|
11563
|
+
if (parsed !== null) return { stale_after: parsed, stale_after_raw: null };
|
|
11564
|
+
}
|
|
11565
|
+
if (Array.isArray(staleAfter) && staleAfter.length === 0) {
|
|
11566
|
+
return { stale_after: null, stale_after_raw: sanitizeStaleAfterRaw(raw, staleAfter) };
|
|
11567
|
+
}
|
|
11568
|
+
if (staleAfter !== void 0 && staleAfter !== null) {
|
|
11569
|
+
const fallback = sanitizeStaleAfterRaw(staleAfter, void 0);
|
|
11570
|
+
if (fallback !== null) return { stale_after: null, stale_after_raw: fallback };
|
|
11571
|
+
}
|
|
11572
|
+
return { stale_after: null, stale_after_raw: sanitizeStaleAfterRaw(raw, staleAfter) };
|
|
11573
|
+
}
|
|
11574
|
+
function sanitizeLifecycleStatus(raw) {
|
|
11575
|
+
const clipToBound = (s) => s.length > IMPORT_TITLE_MAX ? s.slice(0, IMPORT_TITLE_MAX) : s;
|
|
11576
|
+
if (raw === void 0 || raw === null || typeof raw === "string" && raw.trim() === "") return "stable";
|
|
11577
|
+
if (typeof raw === "string") return clipToBound(raw);
|
|
11578
|
+
if (typeof raw === "number" || typeof raw === "boolean" || typeof raw === "bigint") return clipToBound(String(raw));
|
|
11579
|
+
try {
|
|
11580
|
+
const json = JSON.stringify(raw);
|
|
11581
|
+
if (json !== void 0) return clipToBound(json);
|
|
11582
|
+
} catch {
|
|
11583
|
+
}
|
|
11584
|
+
return clipToBound(String(raw));
|
|
11585
|
+
}
|
|
10560
11586
|
var ImportExportService = class {
|
|
10561
11587
|
constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}, vectorRemoval, prefix) {
|
|
10562
11588
|
this.db = db;
|
|
@@ -10702,12 +11728,15 @@ var ImportExportService = class {
|
|
|
10702
11728
|
async getFullBundle(entityId, opts) {
|
|
10703
11729
|
const incl = opts?.includeForgotten ? { includeDeleted: true } : void 0;
|
|
10704
11730
|
const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);
|
|
10705
|
-
const [factsRaw, tasks, events, edges, summaryValue] = await Promise.all([
|
|
11731
|
+
const [factsRaw, tasks, events, edges, summaryValue, bundleMetadataValue] = await Promise.all([
|
|
10706
11732
|
opts?.includeBlobs ? this.entryRepo.findAllByEntityIdWithBlobs(entityId, void 0, incl) : this.entryRepo.findAllByEntityId(entityId, void 0, incl),
|
|
10707
11733
|
this.taskRepo.findAllByEntityId(entityId, void 0, incl),
|
|
10708
11734
|
this.eventRepo.getByEntityId(entityId, opts?.maxEvents, incl),
|
|
10709
11735
|
this.edgeRepo.getByEntityId(entityId),
|
|
10710
|
-
this.metadataRepo.getMeta(entitySummaryMetaKey(entityId))
|
|
11736
|
+
this.metadataRepo.getMeta(entitySummaryMetaKey(entityId)),
|
|
11737
|
+
// §B7: the stored bundle-metadata record rides the entity object back
|
|
11738
|
+
// out, beside the summary.
|
|
11739
|
+
this.metadataRepo.getMeta(bundleMetadataMetaKey(entityId))
|
|
10711
11740
|
]);
|
|
10712
11741
|
const facts = factsRaw.map((f) => {
|
|
10713
11742
|
const {
|
|
@@ -10726,12 +11755,38 @@ var ImportExportService = class {
|
|
|
10726
11755
|
tags: typeof factBase.tags === "string" ? JSON.parse(factBase.tags) : factBase.tags
|
|
10727
11756
|
};
|
|
10728
11757
|
});
|
|
11758
|
+
let bundleMetadata;
|
|
11759
|
+
if (bundleMetadataValue != null) {
|
|
11760
|
+
try {
|
|
11761
|
+
const parsed = JSON.parse(bundleMetadataValue);
|
|
11762
|
+
bundleMetadata = parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
|
|
11763
|
+
if (bundleMetadata === void 0) {
|
|
11764
|
+
emitDiagnostic(this.options, {
|
|
11765
|
+
code: "okf_bundle_metadata_invalid",
|
|
11766
|
+
operation: "exportDump",
|
|
11767
|
+
trigger: "call",
|
|
11768
|
+
entityId,
|
|
11769
|
+
detail: {}
|
|
11770
|
+
});
|
|
11771
|
+
}
|
|
11772
|
+
} catch {
|
|
11773
|
+
bundleMetadata = void 0;
|
|
11774
|
+
emitDiagnostic(this.options, {
|
|
11775
|
+
code: "okf_bundle_metadata_invalid",
|
|
11776
|
+
operation: "exportDump",
|
|
11777
|
+
trigger: "call",
|
|
11778
|
+
entityId,
|
|
11779
|
+
detail: {}
|
|
11780
|
+
});
|
|
11781
|
+
}
|
|
11782
|
+
}
|
|
10729
11783
|
return {
|
|
10730
11784
|
facts,
|
|
10731
11785
|
tasks,
|
|
10732
11786
|
events,
|
|
10733
11787
|
edges,
|
|
10734
11788
|
...summaryValue != null ? { summary: summaryValue } : {},
|
|
11789
|
+
...bundleMetadata != null ? { bundleMetadata } : {},
|
|
10735
11790
|
...wm ? { librarian_watermark: wm } : {}
|
|
10736
11791
|
};
|
|
10737
11792
|
}
|
|
@@ -10739,6 +11794,21 @@ var ImportExportService = class {
|
|
|
10739
11794
|
async doImportEntity(entityId, bundle, merge) {
|
|
10740
11795
|
const skippedSources = [];
|
|
10741
11796
|
const refusalDiagnostics = [];
|
|
11797
|
+
let carriedBundleMetadata;
|
|
11798
|
+
const rawBundleMetadata = bundle.bundleMetadata;
|
|
11799
|
+
if (rawBundleMetadata !== void 0) {
|
|
11800
|
+
const meta = validateBundleMetadata(rawBundleMetadata);
|
|
11801
|
+
for (const reason of meta.reasons) {
|
|
11802
|
+
refusalDiagnostics.push({
|
|
11803
|
+
code: "okf_bundle_metadata_invalid",
|
|
11804
|
+
operation: "importDump",
|
|
11805
|
+
trigger: "call",
|
|
11806
|
+
entityId,
|
|
11807
|
+
detail: { reason }
|
|
11808
|
+
});
|
|
11809
|
+
}
|
|
11810
|
+
carriedBundleMetadata = meta.value;
|
|
11811
|
+
}
|
|
10742
11812
|
const upsertedFactIds = /* @__PURE__ */ new Set();
|
|
10743
11813
|
const liveEmbedFactIds = /* @__PURE__ */ new Set();
|
|
10744
11814
|
const upsertedDeletedFactIds = /* @__PURE__ */ new Set();
|
|
@@ -10771,6 +11841,15 @@ var ImportExportService = class {
|
|
|
10771
11841
|
} else if (!merge) {
|
|
10772
11842
|
await this.metadataRepo.deleteMeta(entitySummaryMetaKey(entityId), tx);
|
|
10773
11843
|
}
|
|
11844
|
+
if (carriedBundleMetadata !== void 0) {
|
|
11845
|
+
await this.metadataRepo.setMeta(
|
|
11846
|
+
bundleMetadataMetaKey(entityId),
|
|
11847
|
+
JSON.stringify(carriedBundleMetadata),
|
|
11848
|
+
tx
|
|
11849
|
+
);
|
|
11850
|
+
} else if (!merge) {
|
|
11851
|
+
await this.metadataRepo.deleteMeta(bundleMetadataMetaKey(entityId), tx);
|
|
11852
|
+
}
|
|
10774
11853
|
const wipedByThisImport = new Set(softDeletedFactIds);
|
|
10775
11854
|
const wipedTasksByThisImport = new Set(softDeletedTaskIds);
|
|
10776
11855
|
const factIds = bundle.facts.map((fact) => fact.id);
|
|
@@ -10893,6 +11972,17 @@ var ImportExportService = class {
|
|
|
10893
11972
|
});
|
|
10894
11973
|
}
|
|
10895
11974
|
const derivedEvents = derivedValidated ?? null;
|
|
11975
|
+
const factExtra = validateOkfExtra(fact.okf_extra, FACT_MAPPED_KEYS);
|
|
11976
|
+
for (const reason of factExtra.reasons) {
|
|
11977
|
+
refusalDiagnostics.push({
|
|
11978
|
+
code: "okf_extra_invalid",
|
|
11979
|
+
operation: "importDump",
|
|
11980
|
+
trigger: "call",
|
|
11981
|
+
entityId,
|
|
11982
|
+
detail: { factId: fact.id, reason }
|
|
11983
|
+
});
|
|
11984
|
+
}
|
|
11985
|
+
const stalePair = sanitizeStaleAfterPair(fact.stale_after_raw, fact.stale_after);
|
|
10896
11986
|
const factObj = {
|
|
10897
11987
|
id: fact.id,
|
|
10898
11988
|
entity_id: entityId,
|
|
@@ -10912,14 +12002,20 @@ var ImportExportService = class {
|
|
|
10912
12002
|
okf_type: fact.okf_type ?? null,
|
|
10913
12003
|
source_pointer: sourcePointer,
|
|
10914
12004
|
...derivedEvents ? { derived_events: derivedEvents } : {},
|
|
10915
|
-
// OKF v0.2 —
|
|
10916
|
-
//
|
|
10917
|
-
|
|
10918
|
-
|
|
12005
|
+
// OKF v0.2 — lifecycle follows §B4 (empty or null is `stable`; a
|
|
12006
|
+
// non-string scalar stores its string form, a list or mapping its
|
|
12007
|
+
// compact JSON text). The other v0.2 fields are forwarded as-is;
|
|
12008
|
+
// parseOkfBundle / the caller is responsible for populating those
|
|
12009
|
+
// per spec.
|
|
12010
|
+
lifecycle_status: sanitizeLifecycleStatus(fact.lifecycle_status),
|
|
12011
|
+
stale_after: stalePair.stale_after,
|
|
10919
12012
|
generated_by: fact.generated_by ?? null,
|
|
10920
12013
|
okf_sources: fact.okf_sources ?? [],
|
|
10921
12014
|
okf_verified: fact.okf_verified ?? [],
|
|
10922
12015
|
okf_usage_window: fact.okf_usage_window ?? null,
|
|
12016
|
+
// OKF v0.3 (§B12) — forwarded through the checks above.
|
|
12017
|
+
okf_extra: factExtra.value,
|
|
12018
|
+
stale_after_raw: stalePair.stale_after_raw,
|
|
10923
12019
|
// last_verified_at/_by are DERIVED mirrors of `okf_verified` per spec
|
|
10924
12020
|
// §5.3. Recomputing here (instead of trusting the payload field) closes
|
|
10925
12021
|
// the invariant that a raw importDump cannot carry a
|
|
@@ -10986,6 +12082,17 @@ var ImportExportService = class {
|
|
|
10986
12082
|
}
|
|
10987
12083
|
if (merge && safeUpdatedAt <= existing.updated_at && task.deleted_at == null) continue;
|
|
10988
12084
|
}
|
|
12085
|
+
const taskExtra = validateOkfExtra(task.okf_extra, TASK_MAPPED_KEYS);
|
|
12086
|
+
for (const reason of taskExtra.reasons) {
|
|
12087
|
+
refusalDiagnostics.push({
|
|
12088
|
+
code: "okf_extra_invalid",
|
|
12089
|
+
operation: "importDump",
|
|
12090
|
+
trigger: "call",
|
|
12091
|
+
entityId,
|
|
12092
|
+
detail: { taskId: task.id, reason }
|
|
12093
|
+
});
|
|
12094
|
+
}
|
|
12095
|
+
const taskStalePair = sanitizeStaleAfterPair(task.stale_after_raw, task.stale_after);
|
|
10989
12096
|
await this.taskRepo.upsertForImport(
|
|
10990
12097
|
{
|
|
10991
12098
|
id: task.id,
|
|
@@ -10998,13 +12105,16 @@ var ImportExportService = class {
|
|
|
10998
12105
|
resolved_at: task.resolved_at,
|
|
10999
12106
|
deleted_at: task.deleted_at,
|
|
11000
12107
|
okf_type: task.okf_type ?? null,
|
|
11001
|
-
// OKF v0.2
|
|
11002
|
-
lifecycle_status: task.lifecycle_status
|
|
11003
|
-
stale_after:
|
|
12108
|
+
// OKF v0.2 — lifecycle follows §B4, as on the fact branch.
|
|
12109
|
+
lifecycle_status: sanitizeLifecycleStatus(task.lifecycle_status),
|
|
12110
|
+
stale_after: taskStalePair.stale_after,
|
|
11004
12111
|
generated_by: task.generated_by ?? null,
|
|
11005
12112
|
okf_sources: task.okf_sources ?? [],
|
|
11006
12113
|
okf_verified: task.okf_verified ?? [],
|
|
11007
12114
|
okf_usage_window: task.okf_usage_window ?? null,
|
|
12115
|
+
// OKF v0.3 (§B12) — forwarded through the checks above.
|
|
12116
|
+
okf_extra: taskExtra.value,
|
|
12117
|
+
stale_after_raw: taskStalePair.stale_after_raw,
|
|
11008
12118
|
// Derived mirrors — see fact branch above; same invariant.
|
|
11009
12119
|
...(() => {
|
|
11010
12120
|
const latest = latestVerified(task.okf_verified ?? [], Date.now());
|
|
@@ -11897,9 +13007,9 @@ var RetrievalService = class {
|
|
|
11897
13007
|
if (maxResults === 0) ; else if (trimmedQuery) {
|
|
11898
13008
|
let usedEmbed = false;
|
|
11899
13009
|
const scoredEntityIds = this._filterScoredEntities(entityIds, sanitizedTierWeights, options?.includeZeroWeightEntities);
|
|
11900
|
-
const
|
|
13010
|
+
const notCurrentIds = excludeDrafts && scoredEntityIds.length > 0 ? await this.entryRepo.findNotCurrentIdsByEntityIds(scoredEntityIds) : EMPTY_ID_SET;
|
|
11901
13011
|
const nonLiveIds = scoredEntityIds.length > 0 ? await this.entryRepo.findNonLiveIdsByEntityIds(scoredEntityIds, liveMode, liveAt) : EMPTY_ID_SET;
|
|
11902
|
-
const excludedIds =
|
|
13012
|
+
const excludedIds = notCurrentIds.size === 0 ? nonLiveIds : nonLiveIds.size === 0 ? notCurrentIds : /* @__PURE__ */ new Set([...notCurrentIds, ...nonLiveIds]);
|
|
11903
13013
|
const excludedPad = excludedIds.size;
|
|
11904
13014
|
const padLimit = (n) => n >= Number.MAX_SAFE_INTEGER ? n : n + excludedPad;
|
|
11905
13015
|
if (scoredEntityIds.length === 0) {
|
|
@@ -12687,6 +13797,6 @@ var WriteService = class {
|
|
|
12687
13797
|
}
|
|
12688
13798
|
};
|
|
12689
13799
|
|
|
12690
|
-
export { BaseRepository, CLASSIFIER_MAX_CHOICES, CURRENT_SCHEMA_VERSION, CheckpointIncompleteError, DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DEFAULT_TYPING_MIN_CONFIDENCE, DiagnosticBuffer, EMBED_CHARS_CEILING, EdgeRepository, EmbeddingService, EraseStepError, 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_ABSTAIN_SENTINEL, ONTOLOGY_BACKFILL_BATCH_SIZE, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_RECHECK_MS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, PromptService, PrunePartialFailureError, RetrievalService, SearchService, SourceStoreService, 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, canEngageIngestTyping, canEngageWriteTyping, chunkText, configureRandomSource, createEntriesDeletedIndex, createEventsForgottenIndex, createLegacySourceTypeIndex, createdAtValue, detectSchemaVersion, drainChunkSql, drainHiSql, edgeTripleAllowed, emitDiagnostic, emptyManifest, entityDrainChunkSql, entityDrainHiSql, entitySummaryMetaKey, extractSqliteCode, factTokenCost, fts5LedgerDropSql, fts5PendingIndexesDdl, fts5TablesDdl, fts5TriggerNames, fts5TriggersDdl, generateId, idDrainChunkSql, idReindexChunkSql, isLiveAt, isReservedAbstainSlug, isRetiredTableName, isUsableDate, isWikiSearchUnavailableError, liveAtSql, nodeTypeReceipts, normalizeSourceHash, normalizeSourceRef, normalizeTitleKey, packFactsByBudget, parseEmbedding, parseJsonArray, parseJsonObject, parseStoredDerivedEvents, parseStoredSourcePointer, passageFtsTablesDdl, passageFtsTriggerNames, passageFtsTriggersDdl, probePendingWork, readRebuildProgress, reanchorRebuildFingerprint, resolveContextBudget, resolveContextBudgetOrThrow, resolveDefaultChunkLength, resolveEdgeDefinitions, resolveEdgesMinConfidence, resolveGrounding, resolveHealScreenMinConfidence, resolveLibrarianStrategy, resolveMaxPromptChars, resolveNodeType, resolveNodeTypeMatch, resolveResolveMinConfidence, resolveSystemOneEdges, resolveSystemOneHealScreen, resolveSystemOneResolve, resolveSystemOneTypeOnIngest, resolveSystemOneTypeOnWrite, resolveSystemOneTyping, resolveTypingMinConfidence, retiredTableName, runSourceRefNormalize, safeSlice, serializeDerivedEvents, serializeSourcePointer, setupDatabase, shouldEmitOntologyReceipt, sweepChunkSql, sweepHiSql, typeSatisfies, validUsage,
|
|
12691
|
-
//# sourceMappingURL=chunk-
|
|
12692
|
-
//# sourceMappingURL=chunk-
|
|
13800
|
+
export { BaseRepository, CLASSIFIER_MAX_CHOICES, CURRENT_SCHEMA_VERSION, CheckpointIncompleteError, DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DEFAULT_TYPING_MIN_CONFIDENCE, DiagnosticBuffer, EMBED_CHARS_CEILING, ENGINE_ACTOR, EdgeRepository, EmbeddingService, EraseStepError, FACT_MAPPED_KEYS, 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_ABSTAIN_SENTINEL, ONTOLOGY_BACKFILL_BATCH_SIZE, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_RECHECK_MS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, PromptService, PrunePartialFailureError, RetrievalService, SearchService, SourceStoreService, TASK_MAPPED_KEYS, 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, canEngageIngestTyping, canEngageWriteTyping, chunkText, configureRandomSource, createEntriesDeletedIndex, createEventsForgottenIndex, createLegacySourceTypeIndex, createdAtValue, detectSchemaVersion, drainChunkSql, drainHiSql, edgeTripleAllowed, emitDiagnostic, emptyManifest, entityDrainChunkSql, entityDrainHiSql, entitySummaryMetaKey, extractSqliteCode, factTokenCost, fts5LedgerDropSql, fts5PendingIndexesDdl, fts5TablesDdl, fts5TriggerNames, fts5TriggersDdl, generateId, idDrainChunkSql, idReindexChunkSql, isLiveAt, isReservedAbstainSlug, isRetiredTableName, isUsableDate, isValidRawBlockEntry, isWikiSearchUnavailableError, liveAtSql, nodeTypeReceipts, normalizeSourceHash, normalizeSourceRef, normalizeTitleKey, packFactsByBudget, parseEmbedding, parseJsonArray, parseJsonObject, parseOkfBundle, parseStoredDerivedEvents, parseStoredSourcePointer, passageFtsTablesDdl, passageFtsTriggerNames, passageFtsTriggersDdl, probePendingWork, readRebuildProgress, reanchorRebuildFingerprint, resolveContextBudget, resolveContextBudgetOrThrow, resolveDefaultChunkLength, resolveEdgeDefinitions, resolveEdgesMinConfidence, resolveGrounding, resolveHealScreenMinConfidence, resolveLibrarianStrategy, resolveMaxPromptChars, resolveNodeType, resolveNodeTypeMatch, resolveResolveMinConfidence, resolveSystemOneEdges, resolveSystemOneHealScreen, resolveSystemOneResolve, resolveSystemOneTypeOnIngest, resolveSystemOneTypeOnWrite, resolveSystemOneTyping, resolveTypingMinConfidence, retiredTableName, runSourceRefNormalize, safeSlice, serializeDerivedEvents, serializeSourcePointer, setupDatabase, shouldEmitOntologyReceipt, sweepChunkSql, sweepHiSql, typeSatisfies, validUsage, validateInlineEdges, validateManifest, warnChangedDefaultsOnce, warnOnce, windowChunkSql, windowHiSql, writeNormalizeStamp, writeRebuildStart };
|
|
13801
|
+
//# sourceMappingURL=chunk-EEVYPJCL.mjs.map
|
|
13802
|
+
//# sourceMappingURL=chunk-EEVYPJCL.mjs.map
|