@equationalapplications/core-llm-wiki 9.20.1 → 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
package/dist/index.js
CHANGED
|
@@ -91,6 +91,7 @@ function resolveDefaultChunkLength(budget) {
|
|
|
91
91
|
// src/utils/engineDefaults.ts
|
|
92
92
|
var DEFAULT_LIBRARIAN_STRATEGY = "ops";
|
|
93
93
|
var DEFAULT_MAINTENANCE_MODE = "deferred";
|
|
94
|
+
var ENGINE_ACTOR = "process:llm-wiki";
|
|
94
95
|
function resolveLibrarianStrategy(config) {
|
|
95
96
|
return config?.librarian?.strategy ?? DEFAULT_LIBRARIAN_STRATEGY;
|
|
96
97
|
}
|
|
@@ -371,6 +372,8 @@ var SEVERITY = {
|
|
|
371
372
|
source_pointer_invalid: "warn",
|
|
372
373
|
source_event_gone: "warn",
|
|
373
374
|
derived_events_invalid: "warn",
|
|
375
|
+
okf_extra_invalid: "warn",
|
|
376
|
+
okf_bundle_metadata_invalid: "warn",
|
|
374
377
|
source_store_source_too_large: "warn",
|
|
375
378
|
source_store_budget_exceeded: "warn",
|
|
376
379
|
source_store_hash_mismatch: "warn",
|
|
@@ -433,6 +436,8 @@ var MESSAGE = {
|
|
|
433
436
|
source_pointer_invalid: "Import met a malformed source pointer value and stored a null pointer.",
|
|
434
437
|
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.",
|
|
435
438
|
derived_events_invalid: "Import met a malformed derived_events value and stored null.",
|
|
439
|
+
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.",
|
|
440
|
+
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.",
|
|
436
441
|
source_store_source_too_large: "A source document exceeded the per-document size cap and was not stored.",
|
|
437
442
|
source_store_budget_exceeded: "Storing a source document would exceed the store UTF-16 code-unit budget and it was not stored.",
|
|
438
443
|
source_store_hash_mismatch: "A source document text did not match its recorded hash and was not stored.",
|
|
@@ -2035,7 +2040,9 @@ async function setupDatabase(db, prefix) {
|
|
|
2035
2040
|
superseded_at INTEGER,
|
|
2036
2041
|
prior_valid_to INTEGER,
|
|
2037
2042
|
source_pointer TEXT,
|
|
2038
|
-
derived_events TEXT
|
|
2043
|
+
derived_events TEXT,
|
|
2044
|
+
stale_after_raw TEXT,
|
|
2045
|
+
okf_extra TEXT
|
|
2039
2046
|
);
|
|
2040
2047
|
|
|
2041
2048
|
CREATE INDEX IF NOT EXISTS ${prefix}entries_entity_idx ON ${prefix}entries(entity_id);
|
|
@@ -2102,7 +2109,9 @@ async function setupDatabase(db, prefix) {
|
|
|
2102
2109
|
last_verified_by TEXT,
|
|
2103
2110
|
okf_sources TEXT,
|
|
2104
2111
|
okf_verified TEXT,
|
|
2105
|
-
okf_usage_window TEXT
|
|
2112
|
+
okf_usage_window TEXT,
|
|
2113
|
+
stale_after_raw TEXT,
|
|
2114
|
+
okf_extra TEXT
|
|
2106
2115
|
);
|
|
2107
2116
|
|
|
2108
2117
|
CREATE INDEX IF NOT EXISTS ${prefix}tasks_entity_idx ON ${prefix}tasks(entity_id, status);
|
|
@@ -2837,6 +2846,25 @@ var MIGRATIONS = [
|
|
|
2837
2846
|
await addEventsForgottenAtColumn(db, prefix);
|
|
2838
2847
|
await createEventsForgottenIndex(db, prefix);
|
|
2839
2848
|
}
|
|
2849
|
+
},
|
|
2850
|
+
{
|
|
2851
|
+
version: 20,
|
|
2852
|
+
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)",
|
|
2853
|
+
run: async (db, prefix) => {
|
|
2854
|
+
for (const table of ["entries", "tasks"]) {
|
|
2855
|
+
const cols = await db.getAllAsync(
|
|
2856
|
+
`PRAGMA table_info(${prefix}${table})`
|
|
2857
|
+
);
|
|
2858
|
+
const existing = new Set(cols.map((c) => c.name));
|
|
2859
|
+
const adds = [
|
|
2860
|
+
["stale_after_raw", `ALTER TABLE ${prefix}${table} ADD COLUMN stale_after_raw TEXT`],
|
|
2861
|
+
["okf_extra", `ALTER TABLE ${prefix}${table} ADD COLUMN okf_extra TEXT`]
|
|
2862
|
+
];
|
|
2863
|
+
for (const [name, sql] of adds) {
|
|
2864
|
+
if (!existing.has(name)) await db.execAsync(sql);
|
|
2865
|
+
}
|
|
2866
|
+
}
|
|
2867
|
+
}
|
|
2840
2868
|
}
|
|
2841
2869
|
];
|
|
2842
2870
|
async function addEventsForgottenAtColumn(db, prefix) {
|
|
@@ -3210,8 +3238,11 @@ function mapRowToFact(row) {
|
|
|
3210
3238
|
const okf_verified = parseJsonArray(row.okf_verified, []);
|
|
3211
3239
|
const now = Date.now();
|
|
3212
3240
|
const staleAfterRaw = row.stale_after != null ? Number(row.stale_after) : null;
|
|
3241
|
+
const staleAfterRawText = row.stale_after_raw != null ? String(row.stale_after_raw) : null;
|
|
3213
3242
|
const sourcePointer = parseStoredSourcePointer(row.source_pointer);
|
|
3214
3243
|
const derivedEvents = parseStoredDerivedEvents(row.derived_events);
|
|
3244
|
+
const generatedAt = row.generated_by != null ? Number(row.updated_at) : null;
|
|
3245
|
+
const okfExtra = parseJsonObject(row.okf_extra);
|
|
3215
3246
|
const mapped = {
|
|
3216
3247
|
id: row.id,
|
|
3217
3248
|
entity_id: row.entity_id,
|
|
@@ -3237,9 +3268,19 @@ function mapRowToFact(row) {
|
|
|
3237
3268
|
okf_usage_window: parseJsonObject(row.okf_usage_window),
|
|
3238
3269
|
last_verified_at: row.last_verified_at != null ? Number(row.last_verified_at) : null,
|
|
3239
3270
|
last_verified_by: row.last_verified_by ?? null,
|
|
3240
|
-
// Spec §2.7 + §5.3: hydrate so read() consumers don't re-call the
|
|
3241
|
-
|
|
3242
|
-
|
|
3271
|
+
// Spec §2.7 + §5.3: hydrate so read() consumers don't re-call the
|
|
3272
|
+
// helpers. §B3 read rule (refinement 37): a stored raw value means the
|
|
3273
|
+
// wire value never parsed, so it is stale — never fresh (§5.5) — even
|
|
3274
|
+
// beside an epoch column the writers would not have paired with it.
|
|
3275
|
+
isStale: staleAfterRawText != null ? true : coreOkf.isStaleAfter(staleAfterRaw, now),
|
|
3276
|
+
trustTier: coreOkf.deriveTrustTier(okf_verified, generatedAt),
|
|
3277
|
+
// v0.3 columns (specs/okf-v03 §F): keys appear only when set — same
|
|
3278
|
+
// rationale as the temporal fields below (existing deep-equality
|
|
3279
|
+
// assertions and host snapshots stay unchanged; NULL = nothing to
|
|
3280
|
+
// preserve). A malformed stored okf_extra reads as absent without
|
|
3281
|
+
// throwing (parseJsonObject).
|
|
3282
|
+
...staleAfterRawText != null ? { stale_after_raw: staleAfterRawText } : {},
|
|
3283
|
+
...okfExtra ? { okf_extra: okfExtra } : {},
|
|
3243
3284
|
// Temporal (spec 2026-09-29 §4, §10.8): keys appear only when set so
|
|
3244
3285
|
// existing deep-equality assertions and host snapshots are unchanged.
|
|
3245
3286
|
...row.valid_from != null ? { valid_from: Number(row.valid_from) } : {},
|
|
@@ -3361,16 +3402,37 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
3361
3402
|
* `WikiGraphNodeOwnershipConflict` (no owner, node ID, or stored content
|
|
3362
3403
|
* is disclosed). Upserts that pass both gates retain existing same-entity
|
|
3363
3404
|
* update + resurrection semantics.
|
|
3405
|
+
*
|
|
3406
|
+
* §C2 content gate (specs/okf-v03): the ON CONFLICT SET computes one
|
|
3407
|
+
* `unchanged` predicate — null-safe `IS` over `title`, `body`, `tags`
|
|
3408
|
+
* (serialized) and `confidence` — and gates `updated_at` and `generated_by`
|
|
3409
|
+
* on it. A byte-identical re-upsert is a true no-op for exactly those two
|
|
3410
|
+
* columns (refinement 27), so a resync or replay can never falsely
|
|
3411
|
+
* de-current a human verification (§5.3); a real content change takes the
|
|
3412
|
+
* new instant and fills a NULL row actor from the caller (COALESCE — a
|
|
3413
|
+
* stored actor, foreign included, is never overwritten). Everything else
|
|
3414
|
+
* in the SET still runs and the outbox event still publishes.
|
|
3415
|
+
* Caller note (review T3-tail2 #2): `deleted_at` is NOT in the compared
|
|
3416
|
+
* set — a tombstone or resurrection over otherwise identical content
|
|
3417
|
+
* keeps the prior `updated_at`. Callers syncing by last-write-wins on
|
|
3418
|
+
* `updated_at` must consult `deleted_at` too (the plan's `hasChanged`
|
|
3419
|
+
* note says the same).
|
|
3420
|
+
* `upsertGraph` replays still advance `updated_at` (refinement 10: it
|
|
3421
|
+
* soft-deletes rows first; the DELETE-then-UPDATE outbox shape is kept).
|
|
3422
|
+
* §C5: pass `at` to share one instant between the write and a same-pass
|
|
3423
|
+
* verification event so the event reads current (`>=`, §A2).
|
|
3364
3424
|
*/
|
|
3365
|
-
async upsert(fact, tx) {
|
|
3425
|
+
async upsert(fact, tx, at) {
|
|
3366
3426
|
const executor = this.getExecutor(tx);
|
|
3367
|
-
const now = Date.now();
|
|
3427
|
+
const now = typeof at === "number" && Number.isFinite(at) ? at : Date.now();
|
|
3368
3428
|
const tagsJson = JSON.stringify(fact.tags);
|
|
3369
3429
|
const embeddingBlob = this.normalizeEmbeddingBlob(fact.embedding_blob);
|
|
3370
3430
|
const existingRow = await executor.getFirstAsync(
|
|
3371
3431
|
`SELECT id, entity_id, lifecycle_status, stale_after, generated_by,
|
|
3372
3432
|
okf_sources, okf_verified, okf_usage_window,
|
|
3373
|
-
|
|
3433
|
+
stale_after_raw, okf_extra,
|
|
3434
|
+
last_verified_at, last_verified_by, source_pointer, derived_events,
|
|
3435
|
+
title, body, tags, confidence, updated_at
|
|
3374
3436
|
FROM ${this.prefix}entries WHERE id = ?`,
|
|
3375
3437
|
[fact.id]
|
|
3376
3438
|
);
|
|
@@ -3378,14 +3440,16 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
3378
3440
|
throw new WikiGraphNodeOwnershipConflict();
|
|
3379
3441
|
}
|
|
3380
3442
|
const operation = fact.deleted_at ? "DELETE" : existingRow ? "UPDATE" : "INSERT";
|
|
3443
|
+
const unchanged = existingRow != null && (existingRow.title ?? null) === (fact.title ?? null) && (existingRow.body ?? null) === (fact.body ?? null) && (existingRow.tags ?? null) === tagsJson && (existingRow.confidence ?? null) === (fact.confidence ?? null);
|
|
3381
3444
|
const result = await executor.runAsync(
|
|
3382
3445
|
`INSERT INTO ${this.prefix}entries (
|
|
3383
3446
|
id, entity_id, title, body, tags, confidence, source_type,
|
|
3384
3447
|
source_hash, source_ref, created_at, updated_at, last_accessed_at, access_count,
|
|
3385
3448
|
deleted_at, embedding_blob, embedding, okf_type,
|
|
3386
3449
|
lifecycle_status, stale_after, generated_by, last_verified_at, last_verified_by,
|
|
3387
|
-
okf_sources, okf_verified, okf_usage_window,
|
|
3388
|
-
|
|
3450
|
+
okf_sources, okf_verified, okf_usage_window, stale_after_raw, okf_extra,
|
|
3451
|
+
source_pointer, derived_events
|
|
3452
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
3389
3453
|
ON CONFLICT(id) DO UPDATE SET
|
|
3390
3454
|
title = excluded.title,
|
|
3391
3455
|
body = excluded.body,
|
|
@@ -3394,7 +3458,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
3394
3458
|
source_type = excluded.source_type,
|
|
3395
3459
|
source_hash = excluded.source_hash,
|
|
3396
3460
|
source_ref = excluded.source_ref,
|
|
3397
|
-
updated_at = excluded.
|
|
3461
|
+
updated_at = CASE WHEN title IS excluded.title AND body IS excluded.body AND tags IS excluded.tags AND confidence IS excluded.confidence
|
|
3462
|
+
THEN updated_at ELSE excluded.updated_at END,
|
|
3398
3463
|
last_accessed_at = excluded.last_accessed_at,
|
|
3399
3464
|
access_count = excluded.access_count,
|
|
3400
3465
|
deleted_at = excluded.deleted_at,
|
|
@@ -3404,6 +3469,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
3404
3469
|
embedding_failure_kind = CASE WHEN excluded.embedding_blob IS NOT NULL THEN NULL ELSE embedding_failure_kind END,
|
|
3405
3470
|
embedding_attempts = CASE WHEN excluded.embedding_blob IS NOT NULL THEN 0 ELSE embedding_attempts END,
|
|
3406
3471
|
okf_type = excluded.okf_type,
|
|
3472
|
+
generated_by = CASE WHEN title IS excluded.title AND body IS excluded.body AND tags IS excluded.tags AND confidence IS excluded.confidence
|
|
3473
|
+
THEN generated_by ELSE COALESCE(generated_by, excluded.generated_by) END,
|
|
3407
3474
|
derived_events = CASE WHEN ? THEN excluded.derived_events ELSE derived_events END
|
|
3408
3475
|
WHERE ${this.prefix}entries.entity_id = excluded.entity_id`,
|
|
3409
3476
|
[
|
|
@@ -3426,7 +3493,10 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
3426
3493
|
fact.okf_type ?? null,
|
|
3427
3494
|
// OKF v0.2 metadata — bound for INSERT only; ON CONFLICT UPDATE
|
|
3428
3495
|
// preserves the existing row values (these columns are intentionally
|
|
3429
|
-
// absent from the SET clause above)
|
|
3496
|
+
// absent from the SET clause above) — with one exception:
|
|
3497
|
+
// `generated_by` IS in the SET, gated by the §C2 CASE (a real
|
|
3498
|
+
// content change fills a NULL row actor from this bind; a stored
|
|
3499
|
+
// actor is never overwritten).
|
|
3430
3500
|
fact.lifecycle_status ?? "stable",
|
|
3431
3501
|
fact.stale_after ?? null,
|
|
3432
3502
|
fact.generated_by ?? null,
|
|
@@ -3435,6 +3505,11 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
3435
3505
|
fact.okf_sources ? JSON.stringify(fact.okf_sources) : null,
|
|
3436
3506
|
fact.okf_verified ? JSON.stringify(fact.okf_verified) : null,
|
|
3437
3507
|
fact.okf_usage_window ? JSON.stringify(fact.okf_usage_window) : null,
|
|
3508
|
+
// v0.3 columns (specs/okf-v03 §B8, §C3) — same INSERT-only policy:
|
|
3509
|
+
// an in-place engine write preserves both; only upsertForImport
|
|
3510
|
+
// overwrites them.
|
|
3511
|
+
fact.stale_after_raw ?? null,
|
|
3512
|
+
fact.okf_extra ? JSON.stringify(fact.okf_extra) : null,
|
|
3438
3513
|
serializeSourcePointer(fact.source_pointer),
|
|
3439
3514
|
serializeDerivedEvents(fact.derived_events),
|
|
3440
3515
|
// derived_events is writable on conflict (the librarian's in-place
|
|
@@ -3462,6 +3537,12 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
3462
3537
|
okf_sources: parseJsonArray(existingRow.okf_sources, []),
|
|
3463
3538
|
okf_verified: parseJsonArray(existingRow.okf_verified, []),
|
|
3464
3539
|
okf_usage_window: parseJsonObject(existingRow.okf_usage_window),
|
|
3540
|
+
// Always report the stored values, null when the column is NULL
|
|
3541
|
+
// (review 2026-12-04) — same rule as TaskRepository's overlay: a
|
|
3542
|
+
// conditional spread leaves the caller's value in the payload when
|
|
3543
|
+
// the stored column is NULL, publishing state the row does not hold.
|
|
3544
|
+
stale_after_raw: existingRow.stale_after_raw,
|
|
3545
|
+
okf_extra: parseJsonObject(existingRow.okf_extra),
|
|
3465
3546
|
last_verified_at: existingRow.last_verified_at != null ? Number(existingRow.last_verified_at) : null,
|
|
3466
3547
|
last_verified_by: existingRow.last_verified_by ?? null,
|
|
3467
3548
|
source_pointer: parseStoredSourcePointer(existingRow.source_pointer),
|
|
@@ -3470,12 +3551,14 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
3470
3551
|
return stored ? { derived_events: stored } : {};
|
|
3471
3552
|
})() : {}
|
|
3472
3553
|
} : null;
|
|
3554
|
+
const persistedUpdatedAt = existingRow && unchanged ? Number(existingRow.updated_at) : now;
|
|
3555
|
+
const persistedGeneratedBy = existingRow ? unchanged ? existingRow.generated_by ?? null : existingRow.generated_by ?? fact.generated_by ?? null : fact.generated_by ?? null;
|
|
3473
3556
|
await this.outbox.push({
|
|
3474
3557
|
entityId: fact.entity_id,
|
|
3475
3558
|
tableName: "entries",
|
|
3476
3559
|
recordId: fact.id,
|
|
3477
3560
|
operation,
|
|
3478
|
-
payload:
|
|
3561
|
+
payload: { ...fact, ...persistedOkf ?? {}, updated_at: persistedUpdatedAt, generated_by: persistedGeneratedBy }
|
|
3479
3562
|
}, tx);
|
|
3480
3563
|
return result;
|
|
3481
3564
|
}
|
|
@@ -3543,8 +3626,9 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
3543
3626
|
source_hash, source_ref, created_at, updated_at, last_accessed_at, access_count,
|
|
3544
3627
|
deleted_at, embedding_blob, embedding, okf_type,
|
|
3545
3628
|
lifecycle_status, stale_after, generated_by, last_verified_at, last_verified_by,
|
|
3546
|
-
okf_sources, okf_verified, okf_usage_window,
|
|
3547
|
-
|
|
3629
|
+
okf_sources, okf_verified, okf_usage_window, stale_after_raw, okf_extra,
|
|
3630
|
+
source_pointer, derived_events
|
|
3631
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
3548
3632
|
ON CONFLICT(id) DO UPDATE SET
|
|
3549
3633
|
entity_id = excluded.entity_id,
|
|
3550
3634
|
title = excluded.title,
|
|
@@ -3573,6 +3657,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
3573
3657
|
okf_sources = excluded.okf_sources,
|
|
3574
3658
|
okf_verified = excluded.okf_verified,
|
|
3575
3659
|
okf_usage_window = excluded.okf_usage_window,
|
|
3660
|
+
stale_after_raw = excluded.stale_after_raw,
|
|
3661
|
+
okf_extra = excluded.okf_extra,
|
|
3576
3662
|
source_pointer = CASE WHEN ? THEN excluded.source_pointer ELSE source_pointer END,
|
|
3577
3663
|
derived_events = CASE WHEN ? THEN excluded.derived_events ELSE derived_events END`,
|
|
3578
3664
|
[
|
|
@@ -3602,6 +3688,12 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
3602
3688
|
fact.okf_sources ? JSON.stringify(fact.okf_sources) : null,
|
|
3603
3689
|
fact.okf_verified ? JSON.stringify(fact.okf_verified) : null,
|
|
3604
3690
|
fact.okf_usage_window ? JSON.stringify(fact.okf_usage_window) : null,
|
|
3691
|
+
// v0.3 columns (specs/okf-v03 §B8): bound for INSERT and overwritten
|
|
3692
|
+
// on conflict — the dump is authoritative here, same replace
|
|
3693
|
+
// semantics as the okf columns above. The engine's in-place `upsert`
|
|
3694
|
+
// keeps its INSERT-only policy for both (§C3).
|
|
3695
|
+
fact.stale_after_raw ?? null,
|
|
3696
|
+
fact.okf_extra ? JSON.stringify(fact.okf_extra) : null,
|
|
3605
3697
|
serializeSourcePointer(fact.source_pointer),
|
|
3606
3698
|
serializeDerivedEvents(fact.derived_events),
|
|
3607
3699
|
// The presence flag binds to the SET clause's CASE, AFTER the INSERT
|
|
@@ -3970,7 +4062,7 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
3970
4062
|
const executor = this.getExecutor(tx);
|
|
3971
4063
|
const now = Date.now();
|
|
3972
4064
|
const eligibleRows = await executor.getAllAsync(
|
|
3973
|
-
`SELECT id FROM ${this.prefix}entries
|
|
4065
|
+
`SELECT id, generated_by FROM ${this.prefix}entries
|
|
3974
4066
|
WHERE entity_id = ? AND confidence = 'inferred'
|
|
3975
4067
|
AND (last_accessed_at <= ? OR (last_accessed_at IS NULL AND created_at <= ?))
|
|
3976
4068
|
AND source_type != 'immutable_document' AND deleted_at IS NULL`,
|
|
@@ -3979,9 +4071,9 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
3979
4071
|
if (eligibleRows.length === 0) return [];
|
|
3980
4072
|
await executor.runAsync(
|
|
3981
4073
|
`UPDATE ${this.prefix}entries
|
|
3982
|
-
SET confidence = 'tentative', updated_at = ?
|
|
4074
|
+
SET confidence = 'tentative', updated_at = ?, generated_by = COALESCE(generated_by, ?)
|
|
3983
4075
|
WHERE entity_id = ? AND confidence = 'inferred' AND (last_accessed_at <= ? OR (last_accessed_at IS NULL AND created_at <= ?)) AND source_type != 'immutable_document' AND deleted_at IS NULL`,
|
|
3984
|
-
[now, entityId, staleThreshold, staleThreshold]
|
|
4076
|
+
[now, ENGINE_ACTOR, entityId, staleThreshold, staleThreshold]
|
|
3985
4077
|
);
|
|
3986
4078
|
for (const row of eligibleRows) {
|
|
3987
4079
|
await this.outbox.push({
|
|
@@ -3989,7 +4081,7 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
3989
4081
|
tableName: "entries",
|
|
3990
4082
|
recordId: row.id,
|
|
3991
4083
|
operation: "UPDATE",
|
|
3992
|
-
payload: { id: row.id, entity_id: entityId, confidence: "tentative", updated_at: now }
|
|
4084
|
+
payload: { id: row.id, entity_id: entityId, confidence: "tentative", updated_at: now, generated_by: row.generated_by ?? ENGINE_ACTOR }
|
|
3993
4085
|
}, tx);
|
|
3994
4086
|
}
|
|
3995
4087
|
return eligibleRows.map((r) => r.id);
|
|
@@ -3997,25 +4089,38 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
3997
4089
|
/**
|
|
3998
4090
|
* Downgrade specific entries to 'tentative' by IDs.
|
|
3999
4091
|
* Used by MaintenanceService.doRunHeal().
|
|
4092
|
+
*
|
|
4093
|
+
* §C4 (specs/okf-v03, refinement 12): the same COALESCE stamp rule as
|
|
4094
|
+
* {@link downgradeStaleInferred}, and only rows whose confidence is not
|
|
4095
|
+
* already 'tentative' change — `RETURNING` scopes the staged outbox UPDATEs
|
|
4096
|
+
* to the rows actually written, so a repeated verdict against an
|
|
4097
|
+
* already-downgraded fact publishes nothing. The row write and its outbox
|
|
4098
|
+
* event are skipped; heal's `heal_downgraded` receipt still fires (the
|
|
4099
|
+
* model's verdict was applied — MaintenanceService owns the receipt).
|
|
4100
|
+
* Returns the ids that changed.
|
|
4000
4101
|
*/
|
|
4001
4102
|
async downgradeByIds(ids, entityId, tx) {
|
|
4002
|
-
if (ids.length === 0) return;
|
|
4103
|
+
if (ids.length === 0) return [];
|
|
4003
4104
|
const executor = this.getExecutor(tx);
|
|
4004
4105
|
const now = Date.now();
|
|
4005
4106
|
const placeholders = ids.map(() => "?").join(",");
|
|
4006
|
-
await executor.
|
|
4007
|
-
`UPDATE ${this.prefix}entries
|
|
4008
|
-
|
|
4107
|
+
const changedRows = await executor.getAllAsync(
|
|
4108
|
+
`UPDATE ${this.prefix}entries
|
|
4109
|
+
SET confidence = 'tentative', updated_at = ?, generated_by = COALESCE(generated_by, ?)
|
|
4110
|
+
WHERE id IN (${placeholders}) AND entity_id = ? AND confidence != 'tentative'
|
|
4111
|
+
RETURNING id, generated_by`,
|
|
4112
|
+
[now, ENGINE_ACTOR, ...ids, entityId]
|
|
4009
4113
|
);
|
|
4010
|
-
for (const
|
|
4114
|
+
for (const row of changedRows) {
|
|
4011
4115
|
await this.outbox.push({
|
|
4012
4116
|
entityId,
|
|
4013
4117
|
tableName: "entries",
|
|
4014
|
-
recordId: id,
|
|
4118
|
+
recordId: row.id,
|
|
4015
4119
|
operation: "UPDATE",
|
|
4016
|
-
payload: { id, entity_id: entityId, confidence: "tentative", updated_at: now }
|
|
4120
|
+
payload: { id: row.id, entity_id: entityId, confidence: "tentative", updated_at: now, generated_by: row.generated_by ?? ENGINE_ACTOR }
|
|
4017
4121
|
}, tx);
|
|
4018
4122
|
}
|
|
4123
|
+
return changedRows.map((r) => r.id);
|
|
4019
4124
|
}
|
|
4020
4125
|
/**
|
|
4021
4126
|
* Soft-delete specific entries by IDs.
|
|
@@ -4311,6 +4416,13 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
4311
4416
|
* come from the exact row that wins MAX(updated_at). The `id ASC` tie-break
|
|
4312
4417
|
* keeps selection deterministic when two live rows share `updated_at`.
|
|
4313
4418
|
*
|
|
4419
|
+
* §C2 dependency (specs/okf-v03 refinement 27): the content gate lets an
|
|
4420
|
+
* `upsert` change `source_hash` on a row whose `updated_at` stays put, so
|
|
4421
|
+
* "most recently updated" is no longer guaranteed to mean "most recently
|
|
4422
|
+
* content-written". No shipped caller re-hashes a row in place through
|
|
4423
|
+
* `upsert` today; any future caller that does must be checked against
|
|
4424
|
+
* this ordering.
|
|
4425
|
+
*
|
|
4314
4426
|
* Source refs are de-duplicated and processed in chunks so the per-query bind
|
|
4315
4427
|
* parameter count stays under SQLite's `SQLITE_MAX_VARIABLE_NUMBER` (default
|
|
4316
4428
|
* 999, leaving one slot for `entity_id`).
|
|
@@ -4563,7 +4675,7 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
4563
4675
|
if (entityIds.length === 0) return [];
|
|
4564
4676
|
const executor = this.getExecutor(tx);
|
|
4565
4677
|
const placeholders = entityIds.map(() => "?").join(",");
|
|
4566
|
-
const draftClause = opts?.excludeDrafts === true ? ` AND lifecycle_status
|
|
4678
|
+
const draftClause = opts?.excludeDrafts === true ? ` AND lifecycle_status IN ('stable','deprecated')` : "";
|
|
4567
4679
|
const liveClause = opts?.live ? ` AND ${liveAtSql(opts.live.mode)}` : "";
|
|
4568
4680
|
const liveArgs = opts?.live ? [opts.live.t, opts.live.t] : [];
|
|
4569
4681
|
const rows = await executor.getAllAsync(
|
|
@@ -4572,14 +4684,21 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
4572
4684
|
);
|
|
4573
4685
|
return rows.map(mapRowToFact);
|
|
4574
4686
|
}
|
|
4575
|
-
/**
|
|
4576
|
-
|
|
4687
|
+
/**
|
|
4688
|
+
* IDs of live facts that are NOT current knowledge for the given entities
|
|
4689
|
+
* (spec §5.1 drafts, §B4 reads): `lifecycle_status` outside
|
|
4690
|
+
* `('stable','deprecated')` — drafts and unknown statuses. This is the
|
|
4691
|
+
* exclusion set scored search subtracts; `lint().unknownStatus` counts the
|
|
4692
|
+
* non-draft strays and `setLifecycleStatus(id, entityId, 'stable')` clears
|
|
4693
|
+
* them. Callers pass ≤ 100 entity ids.
|
|
4694
|
+
*/
|
|
4695
|
+
async findNotCurrentIdsByEntityIds(entityIds, tx) {
|
|
4577
4696
|
if (entityIds.length === 0) return /* @__PURE__ */ new Set();
|
|
4578
4697
|
const executor = this.getExecutor(tx);
|
|
4579
4698
|
const placeholders = entityIds.map(() => "?").join(",");
|
|
4580
4699
|
const rows = await executor.getAllAsync(
|
|
4581
4700
|
`SELECT id FROM ${this.prefix}entries
|
|
4582
|
-
WHERE entity_id IN (${placeholders}) AND deleted_at IS NULL AND lifecycle_status
|
|
4701
|
+
WHERE entity_id IN (${placeholders}) AND deleted_at IS NULL AND lifecycle_status NOT IN ('stable','deprecated')`,
|
|
4583
4702
|
[...entityIds]
|
|
4584
4703
|
);
|
|
4585
4704
|
return new Set(rows.map((r) => r.id));
|
|
@@ -4947,6 +5066,9 @@ function mapRowToTask(row) {
|
|
|
4947
5066
|
const okf_verified = parseJsonArray(row.okf_verified, []);
|
|
4948
5067
|
const now = Date.now();
|
|
4949
5068
|
const staleAfterRaw = row.stale_after != null ? Number(row.stale_after) : null;
|
|
5069
|
+
const staleAfterRawText = row.stale_after_raw != null ? String(row.stale_after_raw) : null;
|
|
5070
|
+
const generatedAt = row.generated_by != null ? Number(row.updated_at) : null;
|
|
5071
|
+
const okfExtra = parseJsonObject(row.okf_extra);
|
|
4950
5072
|
return {
|
|
4951
5073
|
id: row.id,
|
|
4952
5074
|
entity_id: row.entity_id,
|
|
@@ -4967,9 +5089,15 @@ function mapRowToTask(row) {
|
|
|
4967
5089
|
okf_usage_window: parseJsonObject(row.okf_usage_window),
|
|
4968
5090
|
last_verified_at: row.last_verified_at != null ? Number(row.last_verified_at) : null,
|
|
4969
5091
|
last_verified_by: row.last_verified_by ?? null,
|
|
4970
|
-
//
|
|
4971
|
-
|
|
4972
|
-
|
|
5092
|
+
// v0.3 columns (specs/okf-v03 §F): keys appear only when set; NULL =
|
|
5093
|
+
// nothing to preserve. A malformed stored okf_extra reads as absent.
|
|
5094
|
+
...staleAfterRawText != null ? { stale_after_raw: staleAfterRawText } : {},
|
|
5095
|
+
...okfExtra ? { okf_extra: okfExtra } : {},
|
|
5096
|
+
// Spec §2.7 + §5.3: hydrate so read() consumers don't re-call the
|
|
5097
|
+
// helpers. §B3 read rule (refinement 37): raw non-null ⇒ stale — mirror
|
|
5098
|
+
// of the fact side.
|
|
5099
|
+
isStale: staleAfterRawText != null ? true : coreOkf.isStaleAfter(staleAfterRaw, now),
|
|
5100
|
+
trustTier: coreOkf.deriveTrustTier(okf_verified, generatedAt)
|
|
4973
5101
|
};
|
|
4974
5102
|
}
|
|
4975
5103
|
var TaskRepository = class extends BaseRepository {
|
|
@@ -5030,6 +5158,14 @@ var TaskRepository = class extends BaseRepository {
|
|
|
5030
5158
|
* See {@link EntryRepository.upsert} for the rationale — the same applies
|
|
5031
5159
|
* symmetrically to tasks (spec §2.5). Callers that need to overwrite OKF
|
|
5032
5160
|
* metadata should use {@link upsertForImport}.
|
|
5161
|
+
*
|
|
5162
|
+
* §C2/§C5 (specs/okf-v03): the SET gates `updated_at` and `generated_by`
|
|
5163
|
+
* on an `unchanged` predicate over `description`, `priority`, `status`,
|
|
5164
|
+
* `resolved_at` (null-safe `IS`; the `deleted_at` tombstone is outside the
|
|
5165
|
+
* tuple), so a byte-identical re-upsert leaves both untouched. `updatedAt`
|
|
5166
|
+
* is the shared write instant: a write that carries a same-pass
|
|
5167
|
+
* verification passes its event's `at` here so the event reads current
|
|
5168
|
+
* (`>=`, §A2).
|
|
5033
5169
|
*/
|
|
5034
5170
|
async upsert(task, tx, updatedAt) {
|
|
5035
5171
|
const executor = this.getExecutor(tx);
|
|
@@ -5037,26 +5173,37 @@ var TaskRepository = class extends BaseRepository {
|
|
|
5037
5173
|
const existingRow = await executor.getFirstAsync(
|
|
5038
5174
|
`SELECT id, lifecycle_status, stale_after, generated_by,
|
|
5039
5175
|
okf_sources, okf_verified, okf_usage_window,
|
|
5040
|
-
|
|
5176
|
+
stale_after_raw, okf_extra,
|
|
5177
|
+
last_verified_at, last_verified_by,
|
|
5178
|
+
description, status, priority, resolved_at, updated_at
|
|
5041
5179
|
FROM ${this.prefix}tasks WHERE id = ?`,
|
|
5042
5180
|
[task.id]
|
|
5043
5181
|
);
|
|
5044
5182
|
const operation = task.deleted_at != null ? "DELETE" : existingRow ? "UPDATE" : "INSERT";
|
|
5183
|
+
const storedPriority = (v) => {
|
|
5184
|
+
if (v === null || v === void 0) return null;
|
|
5185
|
+
const n = Number(v);
|
|
5186
|
+
return Number.isFinite(n) ? n : String(v);
|
|
5187
|
+
};
|
|
5188
|
+
const unchanged = existingRow != null && (existingRow.description ?? null) === (task.description ?? null) && Object.is(storedPriority(existingRow.priority), storedPriority(task.priority)) && (existingRow.status ?? null) === (task.status ?? null) && (existingRow.resolved_at != null ? Number(existingRow.resolved_at) : null) === (task.resolved_at != null ? Number(task.resolved_at) : null);
|
|
5045
5189
|
await executor.runAsync(
|
|
5046
5190
|
`INSERT INTO ${this.prefix}tasks (
|
|
5047
5191
|
id, entity_id, description, status, priority,
|
|
5048
5192
|
created_at, updated_at, resolved_at, deleted_at,
|
|
5049
5193
|
lifecycle_status, stale_after, generated_by, last_verified_at, last_verified_by,
|
|
5050
|
-
okf_sources, okf_verified, okf_usage_window
|
|
5051
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
5194
|
+
okf_sources, okf_verified, okf_usage_window, stale_after_raw, okf_extra
|
|
5195
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
5052
5196
|
ON CONFLICT(id) DO UPDATE SET
|
|
5053
5197
|
entity_id = excluded.entity_id,
|
|
5054
5198
|
description = excluded.description,
|
|
5055
5199
|
status = excluded.status,
|
|
5056
5200
|
priority = excluded.priority,
|
|
5057
|
-
updated_at = excluded.
|
|
5201
|
+
updated_at = CASE WHEN description IS excluded.description AND priority IS excluded.priority AND status IS excluded.status AND resolved_at IS excluded.resolved_at
|
|
5202
|
+
THEN updated_at ELSE excluded.updated_at END,
|
|
5058
5203
|
resolved_at = excluded.resolved_at,
|
|
5059
|
-
deleted_at = excluded.deleted_at
|
|
5204
|
+
deleted_at = excluded.deleted_at,
|
|
5205
|
+
generated_by = CASE WHEN description IS excluded.description AND priority IS excluded.priority AND status IS excluded.status AND resolved_at IS excluded.resolved_at
|
|
5206
|
+
THEN generated_by ELSE COALESCE(generated_by, excluded.generated_by) END`,
|
|
5060
5207
|
[
|
|
5061
5208
|
task.id,
|
|
5062
5209
|
task.entity_id,
|
|
@@ -5070,7 +5217,10 @@ var TaskRepository = class extends BaseRepository {
|
|
|
5070
5217
|
task.deleted_at ?? null,
|
|
5071
5218
|
// OKF v0.2 metadata — bound for INSERT only; ON CONFLICT UPDATE
|
|
5072
5219
|
// preserves the existing row values (these columns are intentionally
|
|
5073
|
-
// absent from the SET clause above)
|
|
5220
|
+
// absent from the SET clause above) — with one exception:
|
|
5221
|
+
// `generated_by` IS in the SET, gated by the §C2 CASE (a real
|
|
5222
|
+
// content change fills a NULL row actor from this bind; a stored
|
|
5223
|
+
// actor is never overwritten).
|
|
5074
5224
|
task.lifecycle_status ?? "stable",
|
|
5075
5225
|
task.stale_after ?? null,
|
|
5076
5226
|
task.generated_by ?? null,
|
|
@@ -5078,7 +5228,12 @@ var TaskRepository = class extends BaseRepository {
|
|
|
5078
5228
|
task.last_verified_by ?? null,
|
|
5079
5229
|
task.okf_sources ? JSON.stringify(task.okf_sources) : null,
|
|
5080
5230
|
task.okf_verified ? JSON.stringify(task.okf_verified) : null,
|
|
5081
|
-
task.okf_usage_window ? JSON.stringify(task.okf_usage_window) : null
|
|
5231
|
+
task.okf_usage_window ? JSON.stringify(task.okf_usage_window) : null,
|
|
5232
|
+
// v0.3 columns (specs/okf-v03 §B8, §C3) — same INSERT-only policy:
|
|
5233
|
+
// an in-place engine write preserves both; only upsertForImport
|
|
5234
|
+
// overwrites them.
|
|
5235
|
+
task.stale_after_raw ?? null,
|
|
5236
|
+
task.okf_extra ? JSON.stringify(task.okf_extra) : null
|
|
5082
5237
|
]
|
|
5083
5238
|
);
|
|
5084
5239
|
const persistedOkf = existingRow ? {
|
|
@@ -5088,16 +5243,25 @@ var TaskRepository = class extends BaseRepository {
|
|
|
5088
5243
|
okf_sources: parseJsonArray(existingRow.okf_sources, []),
|
|
5089
5244
|
okf_verified: parseJsonArray(existingRow.okf_verified, []),
|
|
5090
5245
|
okf_usage_window: parseJsonObject(existingRow.okf_usage_window),
|
|
5246
|
+
// Always report the stored values, null when the column is NULL
|
|
5247
|
+
// (review 2026-12-04): the conditional spreads left the caller's
|
|
5248
|
+
// `task.stale_after_raw`/`task.okf_extra` in the payload when the
|
|
5249
|
+
// stored column was NULL — publishing metadata the row does not
|
|
5250
|
+
// contain, against the mirror rule the overlay exists for.
|
|
5251
|
+
stale_after_raw: existingRow.stale_after_raw,
|
|
5252
|
+
okf_extra: parseJsonObject(existingRow.okf_extra),
|
|
5091
5253
|
last_verified_at: existingRow.last_verified_at != null ? Number(existingRow.last_verified_at) : null,
|
|
5092
5254
|
last_verified_by: existingRow.last_verified_by ?? null
|
|
5093
5255
|
} : null;
|
|
5256
|
+
const persistedUpdatedAt = existingRow && unchanged ? Number(existingRow.updated_at) : now;
|
|
5257
|
+
const persistedGeneratedBy = existingRow ? unchanged ? existingRow.generated_by ?? null : existingRow.generated_by ?? task.generated_by ?? null : task.generated_by ?? null;
|
|
5094
5258
|
await this.outbox.push(
|
|
5095
5259
|
{
|
|
5096
5260
|
entityId: task.entity_id,
|
|
5097
5261
|
tableName: "tasks",
|
|
5098
5262
|
recordId: task.id,
|
|
5099
5263
|
operation,
|
|
5100
|
-
payload:
|
|
5264
|
+
payload: { ...task, ...persistedOkf ?? {}, updated_at: persistedUpdatedAt, generated_by: persistedGeneratedBy }
|
|
5101
5265
|
},
|
|
5102
5266
|
tx
|
|
5103
5267
|
);
|
|
@@ -5110,8 +5274,8 @@ var TaskRepository = class extends BaseRepository {
|
|
|
5110
5274
|
id, entity_id, description, status, priority,
|
|
5111
5275
|
created_at, updated_at, resolved_at, deleted_at, okf_type,
|
|
5112
5276
|
lifecycle_status, stale_after, generated_by, last_verified_at, last_verified_by,
|
|
5113
|
-
okf_sources, okf_verified, okf_usage_window
|
|
5114
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
5277
|
+
okf_sources, okf_verified, okf_usage_window, stale_after_raw, okf_extra
|
|
5278
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
5115
5279
|
ON CONFLICT(id) DO UPDATE SET
|
|
5116
5280
|
entity_id = excluded.entity_id,
|
|
5117
5281
|
description = excluded.description,
|
|
@@ -5128,7 +5292,9 @@ var TaskRepository = class extends BaseRepository {
|
|
|
5128
5292
|
last_verified_by = excluded.last_verified_by,
|
|
5129
5293
|
okf_sources = excluded.okf_sources,
|
|
5130
5294
|
okf_verified = excluded.okf_verified,
|
|
5131
|
-
okf_usage_window = excluded.okf_usage_window
|
|
5295
|
+
okf_usage_window = excluded.okf_usage_window,
|
|
5296
|
+
stale_after_raw = excluded.stale_after_raw,
|
|
5297
|
+
okf_extra = excluded.okf_extra`,
|
|
5132
5298
|
[
|
|
5133
5299
|
task.id,
|
|
5134
5300
|
task.entity_id,
|
|
@@ -5147,7 +5313,13 @@ var TaskRepository = class extends BaseRepository {
|
|
|
5147
5313
|
task.last_verified_by ?? null,
|
|
5148
5314
|
task.okf_sources ? JSON.stringify(task.okf_sources) : null,
|
|
5149
5315
|
task.okf_verified ? JSON.stringify(task.okf_verified) : null,
|
|
5150
|
-
task.okf_usage_window ? JSON.stringify(task.okf_usage_window) : null
|
|
5316
|
+
task.okf_usage_window ? JSON.stringify(task.okf_usage_window) : null,
|
|
5317
|
+
// v0.3 columns (specs/okf-v03 §B8): bound for INSERT and overwritten
|
|
5318
|
+
// on conflict — the dump is authoritative here, mirroring
|
|
5319
|
+
// EntryRepository.upsertForImport. The engine's in-place `upsert`
|
|
5320
|
+
// keeps its INSERT-only policy for both (§C3).
|
|
5321
|
+
task.stale_after_raw ?? null,
|
|
5322
|
+
task.okf_extra ? JSON.stringify(task.okf_extra) : null
|
|
5151
5323
|
]
|
|
5152
5324
|
);
|
|
5153
5325
|
}
|
|
@@ -5722,7 +5894,7 @@ var EdgeRepository = class extends BaseRepository {
|
|
|
5722
5894
|
END
|
|
5723
5895
|
) >= ?
|
|
5724
5896
|
AND n.source_type NOT IN (${excludeSourceTypesPlaceholders})
|
|
5725
|
-
AND (? = 0 OR n.lifecycle_status
|
|
5897
|
+
AND (? = 0 OR n.lifecycle_status IN ('stable','deprecated'))
|
|
5726
5898
|
AND ${liveAtSql(opts.live.mode, "n.")}
|
|
5727
5899
|
WHERE w.depth < ?
|
|
5728
5900
|
AND instr(w.visited, ',' || (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END) || ',') = 0
|
|
@@ -5779,6 +5951,9 @@ function mapRowToEdge(row) {
|
|
|
5779
5951
|
function entitySummaryMetaKey(entityId) {
|
|
5780
5952
|
return `entity_summary:${entityId}`;
|
|
5781
5953
|
}
|
|
5954
|
+
function bundleMetadataMetaKey(entityId) {
|
|
5955
|
+
return `okf_bundle_metadata:${entityId}`;
|
|
5956
|
+
}
|
|
5782
5957
|
var START_OF_LOG_WATERMARK = Object.freeze({ at: Number.MIN_SAFE_INTEGER, id: "" });
|
|
5783
5958
|
var CheckpointIncompleteError = class extends Error {
|
|
5784
5959
|
constructor() {
|
|
@@ -8893,7 +9068,7 @@ ${JSON.stringify(currentFacts, null, 2)}`,
|
|
|
8893
9068
|
const anchorsShown = !usesPlaceholders || hasDocumentAnchors;
|
|
8894
9069
|
const groundingCorpus = healGrounding ? buildGroundingCorpus([
|
|
8895
9070
|
...eventsShown ? effectiveEvents.map(summaryOf) : [],
|
|
8896
|
-
...anchorsShown ? effectiveAnchors.map((a, i) => ({ status: a?.lifecycle_status, shown: promptAnchors[i] })).filter((x) => x.status
|
|
9071
|
+
...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) : []
|
|
8897
9072
|
]) : null;
|
|
8898
9073
|
const { shapedCandidates, degraded } = applyBodyTruncation(
|
|
8899
9074
|
healCandidates,
|
|
@@ -9429,7 +9604,7 @@ var IngestionService = class {
|
|
|
9429
9604
|
if (!sourceRef) throw new Error("Invalid sourceRef");
|
|
9430
9605
|
params = { ...params, sourceRef };
|
|
9431
9606
|
await this.assertGraphNodeOwnership(entityId, params.nodes, tx);
|
|
9432
|
-
const now = Date.now();
|
|
9607
|
+
const now = opts?.at !== void 0 && Number.isFinite(opts.at) ? opts.at : Date.now();
|
|
9433
9608
|
const ontologyState = await this.ontologyService?.getEffectiveState(entityId, tx) ?? { mode: "off", manifest: { node_types: [], edge_types: [] } };
|
|
9434
9609
|
let { mode, manifest } = ontologyState;
|
|
9435
9610
|
const strictEffective = opts?.strict === false ? false : opts?.strict === true || mode === "strict";
|
|
@@ -9476,6 +9651,9 @@ var IngestionService = class {
|
|
|
9476
9651
|
access_count: 0,
|
|
9477
9652
|
deleted_at: null,
|
|
9478
9653
|
okf_type: normalized.okf_type,
|
|
9654
|
+
// §C1: only the engine-authored path stamps; the host path passes no
|
|
9655
|
+
// flag and binds NULL (the COALESCE still protects any stored actor).
|
|
9656
|
+
...opts?.authoredByEngine ? { generated_by: ENGINE_ACTOR } : {},
|
|
9479
9657
|
...opts?.nodeTrust?.get(node.id)
|
|
9480
9658
|
};
|
|
9481
9659
|
wikiFacts.push(wikiFact);
|
|
@@ -9544,7 +9722,7 @@ var IngestionService = class {
|
|
|
9544
9722
|
await this.sourceRefIndexRepo.softDeleteByEntityAndSourceRef(entityId, params.sourceRef, tx);
|
|
9545
9723
|
await this.sourceRefIndexRepo.upsert(entityId, params.sourceHash, params.sourceRef, tx);
|
|
9546
9724
|
for (const wikiFact of wikiFacts) {
|
|
9547
|
-
await this.entryRepo.upsert(wikiFact, tx);
|
|
9725
|
+
await this.entryRepo.upsert(wikiFact, tx, now);
|
|
9548
9726
|
}
|
|
9549
9727
|
let edgesInsertedCount = 0;
|
|
9550
9728
|
for (const edge of validEdges) {
|
|
@@ -9687,7 +9865,10 @@ var IngestionService = class {
|
|
|
9687
9865
|
entityId,
|
|
9688
9866
|
{ sourceRef, sourceHash, nodes: hostNodes, edges: hostEdges },
|
|
9689
9867
|
tx,
|
|
9690
|
-
|
|
9868
|
+
// §C1: the engine authored every node here. §C5: `at` shares this pass's
|
|
9869
|
+
// clock read (used for the grounding events above) with the row writes,
|
|
9870
|
+
// so a grounded fact's verification stays current.
|
|
9871
|
+
{ strict: false, diag: { buffer: diagBuffer, operation: "ingest" }, authoredByEngine: true, at: now, ...nodeTrust.size > 0 ? { nodeTrust } : {} }
|
|
9691
9872
|
);
|
|
9692
9873
|
return { deletedSourceFactIds, insertedFacts };
|
|
9693
9874
|
}
|
|
@@ -9787,9 +9968,11 @@ var IngestionService = class {
|
|
|
9787
9968
|
access_count: 0,
|
|
9788
9969
|
deleted_at: null,
|
|
9789
9970
|
okf_type: normalized.okf_type,
|
|
9971
|
+
// §C1: the engine extracted this fact from the document.
|
|
9972
|
+
generated_by: ENGINE_ACTOR,
|
|
9790
9973
|
...outcome?.trust
|
|
9791
9974
|
};
|
|
9792
|
-
await this.entryRepo.upsert(wikiFact, tx);
|
|
9975
|
+
await this.entryRepo.upsert(wikiFact, tx, now);
|
|
9793
9976
|
titleIndex.set(normalizeTitleKey(fact.title), { id, okf_type: normalized.okf_type });
|
|
9794
9977
|
insertedDescriptors.push({
|
|
9795
9978
|
id,
|
|
@@ -10787,9 +10970,15 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
|
|
|
10787
10970
|
// Legacy writes no pointer (spec §Legacy path): the column stays null
|
|
10788
10971
|
// on every legacy fact, and the legacy prompt keeps its exact text.
|
|
10789
10972
|
source_pointer: null,
|
|
10973
|
+
// §C1 (specs/okf-v03): the engine authored this fact, so a NULL row
|
|
10974
|
+
// actor is stamped; the upsert's COALESCE never overwrites a stored
|
|
10975
|
+
// (explicit or imported foreign) actor. §C5: the pass's clock read
|
|
10976
|
+
// is shared with the grounding event, so the verification is current
|
|
10977
|
+
// by the `>=` currency test.
|
|
10978
|
+
generated_by: ENGINE_ACTOR,
|
|
10790
10979
|
...grounding?.trust
|
|
10791
10980
|
};
|
|
10792
|
-
await deps.entryRepo.upsert(factObj, tx);
|
|
10981
|
+
await deps.entryRepo.upsert(factObj, tx, now);
|
|
10793
10982
|
const volunteeredSourceEvent = facts[validFactItemIndexes[k]]?.source_event;
|
|
10794
10983
|
if (volunteeredSourceEvent !== void 0 && volunteeredSourceEvent !== null) {
|
|
10795
10984
|
diagBuffer.push({
|
|
@@ -10831,7 +11020,8 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
|
|
|
10831
11020
|
created_at: now,
|
|
10832
11021
|
updated_at: now,
|
|
10833
11022
|
resolved_at: null,
|
|
10834
|
-
deleted_at: null
|
|
11023
|
+
deleted_at: null,
|
|
11024
|
+
generated_by: ENGINE_ACTOR
|
|
10835
11025
|
};
|
|
10836
11026
|
await deps.taskRepo.upsert(taskObj, tx);
|
|
10837
11027
|
}
|
|
@@ -11429,13 +11619,19 @@ async function applyOps(deps, ctx, input) {
|
|
|
11429
11619
|
deleted_at: null,
|
|
11430
11620
|
okf_type: normalized.okf_type,
|
|
11431
11621
|
source_pointer: pointer,
|
|
11622
|
+
// §C1 (specs/okf-v03): the engine authored this text (ADD, the
|
|
11623
|
+
// supersede replacement and the contradicts draft all land here), so a
|
|
11624
|
+
// NULL row actor is stamped; the upsert's COALESCE never overwrites a
|
|
11625
|
+
// stored actor. §C5: the pass's clock read is shared with the
|
|
11626
|
+
// grounding event (§C5 currency, `>=`).
|
|
11627
|
+
generated_by: ENGINE_ACTOR,
|
|
11432
11628
|
// §2: only an UPDATE converted to SUPERSEDE inherits (the merged text
|
|
11433
11629
|
// rests on the target); ADD and plain SUPERSEDE carry no list.
|
|
11434
11630
|
...inheritedDerivedEvents(inheritFrom, pointer?.event_id ?? null),
|
|
11435
11631
|
...g2?.trust,
|
|
11436
11632
|
...draft ? { lifecycle_status: "draft" } : {}
|
|
11437
11633
|
};
|
|
11438
|
-
await deps.entryRepo.upsert(row, tx);
|
|
11634
|
+
await deps.entryRepo.upsert(row, tx, now);
|
|
11439
11635
|
await deps.entryRepo.setTemporal(id, entityId, { valid_from: validFrom }, tx);
|
|
11440
11636
|
if (g.candidate.pointerUnresolved !== null) {
|
|
11441
11637
|
input.diagnostics.push({
|
|
@@ -11510,7 +11706,18 @@ async function applyOps(deps, ctx, input) {
|
|
|
11510
11706
|
title: newTitle,
|
|
11511
11707
|
body: op.body ?? g.candidate.fact.body,
|
|
11512
11708
|
updated_at: now,
|
|
11709
|
+
// §C1: the engine authored the merged text, so a NULL stored actor
|
|
11710
|
+
// is filled; the upsert's COALESCE keeps a stored (foreign)
|
|
11711
|
+
// actor. The §C2 gate stamps only on a real content change.
|
|
11712
|
+
generated_by: existing.generated_by ?? ENGINE_ACTOR,
|
|
11513
11713
|
...derived ? { derived_events: derived } : {}
|
|
11714
|
+
// No shared `at`: this in-place rewrite carries no same-pass
|
|
11715
|
+
// verification, so §C5's shared-instant rationale does not apply —
|
|
11716
|
+
// the repo stamps its own instant inside the transaction (the heal
|
|
11717
|
+
// writeNow discipline). The pass-start read could predate a
|
|
11718
|
+
// concurrent verification commit (the rewritten row would then
|
|
11719
|
+
// out-stay its own replacement, §5.3) or move updated_at backwards
|
|
11720
|
+
// (review 2026-12-04).
|
|
11514
11721
|
}, tx);
|
|
11515
11722
|
titleIndex.delete(normalizeTitleKey(existing.title));
|
|
11516
11723
|
titleIndex.set(normalizeTitleKey(newTitle), { id: existing.id, okf_type: existing.okf_type ?? null });
|
|
@@ -11574,7 +11781,8 @@ async function applyOps(deps, ctx, input) {
|
|
|
11574
11781
|
created_at: now,
|
|
11575
11782
|
updated_at: now,
|
|
11576
11783
|
resolved_at: null,
|
|
11577
|
-
deleted_at: null
|
|
11784
|
+
deleted_at: null,
|
|
11785
|
+
generated_by: ENGINE_ACTOR
|
|
11578
11786
|
};
|
|
11579
11787
|
await deps.taskRepo.upsert(taskObj, tx);
|
|
11580
11788
|
}
|
|
@@ -12632,6 +12840,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
|
|
|
12632
12840
|
await this.metadataRepo.updateCheckpoint(entityId, { memory: 0, heal: 0 }, tx);
|
|
12633
12841
|
}
|
|
12634
12842
|
await this.metadataRepo.deleteMeta(entitySummaryMetaKey(entityId), tx);
|
|
12843
|
+
await this.metadataRepo.deleteMeta(bundleMetadataMetaKey(entityId), tx);
|
|
12635
12844
|
} else {
|
|
12636
12845
|
const hasIdSelectors = params.entryId !== void 0 || params.taskId !== void 0;
|
|
12637
12846
|
const hasSourceSelectors = params.sourceRef !== void 0 || params.sourceHash !== void 0;
|
|
@@ -12981,8 +13190,10 @@ DROP TRIGGER IF EXISTS ${ad};`);
|
|
|
12981
13190
|
* model-directed move emits a `heal_deleted` / `heal_downgraded` receipt
|
|
12982
13191
|
* after commit (`applied`, `applied_unscreened`, or `below_floor`), in every
|
|
12983
13192
|
* mode. An `applied` receipt records that the model VERDICT was applied
|
|
12984
|
-
* (`downgradeByIds` runs
|
|
12985
|
-
* reduced confidence still gets an `applied` receipt
|
|
13193
|
+
* (`downgradeByIds` runs for every applied id): a fact that was already at
|
|
13194
|
+
* reduced confidence still gets an `applied` receipt even though the row
|
|
13195
|
+
* write and its outbox UPDATE are skipped for an already-'tentative' fact
|
|
13196
|
+
* (specs/okf-v03 §C4). A withheld delete paired with a restating `newFact` leaves the fact
|
|
12986
13197
|
* live and the restatement is skipped as `fact_deduplicated`.
|
|
12987
13198
|
*/
|
|
12988
13199
|
async doRunHeal(entityId, options) {
|
|
@@ -13047,11 +13258,14 @@ DROP TRIGGER IF EXISTS ${ad};`);
|
|
|
13047
13258
|
...keywordUnavailable ? { searchUnavailable: true } : {}
|
|
13048
13259
|
};
|
|
13049
13260
|
}
|
|
13050
|
-
const allTasks = await this.taskRepo.findAllPending([entityId], HEAL_MAX_TASKS)
|
|
13261
|
+
const allTasks = (await this.taskRepo.findAllPending([entityId], HEAL_MAX_TASKS)).map((t) => {
|
|
13262
|
+
const { okf_extra: _extra, stale_after_raw: _sraw, ...rest } = t;
|
|
13263
|
+
return rest;
|
|
13264
|
+
});
|
|
13051
13265
|
const recentEvents = await this.eventRepo.getRecent(entityId, 20);
|
|
13052
13266
|
const healGrounding = this.promptService.groundingFor("heal");
|
|
13053
13267
|
const toPromptShape = (f) => {
|
|
13054
|
-
const { embedding: _embedding, embedding_blob: _blob, ...rest } = f;
|
|
13268
|
+
const { embedding: _embedding, embedding_blob: _blob, okf_extra: _extra, stale_after_raw: _sraw, ...rest } = f;
|
|
13055
13269
|
const shown = healGrounding ? (({ lifecycle_status: _l, okf_verified: _v, last_verified_at: _a, last_verified_by: _b, ...r }) => r)(rest) : rest;
|
|
13056
13270
|
return { ...shown, tags: typeof shown.tags === "string" ? JSON.parse(shown.tags) : shown.tags };
|
|
13057
13271
|
};
|
|
@@ -13227,7 +13441,8 @@ DROP TRIGGER IF EXISTS ${ad};`);
|
|
|
13227
13441
|
continue;
|
|
13228
13442
|
}
|
|
13229
13443
|
const id = generateId("fact_");
|
|
13230
|
-
const
|
|
13444
|
+
const writeNow = Date.now();
|
|
13445
|
+
const grounding = healGrounding ? groundingOutcome(checkGrounding(fact.evidence, validNewFactCorpora[k] ?? [], healGrounding), writeNow) : null;
|
|
13231
13446
|
if (grounding?.diagnostic) {
|
|
13232
13447
|
diagBuffer.push({ ...diagBase, code: grounding.diagnostic.code, detail: { factId: id, itemIndex: validNewFactItemIndexes[k], reason: grounding.diagnostic.reason } });
|
|
13233
13448
|
}
|
|
@@ -13242,14 +13457,17 @@ DROP TRIGGER IF EXISTS ${ad};`);
|
|
|
13242
13457
|
source_hash: null,
|
|
13243
13458
|
source_ref: null,
|
|
13244
13459
|
source_pointer: null,
|
|
13245
|
-
created_at:
|
|
13246
|
-
updated_at:
|
|
13460
|
+
created_at: writeNow,
|
|
13461
|
+
updated_at: writeNow,
|
|
13247
13462
|
last_accessed_at: null,
|
|
13248
13463
|
access_count: 0,
|
|
13249
13464
|
deleted_at: null,
|
|
13465
|
+
// §C1: the engine authored this restatement, so a NULL row actor is
|
|
13466
|
+
// stamped; the upsert's COALESCE never overwrites a stored actor.
|
|
13467
|
+
generated_by: ENGINE_ACTOR,
|
|
13250
13468
|
...grounding?.trust
|
|
13251
13469
|
};
|
|
13252
|
-
await this.entryRepo.upsert(factObj, tx);
|
|
13470
|
+
await this.entryRepo.upsert(factObj, tx, writeNow);
|
|
13253
13471
|
insertedFacts.push({ id, entity_id: entityId, title: fact.title, body: fact.body, tags: JSON.stringify(fact.tags) });
|
|
13254
13472
|
healFactsForDedupe.push({ id, title: fact.title });
|
|
13255
13473
|
}
|
|
@@ -14327,152 +14545,1104 @@ var MaintenanceScheduler = class {
|
|
|
14327
14545
|
return { confirmed, pending };
|
|
14328
14546
|
}
|
|
14329
14547
|
};
|
|
14330
|
-
|
|
14331
|
-
|
|
14332
|
-
|
|
14333
|
-
|
|
14334
|
-
|
|
14335
|
-
|
|
14336
|
-
|
|
14337
|
-
|
|
14548
|
+
var CONFIDENCE_VALUES = /* @__PURE__ */ new Set(["certain", "inferred", "tentative"]);
|
|
14549
|
+
var SOURCE_TYPES = /* @__PURE__ */ new Set([
|
|
14550
|
+
"user_stated",
|
|
14551
|
+
"librarian_inferred",
|
|
14552
|
+
"user_confirmed",
|
|
14553
|
+
"immutable_document"
|
|
14554
|
+
]);
|
|
14555
|
+
var TASK_STATUSES = /* @__PURE__ */ new Set(["pending", "in_progress", "done", "abandoned"]);
|
|
14556
|
+
var LIFECYCLE_VALUES = /* @__PURE__ */ new Set(["draft", "stable", "deprecated"]);
|
|
14557
|
+
var EVENT_TYPES = /* @__PURE__ */ new Set(["observation", "decision", "action", "outcome"]);
|
|
14558
|
+
var FACT_MAPPED_KEYS = [
|
|
14559
|
+
"type",
|
|
14560
|
+
"title",
|
|
14561
|
+
"tags",
|
|
14562
|
+
"timestamp",
|
|
14563
|
+
"resource",
|
|
14564
|
+
"id",
|
|
14565
|
+
"entity_id",
|
|
14566
|
+
"confidence",
|
|
14567
|
+
"source_type",
|
|
14568
|
+
"source_hash",
|
|
14569
|
+
"created_at",
|
|
14570
|
+
"updated_at",
|
|
14571
|
+
"access_count",
|
|
14572
|
+
"last_accessed_at",
|
|
14573
|
+
"deleted_at",
|
|
14574
|
+
"status",
|
|
14575
|
+
"stale_after",
|
|
14576
|
+
"generated",
|
|
14577
|
+
"verified",
|
|
14578
|
+
"sources",
|
|
14579
|
+
"usage_window",
|
|
14580
|
+
"valid_from",
|
|
14581
|
+
"valid_to",
|
|
14582
|
+
"superseded_by",
|
|
14583
|
+
"superseded_at",
|
|
14584
|
+
"prior_valid_to",
|
|
14585
|
+
"source_pointer",
|
|
14586
|
+
"derived_events",
|
|
14587
|
+
"x-llm-wiki-lifecycle"
|
|
14588
|
+
];
|
|
14589
|
+
var TASK_MAPPED_KEYS = [
|
|
14590
|
+
"type",
|
|
14591
|
+
"title",
|
|
14592
|
+
"timestamp",
|
|
14593
|
+
"id",
|
|
14594
|
+
"entity_id",
|
|
14595
|
+
"status",
|
|
14596
|
+
"execution_status",
|
|
14597
|
+
"priority",
|
|
14598
|
+
"created_at",
|
|
14599
|
+
"updated_at",
|
|
14600
|
+
"resolved_at",
|
|
14601
|
+
"deleted_at",
|
|
14602
|
+
"stale_after",
|
|
14603
|
+
"generated",
|
|
14604
|
+
"verified",
|
|
14605
|
+
"sources",
|
|
14606
|
+
"usage_window"
|
|
14607
|
+
];
|
|
14608
|
+
var FACT_MAPPED = new Set(FACT_MAPPED_KEYS);
|
|
14609
|
+
var TASK_MAPPED = new Set(TASK_MAPPED_KEYS);
|
|
14610
|
+
var RAW_SLOT_KEY = "x-llm-wiki-raw";
|
|
14611
|
+
function basenameMd(filePath) {
|
|
14612
|
+
const name = filePath.slice(filePath.lastIndexOf("/") + 1);
|
|
14613
|
+
return name.endsWith(".md") ? name.slice(0, -3) : name;
|
|
14338
14614
|
}
|
|
14339
|
-
function
|
|
14340
|
-
|
|
14615
|
+
function isConceptFile(filePath) {
|
|
14616
|
+
if (!filePath.endsWith(".md")) return false;
|
|
14617
|
+
if (filePath.endsWith("/index.md") || filePath === "index.md") return false;
|
|
14618
|
+
if (filePath.endsWith("/log.md") || filePath === "log.md") return false;
|
|
14619
|
+
return true;
|
|
14341
14620
|
}
|
|
14342
|
-
function
|
|
14343
|
-
|
|
14344
|
-
const { at, id } = raw;
|
|
14345
|
-
if (typeof at !== "number" || !Number.isFinite(at) || typeof id !== "string") return null;
|
|
14346
|
-
return { at, id };
|
|
14621
|
+
function isStructuralPath(filePath) {
|
|
14622
|
+
return filePath.endsWith("/index.md") || filePath === "index.md" || filePath.endsWith("/log.md") || filePath === "log.md";
|
|
14347
14623
|
}
|
|
14348
|
-
|
|
14349
|
-
|
|
14350
|
-
|
|
14351
|
-
|
|
14352
|
-
|
|
14353
|
-
const
|
|
14354
|
-
|
|
14355
|
-
|
|
14356
|
-
|
|
14357
|
-
|
|
14358
|
-
|
|
14359
|
-
|
|
14360
|
-
|
|
14361
|
-
else occurredInvalid = true;
|
|
14362
|
-
}
|
|
14363
|
-
let reason = null;
|
|
14364
|
-
const invalidCreated = Number.isNaN(v) || v < -DATE_MAX;
|
|
14365
|
-
if (invalidCreated) reason = "invalid";
|
|
14366
|
-
else if (v > now) reason = "future";
|
|
14367
|
-
else if (merge && localWm !== null && Number.isFinite(localWm.at) && !after(v, e.id, localWm) && (sourceWm === null || after(v, e.id, sourceWm))) {
|
|
14368
|
-
reason = "behind_watermark";
|
|
14369
|
-
}
|
|
14370
|
-
if (reason === "behind_watermark" && occurredAt === null && Number.isFinite(v) && v >= 0) {
|
|
14371
|
-
occurredAt = Math.trunc(v);
|
|
14624
|
+
function posixDirname(filePath) {
|
|
14625
|
+
const idx = filePath.lastIndexOf("/");
|
|
14626
|
+
return idx === -1 ? "" : filePath.slice(0, idx);
|
|
14627
|
+
}
|
|
14628
|
+
function resolveRelativePath(fromFile, linkPath) {
|
|
14629
|
+
const baseDir = posixDirname(fromFile);
|
|
14630
|
+
const segments = [...baseDir ? baseDir.split("/") : [], ...linkPath.split("/")];
|
|
14631
|
+
const resolved = [];
|
|
14632
|
+
for (const seg of segments) {
|
|
14633
|
+
if (seg === "" || seg === ".") continue;
|
|
14634
|
+
if (seg === "..") {
|
|
14635
|
+
resolved.pop();
|
|
14636
|
+
continue;
|
|
14372
14637
|
}
|
|
14373
|
-
|
|
14374
|
-
if (reason === null && occurredInvalid) stamp.reason = "invalid";
|
|
14375
|
-
plan.set(e, stamp);
|
|
14376
|
-
if (reason !== null) restamp.push({ e, key: invalidCreated ? -Infinity : v, stamp });
|
|
14638
|
+
resolved.push(seg);
|
|
14377
14639
|
}
|
|
14378
|
-
|
|
14379
|
-
|
|
14380
|
-
|
|
14640
|
+
return resolved.join("/");
|
|
14641
|
+
}
|
|
14642
|
+
function strictTargetPath(fromFile, strippedPath) {
|
|
14643
|
+
return strippedPath.startsWith("/") ? strippedPath.slice(1) : resolveRelativePath(fromFile, strippedPath);
|
|
14644
|
+
}
|
|
14645
|
+
function resolveSupersededBy(raw, filePath, isV3Bundle, bundleRootPathToId) {
|
|
14646
|
+
if (!isV3Bundle) return raw;
|
|
14647
|
+
return bundleRootPathToId.get(strictTargetPath(filePath, raw)) ?? raw;
|
|
14648
|
+
}
|
|
14649
|
+
function decodeLinkPath(path) {
|
|
14650
|
+
if (!path.includes("%")) return path;
|
|
14651
|
+
try {
|
|
14652
|
+
return decodeURIComponent(path);
|
|
14653
|
+
} catch {
|
|
14654
|
+
return path;
|
|
14381
14655
|
}
|
|
14382
|
-
restamp.forEach((x, i) => {
|
|
14383
|
-
x.stamp.createdAt = floor + 1 + i;
|
|
14384
|
-
});
|
|
14385
|
-
return plan;
|
|
14386
14656
|
}
|
|
14387
|
-
|
|
14388
|
-
|
|
14389
|
-
|
|
14390
|
-
|
|
14391
|
-
|
|
14392
|
-
|
|
14393
|
-
|
|
14394
|
-
|
|
14395
|
-
this.entryRepo = entryRepo;
|
|
14396
|
-
this.taskRepo = taskRepo;
|
|
14397
|
-
this.eventRepo = eventRepo;
|
|
14398
|
-
this.edgeRepo = edgeRepo;
|
|
14399
|
-
this.metadataRepo = metadataRepo;
|
|
14400
|
-
this.searchService = searchService;
|
|
14401
|
-
this.jobManager = jobManager;
|
|
14402
|
-
this.embeddingService = embeddingService;
|
|
14403
|
-
this.options = options;
|
|
14404
|
-
this.vectorRemoval = vectorRemoval;
|
|
14405
|
-
this.prefix = prefix;
|
|
14657
|
+
function addPathAliases(map, filePath, resolvedId) {
|
|
14658
|
+
map.set(filePath, resolvedId);
|
|
14659
|
+
const withoutDot = filePath.replace(/^\.\//, "");
|
|
14660
|
+
if (withoutDot !== filePath) map.set(withoutDot, resolvedId);
|
|
14661
|
+
const entityRelative = filePath.replace(/^entities\/[^/]+\//, "");
|
|
14662
|
+
if (entityRelative !== filePath) {
|
|
14663
|
+
map.set(entityRelative, resolvedId);
|
|
14664
|
+
map.set(`./${entityRelative}`, resolvedId);
|
|
14406
14665
|
}
|
|
14407
|
-
|
|
14408
|
-
|
|
14409
|
-
|
|
14410
|
-
|
|
14411
|
-
|
|
14412
|
-
|
|
14413
|
-
|
|
14414
|
-
|
|
14415
|
-
|
|
14416
|
-
|
|
14417
|
-
|
|
14418
|
-
|
|
14419
|
-
|
|
14420
|
-
|
|
14421
|
-
|
|
14422
|
-
const entities = {};
|
|
14423
|
-
const BATCH = 3;
|
|
14424
|
-
for (let i = 0; i < ids.length; i += BATCH) {
|
|
14425
|
-
const batch = ids.slice(i, i + BATCH);
|
|
14426
|
-
const batchResults = await Promise.all(
|
|
14427
|
-
batch.map(
|
|
14428
|
-
async (id) => {
|
|
14429
|
-
const bundle = await this.getFullBundle(id, { includeBlobs: true, includeForgotten });
|
|
14430
|
-
const storedSources = await this.exportStoredSources(id);
|
|
14431
|
-
return [id, storedSources.length > 0 ? { ...bundle, storedSources } : bundle];
|
|
14432
|
-
}
|
|
14433
|
-
)
|
|
14434
|
-
);
|
|
14435
|
-
for (const [id, bundle] of batchResults) {
|
|
14436
|
-
entities[id] = bundle;
|
|
14437
|
-
}
|
|
14438
|
-
}
|
|
14439
|
-
return { generatedAt: Date.now(), entities };
|
|
14666
|
+
}
|
|
14667
|
+
function lookupResolvedId(map, path) {
|
|
14668
|
+
const normalized = path.replace(/^\.\//, "");
|
|
14669
|
+
return map.get(path) ?? map.get(normalized) ?? map.get(`./${normalized}`);
|
|
14670
|
+
}
|
|
14671
|
+
function stripLinkSuffix(linkPath) {
|
|
14672
|
+
const hashIdx = linkPath.indexOf("#");
|
|
14673
|
+
const queryIdx = linkPath.indexOf("?");
|
|
14674
|
+
if (hashIdx === -1 && queryIdx === -1) return linkPath;
|
|
14675
|
+
const cut = hashIdx === -1 ? queryIdx : queryIdx === -1 ? hashIdx : Math.min(hashIdx, queryIdx);
|
|
14676
|
+
return linkPath.slice(0, cut);
|
|
14677
|
+
}
|
|
14678
|
+
function resolveRoute(filePath, frontmatterType, options) {
|
|
14679
|
+
if (options?.typeMapping && Object.prototype.hasOwnProperty.call(options.typeMapping, frontmatterType)) {
|
|
14680
|
+
return options.typeMapping[frontmatterType];
|
|
14440
14681
|
}
|
|
14441
|
-
|
|
14442
|
-
|
|
14443
|
-
|
|
14444
|
-
|
|
14445
|
-
|
|
14446
|
-
|
|
14447
|
-
|
|
14448
|
-
|
|
14449
|
-
|
|
14450
|
-
}
|
|
14451
|
-
} finally {
|
|
14452
|
-
this.jobManager.releaseImportLocks(entityIds);
|
|
14453
|
-
}
|
|
14454
|
-
return { skippedSources };
|
|
14682
|
+
if (filePath.includes("/facts/")) return "fact";
|
|
14683
|
+
if (filePath.includes("/tasks/")) return "task";
|
|
14684
|
+
return options?.defaultSchema ?? "fact";
|
|
14685
|
+
}
|
|
14686
|
+
function parseFrontmatterTimestamp(value, fallback) {
|
|
14687
|
+
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
14688
|
+
if (typeof value === "string") {
|
|
14689
|
+
const parsed = Date.parse(value);
|
|
14690
|
+
if (Number.isFinite(parsed)) return parsed;
|
|
14455
14691
|
}
|
|
14456
|
-
|
|
14457
|
-
|
|
14692
|
+
return fallback;
|
|
14693
|
+
}
|
|
14694
|
+
function parseStaleAfterPair(raw, parserUnreadable) {
|
|
14695
|
+
if (parserUnreadable) {
|
|
14696
|
+
return { stale_after: null, stale_after_raw: "unreadable" };
|
|
14458
14697
|
}
|
|
14459
|
-
|
|
14460
|
-
|
|
14461
|
-
async storePresent(prefix, tx) {
|
|
14462
|
-
return await this.metadataRepo.tableExists(`${prefix}source_documents`, tx) && await this.metadataRepo.tableExists(`${prefix}source_passages`, tx);
|
|
14698
|
+
if (raw === void 0 || raw === null || Array.isArray(raw) && raw.length === 0) {
|
|
14699
|
+
return { stale_after: null, stale_after_raw: null };
|
|
14463
14700
|
}
|
|
14464
|
-
|
|
14465
|
-
|
|
14466
|
-
|
|
14467
|
-
|
|
14468
|
-
const
|
|
14469
|
-
|
|
14470
|
-
|
|
14471
|
-
|
|
14472
|
-
);
|
|
14473
|
-
|
|
14474
|
-
|
|
14475
|
-
|
|
14701
|
+
if (typeof raw === "string" && raw.trim() === "") {
|
|
14702
|
+
return { stale_after: null, stale_after_raw: null };
|
|
14703
|
+
}
|
|
14704
|
+
if (typeof raw === "string") {
|
|
14705
|
+
const epoch = coreOkf.parseOkfTimestamp(raw);
|
|
14706
|
+
return epoch != null ? { stale_after: epoch, stale_after_raw: null } : { stale_after: null, stale_after_raw: raw };
|
|
14707
|
+
}
|
|
14708
|
+
if (typeof raw === "object") {
|
|
14709
|
+
return { stale_after: null, stale_after_raw: JSON.stringify(raw) };
|
|
14710
|
+
}
|
|
14711
|
+
return { stale_after: null, stale_after_raw: String(raw) };
|
|
14712
|
+
}
|
|
14713
|
+
function parseTagsList(raw) {
|
|
14714
|
+
if (typeof raw === "string") return raw === "" ? [] : [raw];
|
|
14715
|
+
if (Array.isArray(raw)) return raw.filter((t) => typeof t === "string");
|
|
14716
|
+
return [];
|
|
14717
|
+
}
|
|
14718
|
+
function replaceLoneSurrogates(s) {
|
|
14719
|
+
let out = "";
|
|
14720
|
+
for (let i = 0; i < s.length; i++) {
|
|
14721
|
+
const c = s.charCodeAt(i);
|
|
14722
|
+
if (c >= 55296 && c <= 56319) {
|
|
14723
|
+
const n = i + 1 < s.length ? s.charCodeAt(i + 1) : 0;
|
|
14724
|
+
if (n >= 56320 && n <= 57343) {
|
|
14725
|
+
out += s[i] + s[i + 1];
|
|
14726
|
+
i++;
|
|
14727
|
+
} else out += "\uFFFD";
|
|
14728
|
+
} else if (c >= 56320 && c <= 57343) {
|
|
14729
|
+
out += "\uFFFD";
|
|
14730
|
+
} else {
|
|
14731
|
+
out += s[i];
|
|
14732
|
+
}
|
|
14733
|
+
}
|
|
14734
|
+
return out;
|
|
14735
|
+
}
|
|
14736
|
+
function unescapeLogSummary(summary) {
|
|
14737
|
+
return summary.replace(/\\\]/g, "]").replace(/\\\[/g, "[").replace(/\\\\/g, "\\");
|
|
14738
|
+
}
|
|
14739
|
+
var LOG_LINE_PATTERN = /^\(([^)]+)\)\s*(?:\[((?:\\.|[^\[\]\\])*)\]\(([^)]+)\)|(\S.*))$/;
|
|
14740
|
+
function parseLogEntryText(text) {
|
|
14741
|
+
const match = LOG_LINE_PATTERN.exec(text.trim());
|
|
14742
|
+
if (!match) return null;
|
|
14743
|
+
const [, rawType, linkedSummary, linkPath, plainSummary] = match;
|
|
14744
|
+
const event_type = EVENT_TYPES.has(rawType) ? rawType : "observation";
|
|
14745
|
+
if (linkPath) {
|
|
14746
|
+
return { event_type, summary: unescapeLogSummary(linkedSummary), linkPath };
|
|
14747
|
+
}
|
|
14748
|
+
return { event_type, summary: unescapeLogSummary((plainSummary ?? "").trim()) };
|
|
14749
|
+
}
|
|
14750
|
+
function parseLifecycleStatus(raw) {
|
|
14751
|
+
if (typeof raw === "string") {
|
|
14752
|
+
if (LIFECYCLE_VALUES.has(raw)) return raw;
|
|
14753
|
+
return raw === "" ? "stable" : raw;
|
|
14754
|
+
}
|
|
14755
|
+
if (raw === null || raw === void 0) return "stable";
|
|
14756
|
+
if (typeof raw === "object") return JSON.stringify(raw);
|
|
14757
|
+
return String(raw);
|
|
14758
|
+
}
|
|
14759
|
+
function isUnreadable(frontmatter, issues, key) {
|
|
14760
|
+
return issues.some((i) => i.key === key) && !Object.prototype.hasOwnProperty.call(frontmatter, key);
|
|
14761
|
+
}
|
|
14762
|
+
function extractOkfExtra(mapped, frontmatter, unparsed) {
|
|
14763
|
+
const extras = {};
|
|
14764
|
+
for (const [key, value] of Object.entries(frontmatter)) {
|
|
14765
|
+
if (mapped.has(key) || key === RAW_SLOT_KEY) continue;
|
|
14766
|
+
if (Object.prototype.hasOwnProperty.call(unparsed.raw, key)) continue;
|
|
14767
|
+
extras[key] = value;
|
|
14768
|
+
}
|
|
14769
|
+
const rawSlot = {};
|
|
14770
|
+
for (const [key, lines] of Object.entries(unparsed.raw)) {
|
|
14771
|
+
if (mapped.has(key) || key === RAW_SLOT_KEY) continue;
|
|
14772
|
+
rawSlot[key] = lines;
|
|
14773
|
+
}
|
|
14774
|
+
if (Object.keys(rawSlot).length > 0) extras[RAW_SLOT_KEY] = rawSlot;
|
|
14775
|
+
const generated = frontmatter.generated;
|
|
14776
|
+
if (generated !== null && typeof generated === "object" && !Array.isArray(generated)) {
|
|
14777
|
+
const nested = {};
|
|
14778
|
+
for (const [k, v] of Object.entries(generated)) {
|
|
14779
|
+
if (k === "by" || k === "at") continue;
|
|
14780
|
+
nested[k] = v;
|
|
14781
|
+
}
|
|
14782
|
+
if (Object.keys(nested).length > 0) extras.generated = nested;
|
|
14783
|
+
}
|
|
14784
|
+
return Object.keys(extras).length > 0 ? extras : void 0;
|
|
14785
|
+
}
|
|
14786
|
+
var SKIPPED_FILES_CAP = 100;
|
|
14787
|
+
function reportDroppedValues(mapped, filePath, frontmatter, unparsed, droppedValues) {
|
|
14788
|
+
for (const issue of unparsed.issues) {
|
|
14789
|
+
if (issue.key === RAW_SLOT_KEY) continue;
|
|
14790
|
+
if (Object.prototype.hasOwnProperty.call(frontmatter, issue.key)) continue;
|
|
14791
|
+
if (issue.reason !== "anchor_or_alias" && !mapped.has(issue.key)) continue;
|
|
14792
|
+
if (issue.reason === "anchor_or_alias" && Object.prototype.hasOwnProperty.call(unparsed.raw, issue.key)) continue;
|
|
14793
|
+
droppedValues.push({ path: filePath, key: issue.key, reason: issue.reason });
|
|
14794
|
+
}
|
|
14795
|
+
if (Object.prototype.hasOwnProperty.call(frontmatter, RAW_SLOT_KEY) || Object.prototype.hasOwnProperty.call(unparsed.raw, RAW_SLOT_KEY)) {
|
|
14796
|
+
droppedValues.push({ path: filePath, key: RAW_SLOT_KEY, reason: "reserved_key" });
|
|
14797
|
+
}
|
|
14798
|
+
const statusRaw = frontmatter.status;
|
|
14799
|
+
if (statusRaw !== null && statusRaw !== void 0 && typeof statusRaw === "object") {
|
|
14800
|
+
droppedValues.push({ path: filePath, key: "status", reason: "not_scalar" });
|
|
14801
|
+
}
|
|
14802
|
+
const { ignored } = coreOkf.parseSourcesFlexible(frontmatter.sources);
|
|
14803
|
+
if (ignored > 0) {
|
|
14804
|
+
droppedValues.push({ path: filePath, key: "sources", reason: `sources_entry_invalid:${ignored}` });
|
|
14805
|
+
}
|
|
14806
|
+
const rawVerified = frontmatter.verified;
|
|
14807
|
+
const verifiedTotal = Array.isArray(rawVerified) ? rawVerified.length : rawVerified !== null && typeof rawVerified === "object" ? 1 : 0;
|
|
14808
|
+
const verifiedInvalid = verifiedTotal - coreOkf.parseVerifiedFlexible(rawVerified).length;
|
|
14809
|
+
if (verifiedInvalid > 0) {
|
|
14810
|
+
droppedValues.push({ path: filePath, key: "verified", reason: `verified_entry_invalid:${verifiedInvalid}` });
|
|
14811
|
+
}
|
|
14812
|
+
const title = frontmatter.title;
|
|
14813
|
+
if (title !== null && title !== void 0 && typeof title !== "string" && !(Array.isArray(title) && title.length === 0)) {
|
|
14814
|
+
droppedValues.push({ path: filePath, key: "title", reason: "wrong_type" });
|
|
14815
|
+
}
|
|
14816
|
+
const usageWindow = frontmatter.usage_window;
|
|
14817
|
+
if (usageWindow !== null && usageWindow !== void 0 && usageWindow !== "" && typeof usageWindow !== "object") {
|
|
14818
|
+
droppedValues.push({ path: filePath, key: "usage_window", reason: "wrong_type" });
|
|
14819
|
+
}
|
|
14820
|
+
const generated = frontmatter.generated;
|
|
14821
|
+
if (generated !== null && generated !== void 0 && !(Array.isArray(generated) && generated.length === 0)) {
|
|
14822
|
+
if (typeof generated !== "object" || Array.isArray(generated)) {
|
|
14823
|
+
droppedValues.push({ path: filePath, key: "generated", reason: "wrong_type" });
|
|
14824
|
+
} else if (generated.by == null) {
|
|
14825
|
+
droppedValues.push({ path: filePath, key: "generated", reason: "generated_without_by" });
|
|
14826
|
+
}
|
|
14827
|
+
}
|
|
14828
|
+
}
|
|
14829
|
+
function frontmatterToFact(entityId, id, frontmatter, body, now, droppedPointerValues, isV3Bundle, unparsed, filePath, droppedValues, bundleRootPathToId) {
|
|
14830
|
+
reportDroppedValues(FACT_MAPPED, filePath, frontmatter, unparsed, droppedValues);
|
|
14831
|
+
const hasLifecycleKey = Object.prototype.hasOwnProperty.call(frontmatter, "x-llm-wiki-lifecycle");
|
|
14832
|
+
const lifecycleKeyValue = frontmatter["x-llm-wiki-lifecycle"];
|
|
14833
|
+
const restoreLifecycle = hasLifecycleKey && isV3Bundle && typeof lifecycleKeyValue === "string" && lifecycleKeyValue !== "" && parseLifecycleStatus(frontmatter.status) === "deprecated";
|
|
14834
|
+
if (hasLifecycleKey && !restoreLifecycle) {
|
|
14835
|
+
droppedValues.push({ path: filePath, key: "x-llm-wiki-lifecycle", reason: "not_applicable" });
|
|
14836
|
+
}
|
|
14837
|
+
const created_at = parseFrontmatterTimestamp(frontmatter.created_at, now);
|
|
14838
|
+
const generatedAt = coreOkf.parseOkfTimestamp(frontmatter.generated?.at);
|
|
14839
|
+
const updated_at = generatedAt ?? parseFrontmatterTimestamp(
|
|
14840
|
+
frontmatter.timestamp,
|
|
14841
|
+
parseFrontmatterTimestamp(frontmatter.updated_at, now)
|
|
14842
|
+
);
|
|
14843
|
+
const verified = coreOkf.parseVerifiedFlexible(frontmatter.verified);
|
|
14844
|
+
const rawSources = frontmatter.sources;
|
|
14845
|
+
const hasSourcesKey = rawSources !== void 0 || isUnreadable(frontmatter, unparsed.issues, "sources");
|
|
14846
|
+
const { sources } = coreOkf.parseSourcesFlexible(rawSources);
|
|
14847
|
+
const usageWindow = frontmatter.usage_window && typeof frontmatter.usage_window === "object" ? frontmatter.usage_window : null;
|
|
14848
|
+
const lastV = coreOkf.latestVerified(verified, now);
|
|
14849
|
+
const lifecycle_status = isUnreadable(frontmatter, unparsed.issues, "status") ? "unreadable" : restoreLifecycle ? parseLifecycleStatus(lifecycleKeyValue) : parseLifecycleStatus(frontmatter.status);
|
|
14850
|
+
const { stale_after, stale_after_raw } = parseStaleAfterPair(
|
|
14851
|
+
frontmatter.stale_after,
|
|
14852
|
+
isUnreadable(frontmatter, unparsed.issues, "stale_after")
|
|
14853
|
+
);
|
|
14854
|
+
const generated_by = frontmatter.generated?.by ?? null;
|
|
14855
|
+
const okf_extra = extractOkfExtra(FACT_MAPPED, frontmatter, unparsed);
|
|
14856
|
+
if (!hasSourcesKey && !isV3Bundle) {
|
|
14857
|
+
const urls = coreOkf.parseCitationsList(body);
|
|
14858
|
+
for (const url of urls) {
|
|
14859
|
+
sources.push({ resource: url });
|
|
14860
|
+
}
|
|
14861
|
+
}
|
|
14862
|
+
return {
|
|
14863
|
+
id,
|
|
14864
|
+
entity_id: entityId,
|
|
14865
|
+
title: typeof frontmatter.title === "string" ? frontmatter.title : "",
|
|
14866
|
+
body,
|
|
14867
|
+
tags: parseTagsList(frontmatter.tags),
|
|
14868
|
+
confidence: CONFIDENCE_VALUES.has(String(frontmatter.confidence)) ? frontmatter.confidence : "tentative",
|
|
14869
|
+
source_type: SOURCE_TYPES.has(String(frontmatter.source_type)) ? frontmatter.source_type : "user_stated",
|
|
14870
|
+
source_hash: typeof frontmatter.source_hash === "string" ? frontmatter.source_hash : null,
|
|
14871
|
+
source_ref: typeof frontmatter.resource === "string" ? frontmatter.resource : null,
|
|
14872
|
+
created_at,
|
|
14873
|
+
updated_at,
|
|
14874
|
+
last_accessed_at: frontmatter.last_accessed_at != null ? parseFrontmatterTimestamp(frontmatter.last_accessed_at, now) : null,
|
|
14875
|
+
access_count: typeof frontmatter.access_count === "number" ? frontmatter.access_count : 0,
|
|
14876
|
+
deleted_at: frontmatter.deleted_at != null ? parseFrontmatterTimestamp(frontmatter.deleted_at, 0) : null,
|
|
14877
|
+
okf_type: frontmatter.type,
|
|
14878
|
+
// OKF v0.2
|
|
14879
|
+
lifecycle_status,
|
|
14880
|
+
stale_after,
|
|
14881
|
+
// OKF v0.3 §B3: the sibling raw slot of the pair above — verbatim wire
|
|
14882
|
+
// text when the value would not parse, NULL when it did (or was absent).
|
|
14883
|
+
stale_after_raw,
|
|
14884
|
+
generated_by,
|
|
14885
|
+
okf_sources: sources,
|
|
14886
|
+
okf_verified: verified,
|
|
14887
|
+
okf_usage_window: usageWindow,
|
|
14888
|
+
last_verified_at: lastV?.at ?? null,
|
|
14889
|
+
last_verified_by: lastV?.by ?? null,
|
|
14890
|
+
...okf_extra ? { okf_extra } : {},
|
|
14891
|
+
...optionalEpoch("valid_from", frontmatter.valid_from),
|
|
14892
|
+
...optionalEpoch("valid_to", frontmatter.valid_to),
|
|
14893
|
+
...typeof frontmatter.superseded_by === "string" ? {
|
|
14894
|
+
superseded_by: resolveSupersededBy(
|
|
14895
|
+
frontmatter.superseded_by,
|
|
14896
|
+
filePath,
|
|
14897
|
+
isV3Bundle,
|
|
14898
|
+
bundleRootPathToId
|
|
14899
|
+
)
|
|
14900
|
+
} : {},
|
|
14901
|
+
...optionalEpoch("superseded_at", frontmatter.superseded_at),
|
|
14902
|
+
...optionalEpoch("prior_valid_to", frontmatter.prior_valid_to),
|
|
14903
|
+
// Source pointer (specs/source-pointers §Export, import, and OKF): the
|
|
14904
|
+
// parse path has no diagnostic channel, so it reports through the result.
|
|
14905
|
+
// ABSENT key → the property is omitted (not null), so the import
|
|
14906
|
+
// presence guard survives the parse. Malformed → the property is omitted
|
|
14907
|
+
// AND the drop is reported as entry id + reason slug — never the raw
|
|
14908
|
+
// value, which can carry quote text.
|
|
14909
|
+
...(() => {
|
|
14910
|
+
const raw = frontmatter.source_pointer;
|
|
14911
|
+
if (raw === void 0) return {};
|
|
14912
|
+
const v = validateSourcePointerValue(raw);
|
|
14913
|
+
if (v === void 0) {
|
|
14914
|
+
droppedPointerValues.push({ factId: id, reason: "malformed" });
|
|
14915
|
+
return {};
|
|
14916
|
+
}
|
|
14917
|
+
return { source_pointer: v };
|
|
14918
|
+
})(),
|
|
14919
|
+
// derived_events (specs/inplace-update-provenance §5): a well-formed list
|
|
14920
|
+
// is restored; absent or empty omits the property (import presence rule);
|
|
14921
|
+
// malformed omits it AND is reported by id + slug, never the raw value.
|
|
14922
|
+
...(() => {
|
|
14923
|
+
const raw = frontmatter.derived_events;
|
|
14924
|
+
if (raw === void 0) return {};
|
|
14925
|
+
const v = validateDerivedEventsValue(raw);
|
|
14926
|
+
if (v === void 0) {
|
|
14927
|
+
droppedPointerValues.push({ factId: id, reason: "derived_events_malformed" });
|
|
14928
|
+
return {};
|
|
14929
|
+
}
|
|
14930
|
+
return v ? { derived_events: v } : {};
|
|
14931
|
+
})()
|
|
14932
|
+
};
|
|
14933
|
+
}
|
|
14934
|
+
function optionalEpoch(key, v) {
|
|
14935
|
+
return typeof v === "number" && Number.isFinite(v) && v >= 0 ? { [key]: Math.trunc(v) } : {};
|
|
14936
|
+
}
|
|
14937
|
+
function frontmatterToTask(entityId, id, frontmatter, now, usesV1StatusRule, unparsed, filePath, droppedValues) {
|
|
14938
|
+
reportDroppedValues(TASK_MAPPED, filePath, frontmatter, unparsed, droppedValues);
|
|
14939
|
+
const created_at = parseFrontmatterTimestamp(frontmatter.created_at, now);
|
|
14940
|
+
const generatedAt = coreOkf.parseOkfTimestamp(frontmatter.generated?.at);
|
|
14941
|
+
const updated_at = generatedAt ?? parseFrontmatterTimestamp(
|
|
14942
|
+
frontmatter.timestamp,
|
|
14943
|
+
parseFrontmatterTimestamp(frontmatter.updated_at, now)
|
|
14944
|
+
);
|
|
14945
|
+
const verified = coreOkf.parseVerifiedFlexible(frontmatter.verified);
|
|
14946
|
+
const { sources } = coreOkf.parseSourcesFlexible(frontmatter.sources);
|
|
14947
|
+
const usageWindow = frontmatter.usage_window && typeof frontmatter.usage_window === "object" ? frontmatter.usage_window : null;
|
|
14948
|
+
const lastV = coreOkf.latestVerified(verified, now);
|
|
14949
|
+
const lifecycleRaw = frontmatter.status;
|
|
14950
|
+
const executionRaw = frontmatter.execution_status;
|
|
14951
|
+
const isExecutionStatus = (v) => typeof v === "string" && TASK_STATUSES.has(v);
|
|
14952
|
+
const executionFromWire = !isExecutionStatus(executionRaw) && isExecutionStatus(lifecycleRaw);
|
|
14953
|
+
const lifecycle_status = usesV1StatusRule || executionFromWire ? "stable" : isUnreadable(frontmatter, unparsed.issues, "status") ? "unreadable" : parseLifecycleStatus(lifecycleRaw);
|
|
14954
|
+
const { stale_after, stale_after_raw } = parseStaleAfterPair(
|
|
14955
|
+
frontmatter.stale_after,
|
|
14956
|
+
isUnreadable(frontmatter, unparsed.issues, "stale_after")
|
|
14957
|
+
);
|
|
14958
|
+
const okf_extra = extractOkfExtra(TASK_MAPPED, frontmatter, unparsed);
|
|
14959
|
+
let executionState;
|
|
14960
|
+
if (usesV1StatusRule) {
|
|
14961
|
+
executionState = isExecutionStatus(lifecycleRaw) ? lifecycleRaw : "pending";
|
|
14962
|
+
} else {
|
|
14963
|
+
executionState = isExecutionStatus(executionRaw) ? executionRaw : isExecutionStatus(lifecycleRaw) ? lifecycleRaw : "pending";
|
|
14964
|
+
}
|
|
14965
|
+
return {
|
|
14966
|
+
id,
|
|
14967
|
+
entity_id: entityId,
|
|
14968
|
+
description: typeof frontmatter.title === "string" ? frontmatter.title : "",
|
|
14969
|
+
status: executionState,
|
|
14970
|
+
priority: typeof frontmatter.priority === "number" ? frontmatter.priority : 0,
|
|
14971
|
+
created_at,
|
|
14972
|
+
updated_at,
|
|
14973
|
+
resolved_at: frontmatter.resolved_at != null ? parseFrontmatterTimestamp(frontmatter.resolved_at, now) : null,
|
|
14974
|
+
deleted_at: frontmatter.deleted_at != null ? parseFrontmatterTimestamp(frontmatter.deleted_at, 0) : null,
|
|
14975
|
+
okf_type: frontmatter.type,
|
|
14976
|
+
// OKF v0.2
|
|
14977
|
+
lifecycle_status,
|
|
14978
|
+
stale_after,
|
|
14979
|
+
// OKF v0.3 §B3: symmetric with facts — verbatim wire text when the value
|
|
14980
|
+
// would not parse, NULL when it did (or was absent).
|
|
14981
|
+
stale_after_raw,
|
|
14982
|
+
generated_by: frontmatter.generated?.by ?? null,
|
|
14983
|
+
okf_sources: sources,
|
|
14984
|
+
okf_verified: verified,
|
|
14985
|
+
okf_usage_window: usageWindow,
|
|
14986
|
+
last_verified_at: lastV?.at ?? null,
|
|
14987
|
+
last_verified_by: lastV?.by ?? null,
|
|
14988
|
+
...okf_extra ? { okf_extra } : {}
|
|
14989
|
+
};
|
|
14990
|
+
}
|
|
14991
|
+
function findLogMdPath(files) {
|
|
14992
|
+
return files.find((f) => f.path.endsWith("/log.md") || f.path === "log.md")?.path;
|
|
14993
|
+
}
|
|
14994
|
+
function extractEdgesFromLinks(filePath, resolvedId, links, pathToResolvedId, bundleRootPathToId, entityId, now, seenEdges, edges, isV3Bundle) {
|
|
14995
|
+
for (const link of links) {
|
|
14996
|
+
const strippedPath = stripLinkSuffix(decodeLinkPath(link.path));
|
|
14997
|
+
const resolvedTargetPath = resolveRelativePath(filePath, strippedPath);
|
|
14998
|
+
if (isStructuralPath(strippedPath) || isStructuralPath(resolvedTargetPath)) continue;
|
|
14999
|
+
const targetId = isV3Bundle ? bundleRootPathToId.get(strictTargetPath(filePath, strippedPath)) : lookupResolvedId(pathToResolvedId, strippedPath) ?? lookupResolvedId(pathToResolvedId, resolvedTargetPath);
|
|
15000
|
+
if (!targetId) continue;
|
|
15001
|
+
const edgeKey = `${resolvedId}\0${targetId}\0${link.text}`;
|
|
15002
|
+
if (seenEdges.has(edgeKey)) continue;
|
|
15003
|
+
seenEdges.add(edgeKey);
|
|
15004
|
+
edges.push({
|
|
15005
|
+
id: generateId(),
|
|
15006
|
+
entity_id: entityId,
|
|
15007
|
+
source_id: resolvedId,
|
|
15008
|
+
target_id: targetId,
|
|
15009
|
+
edge_type: link.text,
|
|
15010
|
+
created_at: now
|
|
15011
|
+
});
|
|
15012
|
+
}
|
|
15013
|
+
}
|
|
15014
|
+
function parseOkfVersionInts(raw) {
|
|
15015
|
+
if (typeof raw !== "string") return void 0;
|
|
15016
|
+
const m = /^(\d+)\.(\d+)$/.exec(raw);
|
|
15017
|
+
if (!m) return void 0;
|
|
15018
|
+
return { major: Number(m[1]), minor: Number(m[2]) };
|
|
15019
|
+
}
|
|
15020
|
+
function isVersion(v, major, minor) {
|
|
15021
|
+
return v !== void 0 && v.major === major && v.minor === minor;
|
|
15022
|
+
}
|
|
15023
|
+
function versionAtLeast(v, major, minor) {
|
|
15024
|
+
return v !== void 0 && (v.major > major || v.major === major && v.minor >= minor);
|
|
15025
|
+
}
|
|
15026
|
+
function detectOkfBundleLayout(meta) {
|
|
15027
|
+
const profile = meta.profile;
|
|
15028
|
+
const version = parseOkfVersionInts(meta.okf_version);
|
|
15029
|
+
const isProfile1 = profile === "llm-wiki/1";
|
|
15030
|
+
const isProfile2 = profile === "llm-wiki/2";
|
|
15031
|
+
const isProfile3 = profile === "llm-wiki/3";
|
|
15032
|
+
const isLegacyV1 = profile === void 0 && isVersion(version, 0, 1);
|
|
15033
|
+
const isVersionOnlyV2 = profile === void 0 && isVersion(version, 0, 2);
|
|
15034
|
+
const isUnknownProfileV2 = profile !== void 0 && !isProfile1 && !isProfile2 && !isProfile3 && isVersion(version, 0, 2);
|
|
15035
|
+
const isVersionOnlyV3 = profile === void 0 && versionAtLeast(version, 0, 3);
|
|
15036
|
+
const isUnknownProfileV3 = profile !== void 0 && !isProfile1 && !isProfile2 && !isProfile3 && versionAtLeast(version, 0, 3);
|
|
15037
|
+
const isV3Bundle = isProfile3 || isVersionOnlyV3 || isUnknownProfileV3;
|
|
15038
|
+
const summaryEligible = isProfile1 || isProfile2 || isLegacyV1 || isVersionOnlyV2 || isUnknownProfileV2 || isV3Bundle;
|
|
15039
|
+
return {
|
|
15040
|
+
isProfile1,
|
|
15041
|
+
isProfile2,
|
|
15042
|
+
isProfile3,
|
|
15043
|
+
isLegacyV1,
|
|
15044
|
+
isVersionOnlyV2,
|
|
15045
|
+
isUnknownProfileV2,
|
|
15046
|
+
isVersionOnlyV3,
|
|
15047
|
+
isUnknownProfileV3,
|
|
15048
|
+
isV3Bundle,
|
|
15049
|
+
summaryEligible
|
|
15050
|
+
};
|
|
15051
|
+
}
|
|
15052
|
+
function parseOkfBundle(entityId, files, options) {
|
|
15053
|
+
const now = Date.now();
|
|
15054
|
+
const normalizeOkfPath = (p) => p.replace(/^\.\//, "").replace(/\\/g, "/");
|
|
15055
|
+
const normalizedFiles = files.map((f) => ({ ...f, path: normalizeOkfPath(f.path) }));
|
|
15056
|
+
const allowlistedFiles = normalizedFiles.filter((f) => coreOkf.isAllowedOkfPath(f.path));
|
|
15057
|
+
const skippedFiles = [];
|
|
15058
|
+
for (const f of normalizedFiles) {
|
|
15059
|
+
if (!coreOkf.isAllowedOkfPath(f.path)) skippedFiles.push({ path: f.path, reason: "path_not_allowed" });
|
|
15060
|
+
}
|
|
15061
|
+
const entityDirs = new Set(
|
|
15062
|
+
allowlistedFiles.map((f) => /^entities\/([^/]+)\//.exec(f.path)?.[1]).filter((dir) => !!dir)
|
|
15063
|
+
);
|
|
15064
|
+
if (entityDirs.size > 1) {
|
|
15065
|
+
throw new Error(
|
|
15066
|
+
`parseOkfBundle: expected a single-entity bundle for "${entityId}", found entities: ${Array.from(entityDirs).join(", ")}`
|
|
15067
|
+
);
|
|
15068
|
+
}
|
|
15069
|
+
const entityDir = entityDirs.values().next().value ?? entityId;
|
|
15070
|
+
const entityPrefix = `entities/${entityDir}/`;
|
|
15071
|
+
const allowedFiles = allowlistedFiles.filter(
|
|
15072
|
+
(f) => f.path === "index.md" || f.path.startsWith(entityPrefix)
|
|
15073
|
+
);
|
|
15074
|
+
const rootIndex = allowedFiles.find((f) => f.path === "index.md");
|
|
15075
|
+
const profileMeta = rootIndex ? coreOkf.parseRootIndexMd(rootIndex.content) : {};
|
|
15076
|
+
const okfVersion = profileMeta.okf_version;
|
|
15077
|
+
const profile = profileMeta.profile;
|
|
15078
|
+
const { isProfile1, isLegacyV1, isV3Bundle, summaryEligible } = detectOkfBundleLayout(profileMeta);
|
|
15079
|
+
const droppedValues = [];
|
|
15080
|
+
if (rootIndex) {
|
|
15081
|
+
for (const issue of profileMeta.issues ?? []) {
|
|
15082
|
+
if (issue.reason === "anchor_or_alias") {
|
|
15083
|
+
droppedValues.push({ path: rootIndex.path, key: issue.key, reason: issue.reason });
|
|
15084
|
+
}
|
|
15085
|
+
}
|
|
15086
|
+
if (profileMeta.issues?.some((issue) => issue.key === RAW_SLOT_KEY && issue.reason === "reserved_key") || Object.prototype.hasOwnProperty.call(profileMeta.raw, RAW_SLOT_KEY)) {
|
|
15087
|
+
droppedValues.push({ path: rootIndex.path, key: RAW_SLOT_KEY, reason: "reserved_key" });
|
|
15088
|
+
}
|
|
15089
|
+
}
|
|
15090
|
+
const isTypeLessConcept = (filePath, type) => isV3Bundle && (filePath.includes("/facts/") || filePath.includes("/tasks/")) && (type === void 0 || type === "");
|
|
15091
|
+
let entitySummary;
|
|
15092
|
+
const entityIndex = allowedFiles.find((f) => f.path === `${entityPrefix}index.md`);
|
|
15093
|
+
if (summaryEligible && entityIndex) {
|
|
15094
|
+
const summary = coreOkf.parseEntityIndexMd(entityIndex.content).summary;
|
|
15095
|
+
entitySummary = summary || void 0;
|
|
15096
|
+
}
|
|
15097
|
+
const pathToResolvedId = /* @__PURE__ */ new Map();
|
|
15098
|
+
const bundleRootPathToId = /* @__PURE__ */ new Map();
|
|
15099
|
+
for (const file of allowedFiles) {
|
|
15100
|
+
if (!isConceptFile(file.path)) continue;
|
|
15101
|
+
const { frontmatter } = coreOkf.parseConcept(file.content);
|
|
15102
|
+
if (isTypeLessConcept(file.path, frontmatter.type)) {
|
|
15103
|
+
skippedFiles.push({ path: file.path, reason: "no_type" });
|
|
15104
|
+
continue;
|
|
15105
|
+
}
|
|
15106
|
+
const route = resolveRoute(file.path, frontmatter.type ?? "", options);
|
|
15107
|
+
if (route === "ignore") continue;
|
|
15108
|
+
const resolvedId = typeof frontmatter.id === "string" && frontmatter.id ? frontmatter.id : basenameMd(file.path);
|
|
15109
|
+
addPathAliases(pathToResolvedId, file.path, resolvedId);
|
|
15110
|
+
bundleRootPathToId.set(file.path, resolvedId);
|
|
15111
|
+
}
|
|
15112
|
+
const facts = [];
|
|
15113
|
+
const tasks = [];
|
|
15114
|
+
const droppedPointerValues = [];
|
|
15115
|
+
const edges = [];
|
|
15116
|
+
let logContent = null;
|
|
15117
|
+
const logMdPath = findLogMdPath(allowedFiles);
|
|
15118
|
+
for (const file of allowedFiles) {
|
|
15119
|
+
if (file.path.endsWith("/log.md") || file.path === "log.md") {
|
|
15120
|
+
logContent = file.content;
|
|
15121
|
+
continue;
|
|
15122
|
+
}
|
|
15123
|
+
if (!isConceptFile(file.path)) continue;
|
|
15124
|
+
const { frontmatter, body, raw: unparsedRaw, issues } = coreOkf.parseConcept(file.content);
|
|
15125
|
+
if (isTypeLessConcept(file.path, frontmatter.type)) continue;
|
|
15126
|
+
const route = resolveRoute(file.path, frontmatter.type ?? "", options);
|
|
15127
|
+
if (route === "ignore") continue;
|
|
15128
|
+
const resolvedId = typeof frontmatter.id === "string" && frontmatter.id ? frontmatter.id : basenameMd(file.path);
|
|
15129
|
+
const { body: storedBody, relatedLinks } = coreOkf.splitRelatedSection(body);
|
|
15130
|
+
const edgeLinks = isProfile1 || isLegacyV1 ? relatedLinks : [...relatedLinks, ...coreOkf.extractMarkdownLinks(storedBody)];
|
|
15131
|
+
const usesV1StatusRule = isProfile1 || isLegacyV1 || profile === void 0 && okfVersion === void 0;
|
|
15132
|
+
if (route === "fact") {
|
|
15133
|
+
facts.push(
|
|
15134
|
+
frontmatterToFact(entityId, resolvedId, frontmatter, storedBody, now, droppedPointerValues, isV3Bundle, {
|
|
15135
|
+
raw: unparsedRaw,
|
|
15136
|
+
issues
|
|
15137
|
+
}, file.path, droppedValues, bundleRootPathToId)
|
|
15138
|
+
);
|
|
15139
|
+
} else {
|
|
15140
|
+
tasks.push(
|
|
15141
|
+
frontmatterToTask(entityId, resolvedId, frontmatter, now, usesV1StatusRule, {
|
|
15142
|
+
raw: unparsedRaw,
|
|
15143
|
+
issues
|
|
15144
|
+
}, file.path, droppedValues)
|
|
15145
|
+
);
|
|
15146
|
+
}
|
|
15147
|
+
const seenEdges = /* @__PURE__ */ new Set();
|
|
15148
|
+
extractEdgesFromLinks(
|
|
15149
|
+
file.path,
|
|
15150
|
+
resolvedId,
|
|
15151
|
+
edgeLinks,
|
|
15152
|
+
pathToResolvedId,
|
|
15153
|
+
bundleRootPathToId,
|
|
15154
|
+
entityId,
|
|
15155
|
+
now,
|
|
15156
|
+
seenEdges,
|
|
15157
|
+
edges,
|
|
15158
|
+
isV3Bundle
|
|
15159
|
+
);
|
|
15160
|
+
}
|
|
15161
|
+
const events = [];
|
|
15162
|
+
if (logContent != null) {
|
|
15163
|
+
const pending = [];
|
|
15164
|
+
const logPath = logMdPath ?? `entities/${entityId}/log.md`;
|
|
15165
|
+
for (const entry of coreOkf.parseLogMd(logContent)) {
|
|
15166
|
+
const { text, eventId } = coreOkf.parseEventIdComment(entry.text);
|
|
15167
|
+
const parsed = parseLogEntryText(text);
|
|
15168
|
+
if (!parsed) continue;
|
|
15169
|
+
let related_entry_id = null;
|
|
15170
|
+
if (parsed.linkPath) {
|
|
15171
|
+
const strippedLink = stripLinkSuffix(decodeLinkPath(parsed.linkPath));
|
|
15172
|
+
let targetPath;
|
|
15173
|
+
if (isV3Bundle) {
|
|
15174
|
+
targetPath = strictTargetPath(logPath, strippedLink);
|
|
15175
|
+
} else if (strippedLink.startsWith("/") && bundleRootPathToId.has(strippedLink.slice(1))) {
|
|
15176
|
+
targetPath = strippedLink.slice(1);
|
|
15177
|
+
} else {
|
|
15178
|
+
targetPath = resolveRelativePath(logPath, strippedLink);
|
|
15179
|
+
}
|
|
15180
|
+
if (!isStructuralPath(targetPath) && targetPath.includes("/facts/")) {
|
|
15181
|
+
related_entry_id = isV3Bundle ? bundleRootPathToId.get(targetPath) ?? null : lookupResolvedId(pathToResolvedId, targetPath) ?? null;
|
|
15182
|
+
}
|
|
15183
|
+
}
|
|
15184
|
+
const created_at = (/* @__PURE__ */ new Date(`${entry.date}T00:00:00.000Z`)).getTime();
|
|
15185
|
+
if (!Number.isFinite(created_at)) continue;
|
|
15186
|
+
if (eventId === void 0) pending.push({ index: events.length, date: entry.date });
|
|
15187
|
+
events.push({
|
|
15188
|
+
id: eventId ?? "",
|
|
15189
|
+
entity_id: entityId,
|
|
15190
|
+
event_type: parsed.event_type,
|
|
15191
|
+
summary: parsed.summary,
|
|
15192
|
+
related_entry_id,
|
|
15193
|
+
created_at
|
|
15194
|
+
});
|
|
15195
|
+
}
|
|
15196
|
+
const taken = new Set(events.map((e) => e.id).filter((id) => id !== ""));
|
|
15197
|
+
const nextOccurrence = /* @__PURE__ */ new Map();
|
|
15198
|
+
for (const { index, date } of pending) {
|
|
15199
|
+
const e = events[index];
|
|
15200
|
+
const key = JSON.stringify([date, e.event_type, replaceLoneSurrogates(e.summary)]);
|
|
15201
|
+
let occurrence = nextOccurrence.get(key) ?? 0;
|
|
15202
|
+
const derive = coreOkf.createEventIdDeriver({ entityId, date, eventType: e.event_type, summary: e.summary });
|
|
15203
|
+
let id = derive(occurrence);
|
|
15204
|
+
while (taken.has(id)) {
|
|
15205
|
+
occurrence += 1;
|
|
15206
|
+
id = derive(occurrence);
|
|
15207
|
+
}
|
|
15208
|
+
taken.add(id);
|
|
15209
|
+
nextOccurrence.set(key, occurrence + 1);
|
|
15210
|
+
e.id = id;
|
|
15211
|
+
}
|
|
15212
|
+
}
|
|
15213
|
+
const okfParseReport = {};
|
|
15214
|
+
if (skippedFiles.length > 0) {
|
|
15215
|
+
okfParseReport.skippedFiles = skippedFiles.slice(0, SKIPPED_FILES_CAP);
|
|
15216
|
+
if (skippedFiles.length > SKIPPED_FILES_CAP) {
|
|
15217
|
+
okfParseReport.skippedFilesOmitted = skippedFiles.length - SKIPPED_FILES_CAP;
|
|
15218
|
+
}
|
|
15219
|
+
}
|
|
15220
|
+
if (droppedValues.length > 0) okfParseReport.droppedValues = droppedValues;
|
|
15221
|
+
return {
|
|
15222
|
+
generatedAt: now,
|
|
15223
|
+
entities: {
|
|
15224
|
+
// §B7: the root-index metadata record (A5) rides the entity object
|
|
15225
|
+
// beside `summary`, so the exportDump/importDump JSON round-trip and
|
|
15226
|
+
// the §B7 `{prefix}meta` persistence carry it. Undefined when the
|
|
15227
|
+
// bundle has no root index; `{}` when it has one without extra keys.
|
|
15228
|
+
[entityId]: {
|
|
15229
|
+
facts,
|
|
15230
|
+
tasks,
|
|
15231
|
+
events,
|
|
15232
|
+
edges,
|
|
15233
|
+
summary: entitySummary,
|
|
15234
|
+
bundleMetadata: profileMeta.metadata
|
|
15235
|
+
}
|
|
15236
|
+
},
|
|
15237
|
+
...droppedPointerValues.length > 0 ? { dropped_pointer_values: droppedPointerValues } : {},
|
|
15238
|
+
...okfParseReport.skippedFiles || okfParseReport.droppedValues ? { okf_parse_report: okfParseReport } : {}
|
|
15239
|
+
};
|
|
15240
|
+
}
|
|
15241
|
+
var OKF_RAW_SLOT = "x-llm-wiki-raw";
|
|
15242
|
+
function matchRawBlockKeyText(line) {
|
|
15243
|
+
const keyMatch = /^(?:"(?:\\.|[^"\\])*"|'(?:''|[^'])*'|[^:]+)/.exec(line);
|
|
15244
|
+
if (!keyMatch || keyMatch[0].length === 0 || line[keyMatch[0].length] !== ":") return null;
|
|
15245
|
+
return keyMatch[0];
|
|
15246
|
+
}
|
|
15247
|
+
function probeParseKey(keyText) {
|
|
15248
|
+
const parsed = coreOkf.parseFrontmatter(`---
|
|
15249
|
+
${keyText}: __probe__
|
|
15250
|
+
---`);
|
|
15251
|
+
const keys = Object.keys(parsed.frontmatter);
|
|
15252
|
+
if (keys[0] !== "type") return keys[0] ?? null;
|
|
15253
|
+
return parsed.frontmatter["type"] === "__probe__" ? "type" : null;
|
|
15254
|
+
}
|
|
15255
|
+
function isValidRawBlockEntry(key, lines, mappedKeys) {
|
|
15256
|
+
if (mappedKeys.has(key) || key === OKF_RAW_SLOT) return false;
|
|
15257
|
+
if (lines.includes("\r")) return false;
|
|
15258
|
+
const allLines = lines.split(/\r?\n/);
|
|
15259
|
+
const first = allLines[0] ?? "";
|
|
15260
|
+
const keyText = matchRawBlockKeyText(first);
|
|
15261
|
+
if (keyText === null || probeParseKey(keyText) !== key) return false;
|
|
15262
|
+
const afterColon = first.slice(keyText.length + 1);
|
|
15263
|
+
const trimmedAfter = afterColon.trim();
|
|
15264
|
+
const blockOpening = trimmedAfter === "" || /^[ \t]/.test(afterColon) && trimmedAfter.startsWith("#");
|
|
15265
|
+
for (const line of allLines.slice(1)) {
|
|
15266
|
+
const trimmed = line.trim();
|
|
15267
|
+
if (trimmed === "---") return false;
|
|
15268
|
+
if (/^[ \t]*#/.test(line)) continue;
|
|
15269
|
+
if (line.trim() === "" || /^[ \t]/.test(line)) continue;
|
|
15270
|
+
if (blockOpening && /^-\s/.test(line)) continue;
|
|
15271
|
+
return false;
|
|
15272
|
+
}
|
|
15273
|
+
try {
|
|
15274
|
+
const { issues } = coreOkf.parseFrontmatter(`---
|
|
15275
|
+
${lines}
|
|
15276
|
+
---`);
|
|
15277
|
+
return !issues.some((issue) => issue.reason === "anchor_or_alias");
|
|
15278
|
+
} catch {
|
|
15279
|
+
return false;
|
|
15280
|
+
}
|
|
15281
|
+
}
|
|
15282
|
+
|
|
15283
|
+
// src/services/importEventStamps.ts
|
|
15284
|
+
var DATE_MAX = 864e13;
|
|
15285
|
+
var DECIMAL_TEXT = /^\s*[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?\s*$/;
|
|
15286
|
+
function createdAtValue(v) {
|
|
15287
|
+
if (typeof v === "number") return v;
|
|
15288
|
+
if (typeof v === "string" && DECIMAL_TEXT.test(v)) return Number(v);
|
|
15289
|
+
return NaN;
|
|
15290
|
+
}
|
|
15291
|
+
function isUsableDate(v) {
|
|
15292
|
+
return Number.isFinite(v) && v >= -DATE_MAX && v <= DATE_MAX;
|
|
15293
|
+
}
|
|
15294
|
+
function parseSourceWatermark(raw) {
|
|
15295
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return null;
|
|
15296
|
+
const { at, id } = raw;
|
|
15297
|
+
if (typeof at !== "number" || !Number.isFinite(at) || typeof id !== "string") return null;
|
|
15298
|
+
return { at, id };
|
|
15299
|
+
}
|
|
15300
|
+
var cmp = (a, b) => a === b ? 0 : a < b ? -1 : 1;
|
|
15301
|
+
function planEventStamps(events, ctx) {
|
|
15302
|
+
const { now, floor, merge, localWm, sourceWm } = ctx;
|
|
15303
|
+
const after = (v, id, wm) => v > wm.at || v === wm.at && id > wm.id;
|
|
15304
|
+
const plan = /* @__PURE__ */ new Map();
|
|
15305
|
+
const restamp = [];
|
|
15306
|
+
for (const e of events) {
|
|
15307
|
+
const v = createdAtValue(e.created_at);
|
|
15308
|
+
const o = createdAtValue(e.occurred_at);
|
|
15309
|
+
let occurredAt = null;
|
|
15310
|
+
let occurredInvalid = false;
|
|
15311
|
+
if (e.occurred_at != null) {
|
|
15312
|
+
if (isUsableDate(o)) occurredAt = Math.trunc(o);
|
|
15313
|
+
else occurredInvalid = true;
|
|
15314
|
+
}
|
|
15315
|
+
let reason = null;
|
|
15316
|
+
const invalidCreated = Number.isNaN(v) || v < -DATE_MAX;
|
|
15317
|
+
if (invalidCreated) reason = "invalid";
|
|
15318
|
+
else if (v > now) reason = "future";
|
|
15319
|
+
else if (merge && localWm !== null && Number.isFinite(localWm.at) && !after(v, e.id, localWm) && (sourceWm === null || after(v, e.id, sourceWm))) {
|
|
15320
|
+
reason = "behind_watermark";
|
|
15321
|
+
}
|
|
15322
|
+
if (reason === "behind_watermark" && occurredAt === null && Number.isFinite(v) && v >= 0) {
|
|
15323
|
+
occurredAt = Math.trunc(v);
|
|
15324
|
+
}
|
|
15325
|
+
const stamp = { createdAt: v, occurredAt, reason };
|
|
15326
|
+
if (reason === null && occurredInvalid) stamp.reason = "invalid";
|
|
15327
|
+
plan.set(e, stamp);
|
|
15328
|
+
if (reason !== null) restamp.push({ e, key: invalidCreated ? -Infinity : v, stamp });
|
|
15329
|
+
}
|
|
15330
|
+
restamp.sort((x, y) => cmp(x.key, y.key) || cmp(x.e.id, y.e.id));
|
|
15331
|
+
if (restamp.length > 0 && floor + restamp.length > Number.MAX_SAFE_INTEGER) {
|
|
15332
|
+
throw new RangeError(`importDump: cannot re-date ${restamp.length} event(s): the floor (${floor}) is too close to Number.MAX_SAFE_INTEGER to keep them ordered.`);
|
|
15333
|
+
}
|
|
15334
|
+
restamp.forEach((x, i) => {
|
|
15335
|
+
x.stamp.createdAt = floor + 1 + i;
|
|
15336
|
+
});
|
|
15337
|
+
return plan;
|
|
15338
|
+
}
|
|
15339
|
+
|
|
15340
|
+
// src/services/ImportExportService.ts
|
|
15341
|
+
var MAX_EMBEDDING_BLOB_BYTES = 32 * 1024;
|
|
15342
|
+
var IMPORT_TITLE_MAX = 500;
|
|
15343
|
+
var IMPORT_BODY_MAX = 8e3;
|
|
15344
|
+
var OKF_EXTRA_MAX_CHARS = 2 * IMPORT_BODY_MAX;
|
|
15345
|
+
var OKF_GENERATED_SLOT = "generated";
|
|
15346
|
+
var BUNDLE_METADATA_OWNED_KEYS = ["okf_version", "profile"];
|
|
15347
|
+
function isStorableScalar(value) {
|
|
15348
|
+
return typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value) || value === null;
|
|
15349
|
+
}
|
|
15350
|
+
function isSerializableWithinBound(value, depth) {
|
|
15351
|
+
if (isStorableScalar(value)) return true;
|
|
15352
|
+
if (Array.isArray(value)) {
|
|
15353
|
+
for (const item of value) {
|
|
15354
|
+
if (isStorableScalar(item)) continue;
|
|
15355
|
+
if (Array.isArray(item)) {
|
|
15356
|
+
if (depth >= 1) return false;
|
|
15357
|
+
if (!isSerializableWithinBound(item, depth + 1)) return false;
|
|
15358
|
+
} else if (typeof item === "object") {
|
|
15359
|
+
if (!isSerializableWithinBound(item, depth)) return false;
|
|
15360
|
+
} else {
|
|
15361
|
+
return false;
|
|
15362
|
+
}
|
|
15363
|
+
}
|
|
15364
|
+
return true;
|
|
15365
|
+
}
|
|
15366
|
+
if (value !== null && typeof value === "object") {
|
|
15367
|
+
for (const member of Object.values(value)) {
|
|
15368
|
+
if (member === void 0) continue;
|
|
15369
|
+
if (isStorableScalar(member)) continue;
|
|
15370
|
+
if (Array.isArray(member) || typeof member === "object") {
|
|
15371
|
+
if (depth >= 1) return false;
|
|
15372
|
+
if (!isSerializableWithinBound(member, depth + 1)) return false;
|
|
15373
|
+
} else {
|
|
15374
|
+
return false;
|
|
15375
|
+
}
|
|
15376
|
+
}
|
|
15377
|
+
return true;
|
|
15378
|
+
}
|
|
15379
|
+
return false;
|
|
15380
|
+
}
|
|
15381
|
+
function plainObjectOrNull(value) {
|
|
15382
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) return null;
|
|
15383
|
+
return value;
|
|
15384
|
+
}
|
|
15385
|
+
function sanitizeRawSlot(value, mappedKeys, reasons) {
|
|
15386
|
+
const slot = plainObjectOrNull(value);
|
|
15387
|
+
if (slot === null) {
|
|
15388
|
+
reasons.push("not_object");
|
|
15389
|
+
return { ok: false };
|
|
15390
|
+
}
|
|
15391
|
+
const clean = {};
|
|
15392
|
+
for (const [entryKey, entryLines] of Object.entries(slot)) {
|
|
15393
|
+
if (entryKey === "__proto__") {
|
|
15394
|
+
reasons.push("raw_block_invalid");
|
|
15395
|
+
continue;
|
|
15396
|
+
}
|
|
15397
|
+
if (typeof entryLines !== "string") {
|
|
15398
|
+
reasons.push("not_object");
|
|
15399
|
+
return { ok: false };
|
|
15400
|
+
}
|
|
15401
|
+
if (entryLines.length > OKF_EXTRA_MAX_CHARS) {
|
|
15402
|
+
reasons.push("raw_block_invalid");
|
|
15403
|
+
continue;
|
|
15404
|
+
}
|
|
15405
|
+
if (isValidRawBlockEntry(entryKey, entryLines, mappedKeys)) clean[entryKey] = entryLines;
|
|
15406
|
+
else reasons.push("raw_block_invalid");
|
|
15407
|
+
}
|
|
15408
|
+
return { ok: true, slot: clean };
|
|
15409
|
+
}
|
|
15410
|
+
function validateOkfExtra(raw, mappedKeys) {
|
|
15411
|
+
if (raw === void 0) return { value: null, reasons: [] };
|
|
15412
|
+
const input = plainObjectOrNull(raw);
|
|
15413
|
+
if (input === null) return { value: null, reasons: ["not_object"] };
|
|
15414
|
+
const mapped = new Set(mappedKeys);
|
|
15415
|
+
const out = {};
|
|
15416
|
+
const reasons = [];
|
|
15417
|
+
for (const [key, value] of Object.entries(input)) {
|
|
15418
|
+
if (key === OKF_RAW_SLOT) {
|
|
15419
|
+
const slot = sanitizeRawSlot(value, mapped, reasons);
|
|
15420
|
+
if (!slot.ok) return { value: null, reasons };
|
|
15421
|
+
if (slot.slot && Object.keys(slot.slot).length > 0) out[OKF_RAW_SLOT] = slot.slot;
|
|
15422
|
+
continue;
|
|
15423
|
+
}
|
|
15424
|
+
if (key === OKF_GENERATED_SLOT) {
|
|
15425
|
+
const plain = plainObjectOrNull(value);
|
|
15426
|
+
if (plain === null || Object.prototype.hasOwnProperty.call(plain, "__proto__")) {
|
|
15427
|
+
reasons.push("not_object");
|
|
15428
|
+
return { value: null, reasons };
|
|
15429
|
+
}
|
|
15430
|
+
out[key] = value;
|
|
15431
|
+
continue;
|
|
15432
|
+
}
|
|
15433
|
+
if (mapped.has(key)) continue;
|
|
15434
|
+
if (key === "__proto__") {
|
|
15435
|
+
reasons.push("raw_block_invalid");
|
|
15436
|
+
continue;
|
|
15437
|
+
}
|
|
15438
|
+
out[key] = value;
|
|
15439
|
+
}
|
|
15440
|
+
if (Object.keys(out).length === 0) return { value: null, reasons };
|
|
15441
|
+
const slotRecord = out[OKF_RAW_SLOT];
|
|
15442
|
+
if (slotRecord) {
|
|
15443
|
+
for (const rk of Object.keys(slotRecord)) {
|
|
15444
|
+
if (rk !== OKF_RAW_SLOT && Object.prototype.hasOwnProperty.call(out, rk)) {
|
|
15445
|
+
delete slotRecord[rk];
|
|
15446
|
+
reasons.push("raw_block_invalid");
|
|
15447
|
+
}
|
|
15448
|
+
}
|
|
15449
|
+
if (Object.keys(slotRecord).length === 0) delete out[OKF_RAW_SLOT];
|
|
15450
|
+
}
|
|
15451
|
+
if (!Object.values(out).every((value) => isSerializableWithinBound(value, 0))) {
|
|
15452
|
+
return { value: null, reasons: [...reasons, "not_serializable"] };
|
|
15453
|
+
}
|
|
15454
|
+
let serialized;
|
|
15455
|
+
try {
|
|
15456
|
+
serialized = JSON.stringify(out) ?? "";
|
|
15457
|
+
} catch {
|
|
15458
|
+
return { value: null, reasons: [...reasons, "not_serializable"] };
|
|
15459
|
+
}
|
|
15460
|
+
if (serialized.length > OKF_EXTRA_MAX_CHARS) return { value: null, reasons: [...reasons, "too_large"] };
|
|
15461
|
+
return { value: out, reasons };
|
|
15462
|
+
}
|
|
15463
|
+
function validateBundleMetadata(raw) {
|
|
15464
|
+
if (raw === void 0) return { value: void 0, reasons: [] };
|
|
15465
|
+
const input = plainObjectOrNull(raw);
|
|
15466
|
+
if (input === null) return { value: void 0, reasons: ["not_object"] };
|
|
15467
|
+
const owned = new Set(BUNDLE_METADATA_OWNED_KEYS);
|
|
15468
|
+
const out = {};
|
|
15469
|
+
const reasons = [];
|
|
15470
|
+
for (const [key, value] of Object.entries(input)) {
|
|
15471
|
+
if (owned.has(key) || key === "__proto__") continue;
|
|
15472
|
+
if (key === OKF_RAW_SLOT) {
|
|
15473
|
+
const slot = sanitizeRawSlot(value, owned, reasons);
|
|
15474
|
+
if (!slot.ok) return { value: void 0, reasons };
|
|
15475
|
+
if (slot.slot && Object.keys(slot.slot).length > 0) out[OKF_RAW_SLOT] = slot.slot;
|
|
15476
|
+
continue;
|
|
15477
|
+
}
|
|
15478
|
+
out[key] = value;
|
|
15479
|
+
}
|
|
15480
|
+
const metaSlot = out[OKF_RAW_SLOT];
|
|
15481
|
+
if (metaSlot) {
|
|
15482
|
+
for (const rk of Object.keys(metaSlot)) {
|
|
15483
|
+
if (rk !== OKF_RAW_SLOT && Object.prototype.hasOwnProperty.call(out, rk)) {
|
|
15484
|
+
delete metaSlot[rk];
|
|
15485
|
+
reasons.push("raw_block_invalid");
|
|
15486
|
+
}
|
|
15487
|
+
}
|
|
15488
|
+
if (Object.keys(metaSlot).length === 0) delete out[OKF_RAW_SLOT];
|
|
15489
|
+
}
|
|
15490
|
+
if (!Object.values(out).every((value) => isSerializableWithinBound(value, 0))) {
|
|
15491
|
+
return { value: void 0, reasons: [...reasons, "not_serializable"] };
|
|
15492
|
+
}
|
|
15493
|
+
let serialized;
|
|
15494
|
+
try {
|
|
15495
|
+
serialized = JSON.stringify(out) ?? "";
|
|
15496
|
+
} catch {
|
|
15497
|
+
return { value: void 0, reasons: [...reasons, "not_serializable"] };
|
|
15498
|
+
}
|
|
15499
|
+
if (serialized.length > OKF_EXTRA_MAX_CHARS) return { value: void 0, reasons: [...reasons, "too_large"] };
|
|
15500
|
+
return { value: out, reasons };
|
|
15501
|
+
}
|
|
15502
|
+
function sanitizeStaleAfterRaw(raw, staleAfter) {
|
|
15503
|
+
if (raw === void 0 || raw === null) return null;
|
|
15504
|
+
if (typeof raw === "string" && raw.trim() === "") return null;
|
|
15505
|
+
if (typeof staleAfter === "number" && Number.isFinite(staleAfter)) return null;
|
|
15506
|
+
let text;
|
|
15507
|
+
if (typeof raw === "string") {
|
|
15508
|
+
text = raw;
|
|
15509
|
+
} else if (typeof raw === "number" || typeof raw === "boolean" || typeof raw === "bigint") {
|
|
15510
|
+
text = String(raw);
|
|
15511
|
+
} else {
|
|
15512
|
+
try {
|
|
15513
|
+
const json = JSON.stringify(raw);
|
|
15514
|
+
text = json === void 0 ? String(raw) : json;
|
|
15515
|
+
} catch {
|
|
15516
|
+
text = String(raw);
|
|
15517
|
+
}
|
|
15518
|
+
}
|
|
15519
|
+
let out = text;
|
|
15520
|
+
if (text.length > IMPORT_TITLE_MAX) {
|
|
15521
|
+
out = text.slice(0, IMPORT_TITLE_MAX);
|
|
15522
|
+
while (out.length > 0 && coreOkf.parseOkfTimestamp(out) !== null) out = out.slice(0, -1);
|
|
15523
|
+
}
|
|
15524
|
+
return out;
|
|
15525
|
+
}
|
|
15526
|
+
function sanitizeStaleAfterPair(raw, staleAfter) {
|
|
15527
|
+
if (typeof staleAfter === "number" && Number.isFinite(staleAfter)) {
|
|
15528
|
+
return { stale_after: staleAfter, stale_after_raw: null };
|
|
15529
|
+
}
|
|
15530
|
+
if (typeof staleAfter === "string") {
|
|
15531
|
+
const parsed = coreOkf.parseOkfTimestamp(staleAfter);
|
|
15532
|
+
if (parsed !== null) return { stale_after: parsed, stale_after_raw: null };
|
|
15533
|
+
const rawText = sanitizeStaleAfterRaw(raw, void 0);
|
|
15534
|
+
if (rawText !== null) return { stale_after: null, stale_after_raw: rawText };
|
|
15535
|
+
return { stale_after: null, stale_after_raw: sanitizeStaleAfterRaw(staleAfter, void 0) };
|
|
15536
|
+
}
|
|
15537
|
+
if (typeof raw === "string" && raw.trim() !== "") {
|
|
15538
|
+
const parsed = coreOkf.parseOkfTimestamp(raw);
|
|
15539
|
+
if (parsed !== null) return { stale_after: parsed, stale_after_raw: null };
|
|
15540
|
+
}
|
|
15541
|
+
if (Array.isArray(staleAfter) && staleAfter.length === 0) {
|
|
15542
|
+
return { stale_after: null, stale_after_raw: sanitizeStaleAfterRaw(raw, staleAfter) };
|
|
15543
|
+
}
|
|
15544
|
+
if (staleAfter !== void 0 && staleAfter !== null) {
|
|
15545
|
+
const fallback = sanitizeStaleAfterRaw(staleAfter, void 0);
|
|
15546
|
+
if (fallback !== null) return { stale_after: null, stale_after_raw: fallback };
|
|
15547
|
+
}
|
|
15548
|
+
return { stale_after: null, stale_after_raw: sanitizeStaleAfterRaw(raw, staleAfter) };
|
|
15549
|
+
}
|
|
15550
|
+
function sanitizeLifecycleStatus(raw) {
|
|
15551
|
+
const clipToBound = (s) => s.length > IMPORT_TITLE_MAX ? s.slice(0, IMPORT_TITLE_MAX) : s;
|
|
15552
|
+
if (raw === void 0 || raw === null || typeof raw === "string" && raw.trim() === "") return "stable";
|
|
15553
|
+
if (typeof raw === "string") return clipToBound(raw);
|
|
15554
|
+
if (typeof raw === "number" || typeof raw === "boolean" || typeof raw === "bigint") return clipToBound(String(raw));
|
|
15555
|
+
try {
|
|
15556
|
+
const json = JSON.stringify(raw);
|
|
15557
|
+
if (json !== void 0) return clipToBound(json);
|
|
15558
|
+
} catch {
|
|
15559
|
+
}
|
|
15560
|
+
return clipToBound(String(raw));
|
|
15561
|
+
}
|
|
15562
|
+
var ImportExportService = class {
|
|
15563
|
+
constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}, vectorRemoval, prefix) {
|
|
15564
|
+
this.db = db;
|
|
15565
|
+
this.entryRepo = entryRepo;
|
|
15566
|
+
this.taskRepo = taskRepo;
|
|
15567
|
+
this.eventRepo = eventRepo;
|
|
15568
|
+
this.edgeRepo = edgeRepo;
|
|
15569
|
+
this.metadataRepo = metadataRepo;
|
|
15570
|
+
this.searchService = searchService;
|
|
15571
|
+
this.jobManager = jobManager;
|
|
15572
|
+
this.embeddingService = embeddingService;
|
|
15573
|
+
this.options = options;
|
|
15574
|
+
this.vectorRemoval = vectorRemoval;
|
|
15575
|
+
this.prefix = prefix;
|
|
15576
|
+
}
|
|
15577
|
+
async exportDump(entityIds, opts) {
|
|
15578
|
+
const includeForgotten = opts?.includeForgotten === true;
|
|
15579
|
+
let ids;
|
|
15580
|
+
if (entityIds && entityIds.length > 0) {
|
|
15581
|
+
ids = Array.from(new Set(entityIds));
|
|
15582
|
+
} else {
|
|
15583
|
+
ids = await this.metadataRepo.getDistinctEntityIds();
|
|
15584
|
+
const prefix = this.storePrefix();
|
|
15585
|
+
if (prefix !== void 0 && await this.storePresent(prefix)) {
|
|
15586
|
+
const rows = await this.db.getAllAsync(
|
|
15587
|
+
`SELECT DISTINCT entity_id FROM ${prefix}source_documents`
|
|
15588
|
+
);
|
|
15589
|
+
ids = Array.from(/* @__PURE__ */ new Set([...ids, ...rows.map((r) => r.entity_id)])).sort();
|
|
15590
|
+
}
|
|
15591
|
+
}
|
|
15592
|
+
const entities = {};
|
|
15593
|
+
const BATCH = 3;
|
|
15594
|
+
for (let i = 0; i < ids.length; i += BATCH) {
|
|
15595
|
+
const batch = ids.slice(i, i + BATCH);
|
|
15596
|
+
const batchResults = await Promise.all(
|
|
15597
|
+
batch.map(
|
|
15598
|
+
async (id) => {
|
|
15599
|
+
const bundle = await this.getFullBundle(id, { includeBlobs: true, includeForgotten });
|
|
15600
|
+
const storedSources = await this.exportStoredSources(id);
|
|
15601
|
+
return [id, storedSources.length > 0 ? { ...bundle, storedSources } : bundle];
|
|
15602
|
+
}
|
|
15603
|
+
)
|
|
15604
|
+
);
|
|
15605
|
+
for (const [id, bundle] of batchResults) {
|
|
15606
|
+
entities[id] = bundle;
|
|
15607
|
+
}
|
|
15608
|
+
}
|
|
15609
|
+
return { generatedAt: Date.now(), entities };
|
|
15610
|
+
}
|
|
15611
|
+
async importDump(dump, opts) {
|
|
15612
|
+
const merge = opts?.merge ?? false;
|
|
15613
|
+
const skippedSources = [];
|
|
15614
|
+
const entityIds = Object.keys(dump.entities);
|
|
15615
|
+
this.jobManager.acquireImportLocks(entityIds);
|
|
15616
|
+
try {
|
|
15617
|
+
await this.assertNoLegacySourceTypes();
|
|
15618
|
+
for (const [entityId, bundle] of Object.entries(dump.entities)) {
|
|
15619
|
+
skippedSources.push(...await this.doImportEntity(entityId, bundle, merge));
|
|
15620
|
+
}
|
|
15621
|
+
} finally {
|
|
15622
|
+
this.jobManager.releaseImportLocks(entityIds);
|
|
15623
|
+
}
|
|
15624
|
+
return { skippedSources };
|
|
15625
|
+
}
|
|
15626
|
+
storePrefix() {
|
|
15627
|
+
return typeof this.prefix === "string" ? this.prefix : void 0;
|
|
15628
|
+
}
|
|
15629
|
+
// `source_ref_index` needs no check: the v9 migration (add_source_ref_index) creates it, and the
|
|
15630
|
+
// store tables come from v17, which only runs after v9 — so it exists whenever they do.
|
|
15631
|
+
async storePresent(prefix, tx) {
|
|
15632
|
+
return await this.metadataRepo.tableExists(`${prefix}source_documents`, tx) && await this.metadataRepo.tableExists(`${prefix}source_passages`, tx);
|
|
15633
|
+
}
|
|
15634
|
+
/** Spec source-store §8: stored sources for one exported entity; [] when none. */
|
|
15635
|
+
async exportStoredSources(entityId) {
|
|
15636
|
+
const prefix = this.storePrefix();
|
|
15637
|
+
if (prefix === void 0 || !await this.storePresent(prefix)) return [];
|
|
15638
|
+
const docs = await this.db.getAllAsync(
|
|
15639
|
+
`SELECT id, source_ref, source_hash, text, text_hash, char_count, created_at FROM ${prefix}source_documents
|
|
15640
|
+
WHERE entity_id = ? ORDER BY source_ref COLLATE BINARY`,
|
|
15641
|
+
[entityId]
|
|
15642
|
+
);
|
|
15643
|
+
const out = [];
|
|
15644
|
+
for (const d of docs) {
|
|
15645
|
+
const ps = await this.db.getAllAsync(
|
|
14476
15646
|
`SELECT seq, start_offset, end_offset FROM ${prefix}source_passages
|
|
14477
15647
|
WHERE entity_id = ? AND document_id = ? ORDER BY seq`,
|
|
14478
15648
|
[entityId, d.id]
|
|
@@ -14534,12 +15704,15 @@ var ImportExportService = class {
|
|
|
14534
15704
|
async getFullBundle(entityId, opts) {
|
|
14535
15705
|
const incl = opts?.includeForgotten ? { includeDeleted: true } : void 0;
|
|
14536
15706
|
const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);
|
|
14537
|
-
const [factsRaw, tasks, events, edges, summaryValue] = await Promise.all([
|
|
15707
|
+
const [factsRaw, tasks, events, edges, summaryValue, bundleMetadataValue] = await Promise.all([
|
|
14538
15708
|
opts?.includeBlobs ? this.entryRepo.findAllByEntityIdWithBlobs(entityId, void 0, incl) : this.entryRepo.findAllByEntityId(entityId, void 0, incl),
|
|
14539
15709
|
this.taskRepo.findAllByEntityId(entityId, void 0, incl),
|
|
14540
15710
|
this.eventRepo.getByEntityId(entityId, opts?.maxEvents, incl),
|
|
14541
15711
|
this.edgeRepo.getByEntityId(entityId),
|
|
14542
|
-
this.metadataRepo.getMeta(entitySummaryMetaKey(entityId))
|
|
15712
|
+
this.metadataRepo.getMeta(entitySummaryMetaKey(entityId)),
|
|
15713
|
+
// §B7: the stored bundle-metadata record rides the entity object back
|
|
15714
|
+
// out, beside the summary.
|
|
15715
|
+
this.metadataRepo.getMeta(bundleMetadataMetaKey(entityId))
|
|
14543
15716
|
]);
|
|
14544
15717
|
const facts = factsRaw.map((f) => {
|
|
14545
15718
|
const {
|
|
@@ -14558,12 +15731,38 @@ var ImportExportService = class {
|
|
|
14558
15731
|
tags: typeof factBase.tags === "string" ? JSON.parse(factBase.tags) : factBase.tags
|
|
14559
15732
|
};
|
|
14560
15733
|
});
|
|
15734
|
+
let bundleMetadata;
|
|
15735
|
+
if (bundleMetadataValue != null) {
|
|
15736
|
+
try {
|
|
15737
|
+
const parsed = JSON.parse(bundleMetadataValue);
|
|
15738
|
+
bundleMetadata = parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
|
|
15739
|
+
if (bundleMetadata === void 0) {
|
|
15740
|
+
emitDiagnostic(this.options, {
|
|
15741
|
+
code: "okf_bundle_metadata_invalid",
|
|
15742
|
+
operation: "exportDump",
|
|
15743
|
+
trigger: "call",
|
|
15744
|
+
entityId,
|
|
15745
|
+
detail: {}
|
|
15746
|
+
});
|
|
15747
|
+
}
|
|
15748
|
+
} catch {
|
|
15749
|
+
bundleMetadata = void 0;
|
|
15750
|
+
emitDiagnostic(this.options, {
|
|
15751
|
+
code: "okf_bundle_metadata_invalid",
|
|
15752
|
+
operation: "exportDump",
|
|
15753
|
+
trigger: "call",
|
|
15754
|
+
entityId,
|
|
15755
|
+
detail: {}
|
|
15756
|
+
});
|
|
15757
|
+
}
|
|
15758
|
+
}
|
|
14561
15759
|
return {
|
|
14562
15760
|
facts,
|
|
14563
15761
|
tasks,
|
|
14564
15762
|
events,
|
|
14565
15763
|
edges,
|
|
14566
15764
|
...summaryValue != null ? { summary: summaryValue } : {},
|
|
15765
|
+
...bundleMetadata != null ? { bundleMetadata } : {},
|
|
14567
15766
|
...wm ? { librarian_watermark: wm } : {}
|
|
14568
15767
|
};
|
|
14569
15768
|
}
|
|
@@ -14571,6 +15770,21 @@ var ImportExportService = class {
|
|
|
14571
15770
|
async doImportEntity(entityId, bundle, merge) {
|
|
14572
15771
|
const skippedSources = [];
|
|
14573
15772
|
const refusalDiagnostics = [];
|
|
15773
|
+
let carriedBundleMetadata;
|
|
15774
|
+
const rawBundleMetadata = bundle.bundleMetadata;
|
|
15775
|
+
if (rawBundleMetadata !== void 0) {
|
|
15776
|
+
const meta = validateBundleMetadata(rawBundleMetadata);
|
|
15777
|
+
for (const reason of meta.reasons) {
|
|
15778
|
+
refusalDiagnostics.push({
|
|
15779
|
+
code: "okf_bundle_metadata_invalid",
|
|
15780
|
+
operation: "importDump",
|
|
15781
|
+
trigger: "call",
|
|
15782
|
+
entityId,
|
|
15783
|
+
detail: { reason }
|
|
15784
|
+
});
|
|
15785
|
+
}
|
|
15786
|
+
carriedBundleMetadata = meta.value;
|
|
15787
|
+
}
|
|
14574
15788
|
const upsertedFactIds = /* @__PURE__ */ new Set();
|
|
14575
15789
|
const liveEmbedFactIds = /* @__PURE__ */ new Set();
|
|
14576
15790
|
const upsertedDeletedFactIds = /* @__PURE__ */ new Set();
|
|
@@ -14603,6 +15817,15 @@ var ImportExportService = class {
|
|
|
14603
15817
|
} else if (!merge) {
|
|
14604
15818
|
await this.metadataRepo.deleteMeta(entitySummaryMetaKey(entityId), tx);
|
|
14605
15819
|
}
|
|
15820
|
+
if (carriedBundleMetadata !== void 0) {
|
|
15821
|
+
await this.metadataRepo.setMeta(
|
|
15822
|
+
bundleMetadataMetaKey(entityId),
|
|
15823
|
+
JSON.stringify(carriedBundleMetadata),
|
|
15824
|
+
tx
|
|
15825
|
+
);
|
|
15826
|
+
} else if (!merge) {
|
|
15827
|
+
await this.metadataRepo.deleteMeta(bundleMetadataMetaKey(entityId), tx);
|
|
15828
|
+
}
|
|
14606
15829
|
const wipedByThisImport = new Set(softDeletedFactIds);
|
|
14607
15830
|
const wipedTasksByThisImport = new Set(softDeletedTaskIds);
|
|
14608
15831
|
const factIds = bundle.facts.map((fact) => fact.id);
|
|
@@ -14725,6 +15948,17 @@ var ImportExportService = class {
|
|
|
14725
15948
|
});
|
|
14726
15949
|
}
|
|
14727
15950
|
const derivedEvents = derivedValidated ?? null;
|
|
15951
|
+
const factExtra = validateOkfExtra(fact.okf_extra, FACT_MAPPED_KEYS);
|
|
15952
|
+
for (const reason of factExtra.reasons) {
|
|
15953
|
+
refusalDiagnostics.push({
|
|
15954
|
+
code: "okf_extra_invalid",
|
|
15955
|
+
operation: "importDump",
|
|
15956
|
+
trigger: "call",
|
|
15957
|
+
entityId,
|
|
15958
|
+
detail: { factId: fact.id, reason }
|
|
15959
|
+
});
|
|
15960
|
+
}
|
|
15961
|
+
const stalePair = sanitizeStaleAfterPair(fact.stale_after_raw, fact.stale_after);
|
|
14728
15962
|
const factObj = {
|
|
14729
15963
|
id: fact.id,
|
|
14730
15964
|
entity_id: entityId,
|
|
@@ -14744,14 +15978,20 @@ var ImportExportService = class {
|
|
|
14744
15978
|
okf_type: fact.okf_type ?? null,
|
|
14745
15979
|
source_pointer: sourcePointer,
|
|
14746
15980
|
...derivedEvents ? { derived_events: derivedEvents } : {},
|
|
14747
|
-
// OKF v0.2 —
|
|
14748
|
-
//
|
|
14749
|
-
|
|
14750
|
-
|
|
15981
|
+
// OKF v0.2 — lifecycle follows §B4 (empty or null is `stable`; a
|
|
15982
|
+
// non-string scalar stores its string form, a list or mapping its
|
|
15983
|
+
// compact JSON text). The other v0.2 fields are forwarded as-is;
|
|
15984
|
+
// parseOkfBundle / the caller is responsible for populating those
|
|
15985
|
+
// per spec.
|
|
15986
|
+
lifecycle_status: sanitizeLifecycleStatus(fact.lifecycle_status),
|
|
15987
|
+
stale_after: stalePair.stale_after,
|
|
14751
15988
|
generated_by: fact.generated_by ?? null,
|
|
14752
15989
|
okf_sources: fact.okf_sources ?? [],
|
|
14753
15990
|
okf_verified: fact.okf_verified ?? [],
|
|
14754
15991
|
okf_usage_window: fact.okf_usage_window ?? null,
|
|
15992
|
+
// OKF v0.3 (§B12) — forwarded through the checks above.
|
|
15993
|
+
okf_extra: factExtra.value,
|
|
15994
|
+
stale_after_raw: stalePair.stale_after_raw,
|
|
14755
15995
|
// last_verified_at/_by are DERIVED mirrors of `okf_verified` per spec
|
|
14756
15996
|
// §5.3. Recomputing here (instead of trusting the payload field) closes
|
|
14757
15997
|
// the invariant that a raw importDump cannot carry a
|
|
@@ -14818,6 +16058,17 @@ var ImportExportService = class {
|
|
|
14818
16058
|
}
|
|
14819
16059
|
if (merge && safeUpdatedAt <= existing.updated_at && task.deleted_at == null) continue;
|
|
14820
16060
|
}
|
|
16061
|
+
const taskExtra = validateOkfExtra(task.okf_extra, TASK_MAPPED_KEYS);
|
|
16062
|
+
for (const reason of taskExtra.reasons) {
|
|
16063
|
+
refusalDiagnostics.push({
|
|
16064
|
+
code: "okf_extra_invalid",
|
|
16065
|
+
operation: "importDump",
|
|
16066
|
+
trigger: "call",
|
|
16067
|
+
entityId,
|
|
16068
|
+
detail: { taskId: task.id, reason }
|
|
16069
|
+
});
|
|
16070
|
+
}
|
|
16071
|
+
const taskStalePair = sanitizeStaleAfterPair(task.stale_after_raw, task.stale_after);
|
|
14821
16072
|
await this.taskRepo.upsertForImport(
|
|
14822
16073
|
{
|
|
14823
16074
|
id: task.id,
|
|
@@ -14830,13 +16081,16 @@ var ImportExportService = class {
|
|
|
14830
16081
|
resolved_at: task.resolved_at,
|
|
14831
16082
|
deleted_at: task.deleted_at,
|
|
14832
16083
|
okf_type: task.okf_type ?? null,
|
|
14833
|
-
// OKF v0.2
|
|
14834
|
-
lifecycle_status: task.lifecycle_status
|
|
14835
|
-
stale_after:
|
|
16084
|
+
// OKF v0.2 — lifecycle follows §B4, as on the fact branch.
|
|
16085
|
+
lifecycle_status: sanitizeLifecycleStatus(task.lifecycle_status),
|
|
16086
|
+
stale_after: taskStalePair.stale_after,
|
|
14836
16087
|
generated_by: task.generated_by ?? null,
|
|
14837
16088
|
okf_sources: task.okf_sources ?? [],
|
|
14838
16089
|
okf_verified: task.okf_verified ?? [],
|
|
14839
16090
|
okf_usage_window: task.okf_usage_window ?? null,
|
|
16091
|
+
// OKF v0.3 (§B12) — forwarded through the checks above.
|
|
16092
|
+
okf_extra: taskExtra.value,
|
|
16093
|
+
stale_after_raw: taskStalePair.stale_after_raw,
|
|
14840
16094
|
// Derived mirrors — see fact branch above; same invariant.
|
|
14841
16095
|
...(() => {
|
|
14842
16096
|
const latest = coreOkf.latestVerified(task.okf_verified ?? [], Date.now());
|
|
@@ -15729,9 +16983,9 @@ var RetrievalService = class {
|
|
|
15729
16983
|
if (maxResults === 0) ; else if (trimmedQuery) {
|
|
15730
16984
|
let usedEmbed = false;
|
|
15731
16985
|
const scoredEntityIds = this._filterScoredEntities(entityIds, sanitizedTierWeights, options?.includeZeroWeightEntities);
|
|
15732
|
-
const
|
|
16986
|
+
const notCurrentIds = excludeDrafts && scoredEntityIds.length > 0 ? await this.entryRepo.findNotCurrentIdsByEntityIds(scoredEntityIds) : EMPTY_ID_SET;
|
|
15733
16987
|
const nonLiveIds = scoredEntityIds.length > 0 ? await this.entryRepo.findNonLiveIdsByEntityIds(scoredEntityIds, liveMode, liveAt) : EMPTY_ID_SET;
|
|
15734
|
-
const excludedIds =
|
|
16988
|
+
const excludedIds = notCurrentIds.size === 0 ? nonLiveIds : nonLiveIds.size === 0 ? notCurrentIds : /* @__PURE__ */ new Set([...notCurrentIds, ...nonLiveIds]);
|
|
15735
16989
|
const excludedPad = excludedIds.size;
|
|
15736
16990
|
const padLimit = (n) => n >= Number.MAX_SAFE_INTEGER ? n : n + excludedPad;
|
|
15737
16991
|
if (scoredEntityIds.length === 0) {
|
|
@@ -16800,6 +18054,7 @@ var LintRepository = class extends BaseRepository {
|
|
|
16800
18054
|
`SELECT
|
|
16801
18055
|
SUM(CASE WHEN okf_type IS NULL THEN 1 ELSE 0 END) AS untyped,
|
|
16802
18056
|
SUM(CASE WHEN lifecycle_status = 'draft' THEN 1 ELSE 0 END) AS drafts,
|
|
18057
|
+
SUM(CASE WHEN lifecycle_status NOT IN ('stable','draft','deprecated') THEN 1 ELSE 0 END) AS unknown_status,
|
|
16803
18058
|
SUM(CASE WHEN source_type = 'librarian_inferred'
|
|
16804
18059
|
AND COALESCE(json_array_length(CASE WHEN json_valid(okf_verified) THEN okf_verified END), 0) = 0
|
|
16805
18060
|
THEN 1 ELSE 0 END) AS unverified
|
|
@@ -16810,6 +18065,7 @@ var LintRepository = class extends BaseRepository {
|
|
|
16810
18065
|
return {
|
|
16811
18066
|
untypedFacts: Number(row?.untyped ?? 0),
|
|
16812
18067
|
drafts: Number(row?.drafts ?? 0),
|
|
18068
|
+
unknownStatus: Number(row?.unknown_status ?? 0),
|
|
16813
18069
|
unverifiedInferred: Number(row?.unverified ?? 0)
|
|
16814
18070
|
};
|
|
16815
18071
|
}
|
|
@@ -16938,8 +18194,21 @@ var OkfTrustWritesRepository = class {
|
|
|
16938
18194
|
* other's events (the previous implementation serialized only the supplied
|
|
16939
18195
|
* array and overwrote, dropping any pre-existing history).
|
|
16940
18196
|
*
|
|
16941
|
-
*
|
|
16942
|
-
*
|
|
18197
|
+
* Each element is rebuilt as `json_patch(old_entry, {by, at})`, not
|
|
18198
|
+
* `json_object('by', …, 'at', …)`, so stored entries keep their `x-` extras
|
|
18199
|
+
* across appends (spec okf-v03 §C landmine, refinement 29).
|
|
18200
|
+
*
|
|
18201
|
+
* Sets the `last_verified_*` convenience columns from the CALLER-PASSED
|
|
18202
|
+
* event list (review T3-tail7 #3 — the columns mirror the append batch,
|
|
18203
|
+
* not the post-merge history: a host that backfills an older event owns
|
|
18204
|
+
* the resulting value).
|
|
18205
|
+
*
|
|
18206
|
+
* Two §B8/§13.4 behaviors worth stating (review T4-R2 #4): the append is a
|
|
18207
|
+
* JSON merge-patch, so a stored event member patched with an absent `by` /
|
|
18208
|
+
* `at` loses that key (merge-patch null-deletes) rather than persisting an
|
|
18209
|
+
* explicit `null`; and every extra key the caller passes on an event rides
|
|
18210
|
+
* the stored JSON verbatim — inline extras for `verified[]` are the
|
|
18211
|
+
* documented §13.4 home, validated only by the §A3c wire bound at import.
|
|
16943
18212
|
*/
|
|
16944
18213
|
async writeOkfTrust(entryId, entityId, verified, tx) {
|
|
16945
18214
|
const executor = this.getExecutor(tx);
|
|
@@ -16949,13 +18218,15 @@ var OkfTrustWritesRepository = class {
|
|
|
16949
18218
|
await executor.runAsync(
|
|
16950
18219
|
`UPDATE ${this.prefix}entries
|
|
16951
18220
|
SET okf_verified = COALESCE(
|
|
16952
|
-
(SELECT json_group_array(json_object('by', s.by_val, 'at', s.at_val))
|
|
18221
|
+
(SELECT json_group_array(json_patch(s.old_entry, json_object('by', s.by_val, 'at', s.at_val)))
|
|
16953
18222
|
FROM (
|
|
16954
|
-
SELECT
|
|
18223
|
+
SELECT value AS old_entry,
|
|
18224
|
+
json_extract(value, '$.by') AS by_val,
|
|
16955
18225
|
json_extract(value, '$.at') AS at_val
|
|
16956
18226
|
FROM json_each(okf_verified)
|
|
16957
18227
|
UNION ALL
|
|
16958
|
-
SELECT
|
|
18228
|
+
SELECT value,
|
|
18229
|
+
json_extract(value, '$.by'),
|
|
16959
18230
|
json_extract(value, '$.at')
|
|
16960
18231
|
FROM json_each(?)
|
|
16961
18232
|
) AS s
|
|
@@ -16989,12 +18260,19 @@ var OkfTrustWritesRepository = class {
|
|
|
16989
18260
|
[status, entryId, entityId]
|
|
16990
18261
|
);
|
|
16991
18262
|
}
|
|
16992
|
-
/**
|
|
18263
|
+
/**
|
|
18264
|
+
* Set the absolute cutoff (epoch ms) for staleness, or NULL to clear.
|
|
18265
|
+
* §B3 mutual exclusivity (owner review fix 5): a valid cutoff clears
|
|
18266
|
+
* `stale_after_raw` — an old unparseable value must never survive a later
|
|
18267
|
+
* valid write and pin `isStale` true forever — and clearing NULLs both.
|
|
18268
|
+
* Does NOT touch `updated_at`.
|
|
18269
|
+
*/
|
|
16993
18270
|
async setStaleAfter(entryId, entityId, date, tx) {
|
|
16994
18271
|
const executor = this.getExecutor(tx);
|
|
16995
18272
|
await executor.runAsync(
|
|
16996
18273
|
`UPDATE ${this.prefix}entries
|
|
16997
|
-
SET stale_after =
|
|
18274
|
+
SET stale_after = ?,
|
|
18275
|
+
stale_after_raw = NULL
|
|
16998
18276
|
WHERE id = ? AND entity_id = ?`,
|
|
16999
18277
|
[date, entryId, entityId]
|
|
17000
18278
|
);
|
|
@@ -17020,13 +18298,15 @@ var OkfTrustWritesRepository = class {
|
|
|
17020
18298
|
await executor.runAsync(
|
|
17021
18299
|
`UPDATE ${this.prefix}tasks
|
|
17022
18300
|
SET okf_verified = COALESCE(
|
|
17023
|
-
(SELECT json_group_array(json_object('by', s.by_val, 'at', s.at_val))
|
|
18301
|
+
(SELECT json_group_array(json_patch(s.old_entry, json_object('by', s.by_val, 'at', s.at_val)))
|
|
17024
18302
|
FROM (
|
|
17025
|
-
SELECT
|
|
18303
|
+
SELECT value AS old_entry,
|
|
18304
|
+
json_extract(value, '$.by') AS by_val,
|
|
17026
18305
|
json_extract(value, '$.at') AS at_val
|
|
17027
18306
|
FROM json_each(okf_verified)
|
|
17028
18307
|
UNION ALL
|
|
17029
|
-
SELECT
|
|
18308
|
+
SELECT value,
|
|
18309
|
+
json_extract(value, '$.by'),
|
|
17030
18310
|
json_extract(value, '$.at')
|
|
17031
18311
|
FROM json_each(?)
|
|
17032
18312
|
) AS s
|
|
@@ -17058,11 +18338,13 @@ var OkfTrustWritesRepository = class {
|
|
|
17058
18338
|
[status, taskId, entityId]
|
|
17059
18339
|
);
|
|
17060
18340
|
}
|
|
18341
|
+
/** Task variant of {@link setStaleAfter} — §B3 pair exclusivity included. */
|
|
17061
18342
|
async setStaleAfterTask(taskId, entityId, date, tx) {
|
|
17062
18343
|
const executor = this.getExecutor(tx);
|
|
17063
18344
|
await executor.runAsync(
|
|
17064
18345
|
`UPDATE ${this.prefix}tasks
|
|
17065
|
-
SET stale_after =
|
|
18346
|
+
SET stale_after = ?,
|
|
18347
|
+
stale_after_raw = NULL
|
|
17066
18348
|
WHERE id = ? AND entity_id = ?`,
|
|
17067
18349
|
[date, taskId, entityId]
|
|
17068
18350
|
);
|
|
@@ -17079,7 +18361,7 @@ var OkfTrustWritesRepository = class {
|
|
|
17079
18361
|
};
|
|
17080
18362
|
|
|
17081
18363
|
// src/utils/rememberInput.ts
|
|
17082
|
-
var
|
|
18364
|
+
var CONFIDENCE_VALUES2 = /* @__PURE__ */ new Set(["certain", "inferred", "tentative"]);
|
|
17083
18365
|
var SOURCE_TYPE_VALUES = /* @__PURE__ */ new Set(["user_stated", "user_confirmed"]);
|
|
17084
18366
|
function normalizeRememberInput(entityId, input, now) {
|
|
17085
18367
|
assertEntityId(entityId);
|
|
@@ -17105,7 +18387,7 @@ function normalizeRememberInput(entityId, input, now) {
|
|
|
17105
18387
|
tags = [...input.tags];
|
|
17106
18388
|
}
|
|
17107
18389
|
const confidence = input.confidence === void 0 ? "certain" : input.confidence;
|
|
17108
|
-
if (!
|
|
18390
|
+
if (!CONFIDENCE_VALUES2.has(confidence)) {
|
|
17109
18391
|
throw new TypeError(`remember(): input.confidence must be certain | inferred | tentative; got ${JSON.stringify(input.confidence)}.`);
|
|
17110
18392
|
}
|
|
17111
18393
|
const sourceType = input.source_type === void 0 ? "user_stated" : input.source_type;
|
|
@@ -18363,1050 +19645,733 @@ var WikiMemory = class {
|
|
|
18363
19645
|
const after = options?.cursor === void 0 ? null : decodeDraftCursor(options.cursor);
|
|
18364
19646
|
const rows = await this.entryRepo.listDraftsByEntityId(entityId, limit + 1, after);
|
|
18365
19647
|
const facts = rows.slice(0, limit);
|
|
18366
|
-
const last = facts[facts.length - 1];
|
|
18367
|
-
return {
|
|
18368
|
-
facts,
|
|
18369
|
-
nextCursor: rows.length > limit && last ? `${last.created_at}:${last.id}` : null
|
|
18370
|
-
};
|
|
18371
|
-
}
|
|
18372
|
-
/**
|
|
18373
|
-
* Promote a draft to `stable` and record who reviewed it, atomically
|
|
18374
|
-
* (spec §5.2). Metadata writes only: `updated_at` is not bumped and no
|
|
18375
|
-
* outbox event is pushed. Pass `by: 'human:<id>'` so `trustTier` becomes
|
|
18376
|
-
* `'human-reviewed'`.
|
|
18377
|
-
*
|
|
18378
|
-
* @throws WikiDraftNotFound when no live draft with that id exists for the entity.
|
|
18379
|
-
*/
|
|
18380
|
-
async promoteDraft(entryId, entityId, reviewer) {
|
|
18381
|
-
const by = reviewer?.by;
|
|
18382
|
-
if (typeof by !== "string" || by.trim().length === 0) {
|
|
18383
|
-
throw new TypeError("promoteDraft requires reviewer.by to be a non-empty string.");
|
|
18384
|
-
}
|
|
18385
|
-
await this.db.withTransactionAsync(async (tx) => {
|
|
18386
|
-
if (!await this.entryRepo.isLiveDraft(entryId, entityId, tx)) {
|
|
18387
|
-
throw new WikiDraftNotFound();
|
|
18388
|
-
}
|
|
18389
|
-
await this.okfTrustWrites.setLifecycleStatus(entryId, entityId, "stable", tx);
|
|
18390
|
-
await this.okfTrustWrites.writeOkfTrust(entryId, entityId, [{ by, at: (/* @__PURE__ */ new Date()).toISOString() }], tx);
|
|
18391
|
-
});
|
|
18392
|
-
}
|
|
18393
|
-
/** Set a fact's stale_after (epoch ms) or clear it. Does NOT touch `updated_at`. */
|
|
18394
|
-
async setStaleAfter(entryId, entityId, date) {
|
|
18395
|
-
return this.okfTrustWrites.setStaleAfter(entryId, entityId, date);
|
|
18396
|
-
}
|
|
18397
|
-
/** Set a fact's generated_by actor string. Does NOT touch `updated_at`. */
|
|
18398
|
-
async setGeneratedBy(entryId, entityId, actor) {
|
|
18399
|
-
return this.okfTrustWrites.setGeneratedBy(entryId, entityId, actor);
|
|
18400
|
-
}
|
|
18401
|
-
/** Task variants of the same five DAO methods. Symmetric per spec §2.5. */
|
|
18402
|
-
async writeOkfTrustTask(taskId, entityId, verified) {
|
|
18403
|
-
return this.okfTrustWrites.writeOkfTrustTask(taskId, entityId, verified);
|
|
18404
|
-
}
|
|
18405
|
-
async writeOkfSourcesTask(taskId, entityId, sources) {
|
|
18406
|
-
return this.okfTrustWrites.writeOkfSourcesTask(taskId, entityId, sources);
|
|
18407
|
-
}
|
|
18408
|
-
async setLifecycleStatusTask(taskId, entityId, status) {
|
|
18409
|
-
return this.okfTrustWrites.setLifecycleStatusTask(taskId, entityId, status);
|
|
18410
|
-
}
|
|
18411
|
-
async setStaleAfterTask(taskId, entityId, date) {
|
|
18412
|
-
return this.okfTrustWrites.setStaleAfterTask(taskId, entityId, date);
|
|
18413
|
-
}
|
|
18414
|
-
async setGeneratedByTask(taskId, entityId, actor) {
|
|
18415
|
-
return this.okfTrustWrites.setGeneratedByTask(taskId, entityId, actor);
|
|
18416
|
-
}
|
|
18417
|
-
};
|
|
18418
|
-
_testAccessNonTestEnvWarned = new WeakMap();
|
|
18419
|
-
/** Max upsertGraph node and superseded-fact ids held for their post-commit sync (spec #280 id threading). */
|
|
18420
|
-
WikiMemory.UPSERT_ID_STASH_CAP = 1e4;
|
|
18421
|
-
/** Max superseded-fact ids held for post-commit removal delivery. */
|
|
18422
|
-
WikiMemory.REMOVAL_STASH_CAP = 1e4;
|
|
18423
|
-
function assertEntityId2(entityId) {
|
|
18424
|
-
if (typeof entityId !== "string" || entityId.length === 0) {
|
|
18425
|
-
throw new TypeError("Invalid entityId: must be a non-empty string.");
|
|
18426
|
-
}
|
|
18427
|
-
}
|
|
18428
|
-
|
|
18429
|
-
// src/utils/formatContext.ts
|
|
18430
|
-
function validateMaxOption(value, name) {
|
|
18431
|
-
if (!isFinite(value) || value < 0) {
|
|
18432
|
-
throw new Error(`Invalid ${name}: must be a non-negative finite number`);
|
|
18433
|
-
}
|
|
18434
|
-
}
|
|
18435
|
-
var CONFIDENCE_WEIGHT = {
|
|
18436
|
-
certain: 1,
|
|
18437
|
-
inferred: 0.6,
|
|
18438
|
-
tentative: 0.3
|
|
18439
|
-
};
|
|
18440
|
-
function scoreFactFor(fact, weights, now) {
|
|
18441
|
-
const confW = CONFIDENCE_WEIGHT[fact.confidence] ?? 0.3;
|
|
18442
|
-
const ageDays = (now - fact.updated_at) / 864e5;
|
|
18443
|
-
const recencyDecay = Math.exp(-ageDays / 30);
|
|
18444
|
-
return confW * weights.confidence + Math.log(1 + fact.access_count) * weights.accessCount + recencyDecay * weights.recency;
|
|
18445
|
-
}
|
|
18446
|
-
function renderFactMarkdown(fact, includeConfidence, includeTags, includeEntityIds, score) {
|
|
18447
|
-
const confPart = includeConfidence ? ` (${fact.confidence})` : "";
|
|
18448
|
-
const tagPart = includeTags && fact.tags.length > 0 ? ` [${fact.tags.join(", ")}]` : "";
|
|
18449
|
-
const sourcePart = includeEntityIds ? ` {entity_id=${fact.entity_id}}` : "";
|
|
18450
|
-
const scorePart = score !== void 0 ? ` {score=${score.toFixed(4)}}` : "";
|
|
18451
|
-
return `- **${fact.title}**${confPart}${tagPart}${sourcePart}${scorePart}
|
|
18452
|
-
${fact.body.replace(/\n/g, "\n ")}`;
|
|
18453
|
-
}
|
|
18454
|
-
function renderFactPlain(fact, includeConfidence, includeTags, includeEntityIds, score) {
|
|
18455
|
-
const confPart = includeConfidence ? ` (${fact.confidence})` : "";
|
|
18456
|
-
const tagPart = includeTags && fact.tags.length > 0 ? ` [${fact.tags.join(", ")}]` : "";
|
|
18457
|
-
const sourcePart = includeEntityIds ? ` {entity_id=${fact.entity_id}}` : "";
|
|
18458
|
-
const scorePart = score !== void 0 ? ` {score=${score.toFixed(4)}}` : "";
|
|
18459
|
-
return `${fact.title}${confPart}${tagPart}${sourcePart}${scorePart}: ${fact.body}`;
|
|
18460
|
-
}
|
|
18461
|
-
function renderTaskMarkdown(task) {
|
|
18462
|
-
return `- [P${task.priority}] ${task.description.replace(/\n/g, "\n ")} (${task.status})`;
|
|
18463
|
-
}
|
|
18464
|
-
function renderTaskPlain(task) {
|
|
18465
|
-
return `[P${task.priority}] ${task.description} (${task.status})`;
|
|
18466
|
-
}
|
|
18467
|
-
function renderEventMarkdown(event) {
|
|
18468
|
-
const ts = new Date(event.created_at).toISOString();
|
|
18469
|
-
return `- [${event.event_type} @ ${ts}] ${event.summary.replace(/\n/g, "\n ")}`;
|
|
18470
|
-
}
|
|
18471
|
-
function renderEventPlain(event) {
|
|
18472
|
-
const ts = new Date(event.created_at).toISOString();
|
|
18473
|
-
return `[${event.event_type} @ ${ts}] ${event.summary}`;
|
|
18474
|
-
}
|
|
18475
|
-
function renderSourceLabel(p, includeEntityId) {
|
|
18476
|
-
const entity = includeEntityId ? `${p.entityId} ` : "";
|
|
18477
|
-
return `${entity}${p.sourceRef} #${p.seq}${p.truncated ? " (excerpt)" : ""}`;
|
|
18478
|
-
}
|
|
18479
|
-
function formatContext(bundle, options) {
|
|
18480
|
-
const opts = {
|
|
18481
|
-
format: options?.format ?? "markdown",
|
|
18482
|
-
maxFacts: options?.maxFacts ?? 10,
|
|
18483
|
-
maxTasks: options?.maxTasks ?? 10,
|
|
18484
|
-
maxEvents: options?.maxEvents ?? 10,
|
|
18485
|
-
includeConfidence: !(options?.compact ?? false) && (options?.includeConfidence ?? true),
|
|
18486
|
-
includeTags: !(options?.compact ?? false) && (options?.includeTags ?? true),
|
|
18487
|
-
includeEntityIds: !(options?.compact ?? false) && (options?.includeEntityIds ?? false),
|
|
18488
|
-
includeFactScores: !(options?.compact ?? false) && (options?.includeFactScores ?? false),
|
|
18489
|
-
compact: options?.compact ?? false,
|
|
18490
|
-
factWeights: {
|
|
18491
|
-
confidence: options?.factWeights?.confidence ?? 1,
|
|
18492
|
-
accessCount: options?.factWeights?.accessCount ?? 0.3,
|
|
18493
|
-
recency: options?.factWeights?.recency ?? 0.5
|
|
18494
|
-
}
|
|
18495
|
-
};
|
|
18496
|
-
validateMaxOption(opts.maxFacts, "maxFacts");
|
|
18497
|
-
validateMaxOption(opts.maxTasks, "maxTasks");
|
|
18498
|
-
validateMaxOption(opts.maxEvents, "maxEvents");
|
|
18499
|
-
const weights = opts.factWeights;
|
|
18500
|
-
const now = Date.now();
|
|
18501
|
-
const sortedFacts = bundle.factScores ? [...bundle.facts].slice(0, opts.maxFacts) : [...bundle.facts].sort((a, b) => scoreFactFor(b, weights, now) - scoreFactFor(a, weights, now)).slice(0, opts.maxFacts);
|
|
18502
|
-
const sortedTasks = [...bundle.tasks].sort((a, b) => b.priority - a.priority || a.created_at - b.created_at).slice(0, opts.maxTasks);
|
|
18503
|
-
const sortedEvents = [...bundle.events].sort((a, b) => b.created_at - a.created_at).slice(0, opts.maxEvents);
|
|
18504
|
-
const sources = bundle.sources ?? [];
|
|
18505
|
-
if (sortedFacts.length === 0 && sortedTasks.length === 0 && sortedEvents.length === 0 && sources.length === 0) {
|
|
18506
|
-
return "";
|
|
18507
|
-
}
|
|
18508
|
-
const isMarkdown = opts.format === "markdown";
|
|
18509
|
-
const lines = [];
|
|
18510
|
-
if (isMarkdown) {
|
|
18511
|
-
lines.push("## Memory");
|
|
18512
|
-
if (sortedFacts.length > 0) {
|
|
18513
|
-
lines.push("");
|
|
18514
|
-
lines.push("### Known Facts");
|
|
18515
|
-
for (const fact of sortedFacts) {
|
|
18516
|
-
lines.push(renderFactMarkdown(fact, opts.includeConfidence, opts.includeTags, opts.includeEntityIds, opts.includeFactScores ? bundle.factScores?.[fact.id] : void 0));
|
|
18517
|
-
}
|
|
18518
|
-
}
|
|
18519
|
-
if (sortedTasks.length > 0) {
|
|
18520
|
-
lines.push("");
|
|
18521
|
-
lines.push("### Open Tasks");
|
|
18522
|
-
for (const task of sortedTasks) {
|
|
18523
|
-
lines.push(renderTaskMarkdown(task));
|
|
18524
|
-
}
|
|
18525
|
-
}
|
|
18526
|
-
if (sortedEvents.length > 0) {
|
|
18527
|
-
lines.push("");
|
|
18528
|
-
lines.push("### Recent Events");
|
|
18529
|
-
for (const event of sortedEvents) {
|
|
18530
|
-
lines.push(renderEventMarkdown(event));
|
|
18531
|
-
}
|
|
18532
|
-
}
|
|
18533
|
-
if (sources.length > 0) {
|
|
18534
|
-
lines.push("");
|
|
18535
|
-
lines.push("### Sources");
|
|
18536
|
-
for (const p of sources) {
|
|
18537
|
-
lines.push(`- [${renderSourceLabel(p, opts.includeEntityIds)}] ${p.text.replace(/\n/g, "\n ")}`);
|
|
18538
|
-
}
|
|
18539
|
-
}
|
|
18540
|
-
} else {
|
|
18541
|
-
if (sortedFacts.length > 0) {
|
|
18542
|
-
lines.push("KNOWN FACTS:");
|
|
18543
|
-
for (const fact of sortedFacts) {
|
|
18544
|
-
lines.push(renderFactPlain(fact, opts.includeConfidence, opts.includeTags, opts.includeEntityIds, opts.includeFactScores ? bundle.factScores?.[fact.id] : void 0));
|
|
18545
|
-
}
|
|
18546
|
-
}
|
|
18547
|
-
if (sortedTasks.length > 0) {
|
|
18548
|
-
lines.push("OPEN TASKS:");
|
|
18549
|
-
for (const task of sortedTasks) {
|
|
18550
|
-
lines.push(renderTaskPlain(task));
|
|
18551
|
-
}
|
|
18552
|
-
}
|
|
18553
|
-
if (sortedEvents.length > 0) {
|
|
18554
|
-
lines.push("RECENT EVENTS:");
|
|
18555
|
-
for (const event of sortedEvents) {
|
|
18556
|
-
lines.push(renderEventPlain(event));
|
|
18557
|
-
}
|
|
19648
|
+
const last = facts[facts.length - 1];
|
|
19649
|
+
return {
|
|
19650
|
+
facts,
|
|
19651
|
+
nextCursor: rows.length > limit && last ? `${last.created_at}:${last.id}` : null
|
|
19652
|
+
};
|
|
19653
|
+
}
|
|
19654
|
+
/**
|
|
19655
|
+
* Promote a draft to `stable` and record who reviewed it, atomically
|
|
19656
|
+
* (spec §5.2). Metadata writes only: `updated_at` is not bumped and no
|
|
19657
|
+
* outbox event is pushed. Pass `by: 'human:<id>'` so `trustTier` becomes
|
|
19658
|
+
* `'human-reviewed'`.
|
|
19659
|
+
*
|
|
19660
|
+
* @throws WikiDraftNotFound when no live draft with that id exists for the entity.
|
|
19661
|
+
*/
|
|
19662
|
+
async promoteDraft(entryId, entityId, reviewer) {
|
|
19663
|
+
const by = reviewer?.by;
|
|
19664
|
+
if (typeof by !== "string" || by.trim().length === 0) {
|
|
19665
|
+
throw new TypeError("promoteDraft requires reviewer.by to be a non-empty string.");
|
|
18558
19666
|
}
|
|
18559
|
-
|
|
18560
|
-
|
|
18561
|
-
|
|
18562
|
-
lines.push(`[${renderSourceLabel(p, opts.includeEntityIds)}] ${p.text}`);
|
|
19667
|
+
await this.db.withTransactionAsync(async (tx) => {
|
|
19668
|
+
if (!await this.entryRepo.isLiveDraft(entryId, entityId, tx)) {
|
|
19669
|
+
throw new WikiDraftNotFound();
|
|
18563
19670
|
}
|
|
18564
|
-
|
|
19671
|
+
await this.okfTrustWrites.setLifecycleStatus(entryId, entityId, "stable", tx);
|
|
19672
|
+
await this.okfTrustWrites.writeOkfTrust(entryId, entityId, [{ by, at: (/* @__PURE__ */ new Date()).toISOString() }], tx);
|
|
19673
|
+
});
|
|
18565
19674
|
}
|
|
18566
|
-
|
|
18567
|
-
|
|
18568
|
-
|
|
18569
|
-
// src/utils/formatGraphContext.ts
|
|
18570
|
-
function formatGraphContext(neighborhood) {
|
|
18571
|
-
const { nodes, edges } = neighborhood;
|
|
18572
|
-
if (nodes.length === 0) return "";
|
|
18573
|
-
const nodeById = new Map(nodes.map((n) => [n.id, n]));
|
|
18574
|
-
const nodeIndex = new Map(nodes.map((n, i) => [n.id, i]));
|
|
18575
|
-
const lines = [];
|
|
18576
|
-
for (const node of nodes) {
|
|
18577
|
-
lines.push(`[${node.okf_type ?? "fact"}] ${node.title} (ID: ${node.id})`);
|
|
18578
|
-
const outbound = edgesByDirection(edges, node.id, "source_id", nodeById, nodeIndex);
|
|
18579
|
-
const inbound = edgesByDirection(edges, node.id, "target_id", nodeById, nodeIndex);
|
|
18580
|
-
for (const { edge, other } of outbound) {
|
|
18581
|
-
lines.push(` -[${edge.edge_type}]-> [${other.okf_type ?? "fact"}] ${other.title}`);
|
|
18582
|
-
}
|
|
18583
|
-
for (const { edge, other } of inbound) {
|
|
18584
|
-
lines.push(` <-[${edge.edge_type}]- [${other.okf_type ?? "fact"}] ${other.title}`);
|
|
18585
|
-
}
|
|
19675
|
+
/** Set a fact's stale_after (epoch ms) or clear it. Does NOT touch `updated_at`. */
|
|
19676
|
+
async setStaleAfter(entryId, entityId, date) {
|
|
19677
|
+
return this.okfTrustWrites.setStaleAfter(entryId, entityId, date);
|
|
18586
19678
|
}
|
|
18587
|
-
|
|
18588
|
-
|
|
18589
|
-
|
|
18590
|
-
const otherEndpoint = endpoint === "source_id" ? "target_id" : "source_id";
|
|
18591
|
-
return edges.filter((e) => e[endpoint] === nodeId).filter((e) => {
|
|
18592
|
-
const otherId = e[otherEndpoint];
|
|
18593
|
-
const selfIdx = nodeIndex.get(nodeId);
|
|
18594
|
-
const otherIdx = nodeIndex.get(otherId);
|
|
18595
|
-
return otherIdx !== void 0 && selfIdx < otherIdx;
|
|
18596
|
-
}).map((edge) => ({ edge, other: nodeById.get(edge[otherEndpoint]) })).sort(
|
|
18597
|
-
(a, b) => a.edge.edge_type.localeCompare(b.edge.edge_type) || a.other.title.localeCompare(b.other.title) || a.other.id.localeCompare(b.other.id) || a.edge.id.localeCompare(b.edge.id)
|
|
18598
|
-
);
|
|
18599
|
-
}
|
|
18600
|
-
|
|
18601
|
-
// src/utils/sanitizeForFilename.ts
|
|
18602
|
-
function shortHash(value) {
|
|
18603
|
-
let h1 = 5381;
|
|
18604
|
-
let h2 = 52711;
|
|
18605
|
-
for (let i = 0; i < value.length; i += 1) {
|
|
18606
|
-
const c = value.charCodeAt(i);
|
|
18607
|
-
h1 = Math.imul(h1, 33) ^ c;
|
|
18608
|
-
h2 = Math.imul(h2, 31) ^ c;
|
|
19679
|
+
/** Set a fact's generated_by actor string. Does NOT touch `updated_at`. */
|
|
19680
|
+
async setGeneratedBy(entryId, entityId, actor) {
|
|
19681
|
+
return this.okfTrustWrites.setGeneratedBy(entryId, entityId, actor);
|
|
18609
19682
|
}
|
|
18610
|
-
|
|
18611
|
-
|
|
18612
|
-
|
|
18613
|
-
var WINDOWS_RESERVED_NAMES = /* @__PURE__ */ new Set([
|
|
18614
|
-
"con",
|
|
18615
|
-
"prn",
|
|
18616
|
-
"aux",
|
|
18617
|
-
"nul",
|
|
18618
|
-
"com1",
|
|
18619
|
-
"com2",
|
|
18620
|
-
"com3",
|
|
18621
|
-
"com4",
|
|
18622
|
-
"com5",
|
|
18623
|
-
"com6",
|
|
18624
|
-
"com7",
|
|
18625
|
-
"com8",
|
|
18626
|
-
"com9",
|
|
18627
|
-
"lpt1",
|
|
18628
|
-
"lpt2",
|
|
18629
|
-
"lpt3",
|
|
18630
|
-
"lpt4",
|
|
18631
|
-
"lpt5",
|
|
18632
|
-
"lpt6",
|
|
18633
|
-
"lpt7",
|
|
18634
|
-
"lpt8",
|
|
18635
|
-
"lpt9"
|
|
18636
|
-
]);
|
|
18637
|
-
function isWindowsReservedName(name) {
|
|
18638
|
-
const base = name.split(".")[0];
|
|
18639
|
-
return WINDOWS_RESERVED_NAMES.has(base.toLowerCase());
|
|
18640
|
-
}
|
|
18641
|
-
function sanitizeForFilename(value) {
|
|
18642
|
-
const normalized = value.normalize("NFKC");
|
|
18643
|
-
const sanitized = normalized.replace(/[^A-Za-z0-9._-]+/g, "_").replace(/^\.+/, "_").replace(/_+/g, "_").replace(/^[_-]+|[_-]+$/g, "");
|
|
18644
|
-
const MAX_BASE = 200;
|
|
18645
|
-
const trimmed = sanitized.length > MAX_BASE ? sanitized.slice(0, MAX_BASE) : sanitized;
|
|
18646
|
-
let baseName = trimmed && trimmed !== "." && trimmed !== ".." ? trimmed : "entity";
|
|
18647
|
-
const withoutTrailingDotSpace = baseName.replace(/[. ]+$/, "");
|
|
18648
|
-
const hadTrailingDotSpace = withoutTrailingDotSpace !== baseName;
|
|
18649
|
-
if (hadTrailingDotSpace) {
|
|
18650
|
-
baseName = withoutTrailingDotSpace || "entity";
|
|
19683
|
+
/** Task variants of the same five DAO methods. Symmetric per spec §2.5. */
|
|
19684
|
+
async writeOkfTrustTask(taskId, entityId, verified) {
|
|
19685
|
+
return this.okfTrustWrites.writeOkfTrustTask(taskId, entityId, verified);
|
|
18651
19686
|
}
|
|
18652
|
-
|
|
18653
|
-
|
|
18654
|
-
if (!needsSuffix) return baseName;
|
|
18655
|
-
const suffix = `-${shortHash(value)}`;
|
|
18656
|
-
return `${baseName}${suffix}`;
|
|
18657
|
-
}
|
|
18658
|
-
function sanitizeConceptId(id) {
|
|
18659
|
-
const sanitized = sanitizeForFilename(id);
|
|
18660
|
-
if (OKF_RESERVED_CONCEPT_NAMES.has(sanitized.toLowerCase())) {
|
|
18661
|
-
return `${sanitized}-${shortHash(id)}`;
|
|
19687
|
+
async writeOkfSourcesTask(taskId, entityId, sources) {
|
|
19688
|
+
return this.okfTrustWrites.writeOkfSourcesTask(taskId, entityId, sources);
|
|
18662
19689
|
}
|
|
18663
|
-
|
|
18664
|
-
|
|
18665
|
-
|
|
18666
|
-
// src/utils/formatMemoryDump.ts
|
|
18667
|
-
function renderFact(f) {
|
|
18668
|
-
const tags = (f.tags || []).join(", ");
|
|
18669
|
-
const source = f.source_ref ?? f.source_type;
|
|
18670
|
-
return `### ${f.title}
|
|
18671
|
-
**Tags:** ${tags}
|
|
18672
|
-
**Confidence:** ${f.confidence}
|
|
18673
|
-
**Source:** ${source}
|
|
18674
|
-
|
|
18675
|
-
${f.body}
|
|
18676
|
-
|
|
18677
|
-
---
|
|
18678
|
-
`;
|
|
18679
|
-
}
|
|
18680
|
-
function renderTask(t) {
|
|
18681
|
-
const checked = t.status === "done" ? "x" : " ";
|
|
18682
|
-
const note = t.status === "done" ? " (done)" : t.status === "abandoned" ? " (abandoned)" : t.status === "in_progress" ? " (in progress)" : "";
|
|
18683
|
-
return `- [${checked}] ${t.description}${note}
|
|
18684
|
-
`;
|
|
18685
|
-
}
|
|
18686
|
-
function renderEvent(e) {
|
|
18687
|
-
const ts = new Date(e.created_at).toISOString();
|
|
18688
|
-
return `- [${ts}] (${e.event_type}) ${e.summary}
|
|
18689
|
-
`;
|
|
18690
|
-
}
|
|
18691
|
-
function renderEntity(entityId, bundle, generatedAt) {
|
|
18692
|
-
const lines = [];
|
|
18693
|
-
lines.push(`# Memory Dump: ${entityId}`);
|
|
18694
|
-
lines.push(`Generated: ${new Date(generatedAt).toISOString()}`);
|
|
18695
|
-
lines.push("");
|
|
18696
|
-
lines.push("## Facts");
|
|
18697
|
-
lines.push("");
|
|
18698
|
-
if (bundle.facts.length === 0) {
|
|
18699
|
-
lines.push("_(none)_\n");
|
|
18700
|
-
} else {
|
|
18701
|
-
for (const f of bundle.facts) lines.push(renderFact(f));
|
|
19690
|
+
async setLifecycleStatusTask(taskId, entityId, status) {
|
|
19691
|
+
return this.okfTrustWrites.setLifecycleStatusTask(taskId, entityId, status);
|
|
18702
19692
|
}
|
|
18703
|
-
|
|
18704
|
-
|
|
18705
|
-
if (bundle.tasks.length === 0) {
|
|
18706
|
-
lines.push("_(none)_\n");
|
|
18707
|
-
} else {
|
|
18708
|
-
for (const t of bundle.tasks) lines.push(renderTask(t));
|
|
19693
|
+
async setStaleAfterTask(taskId, entityId, date) {
|
|
19694
|
+
return this.okfTrustWrites.setStaleAfterTask(taskId, entityId, date);
|
|
18709
19695
|
}
|
|
18710
|
-
|
|
18711
|
-
|
|
18712
|
-
|
|
18713
|
-
|
|
18714
|
-
|
|
18715
|
-
|
|
18716
|
-
|
|
19696
|
+
async setGeneratedByTask(taskId, entityId, actor) {
|
|
19697
|
+
return this.okfTrustWrites.setGeneratedByTask(taskId, entityId, actor);
|
|
19698
|
+
}
|
|
19699
|
+
};
|
|
19700
|
+
_testAccessNonTestEnvWarned = new WeakMap();
|
|
19701
|
+
/** Max upsertGraph node and superseded-fact ids held for their post-commit sync (spec #280 id threading). */
|
|
19702
|
+
WikiMemory.UPSERT_ID_STASH_CAP = 1e4;
|
|
19703
|
+
/** Max superseded-fact ids held for post-commit removal delivery. */
|
|
19704
|
+
WikiMemory.REMOVAL_STASH_CAP = 1e4;
|
|
19705
|
+
function assertEntityId2(entityId) {
|
|
19706
|
+
if (typeof entityId !== "string" || entityId.length === 0) {
|
|
19707
|
+
throw new TypeError("Invalid entityId: must be a non-empty string.");
|
|
18717
19708
|
}
|
|
18718
|
-
return lines.join("\n");
|
|
18719
|
-
}
|
|
18720
|
-
function formatEntityFileName(entityId) {
|
|
18721
|
-
return `${sanitizeForFilename(entityId)}.md`;
|
|
18722
|
-
}
|
|
18723
|
-
function formatMemoryDump(dump) {
|
|
18724
|
-
const files = Object.entries(dump.entities).map(([entityId, bundle]) => ({
|
|
18725
|
-
name: formatEntityFileName(entityId),
|
|
18726
|
-
content: renderEntity(entityId, bundle, dump.generatedAt)
|
|
18727
|
-
}));
|
|
18728
|
-
const manifestDump = {
|
|
18729
|
-
generatedAt: dump.generatedAt,
|
|
18730
|
-
entities: Object.fromEntries(
|
|
18731
|
-
Object.entries(dump.entities).map(([entityId, bundle]) => [
|
|
18732
|
-
entityId,
|
|
18733
|
-
{
|
|
18734
|
-
...bundle,
|
|
18735
|
-
facts: bundle.facts.map((f) => {
|
|
18736
|
-
const { embedding_blob: _blob, ...rest } = f;
|
|
18737
|
-
return rest;
|
|
18738
|
-
})
|
|
18739
|
-
}
|
|
18740
|
-
])
|
|
18741
|
-
)
|
|
18742
|
-
};
|
|
18743
|
-
return {
|
|
18744
|
-
manifest: JSON.stringify(manifestDump, null, 2),
|
|
18745
|
-
files
|
|
18746
|
-
};
|
|
18747
|
-
}
|
|
18748
|
-
var DEFAULT_PROFILE = "llm-wiki/2";
|
|
18749
|
-
function isoOrFallback(updatedAt) {
|
|
18750
|
-
if (!Number.isFinite(updatedAt)) return (/* @__PURE__ */ new Date(0)).toISOString();
|
|
18751
|
-
const d = new Date(updatedAt);
|
|
18752
|
-
if (!Number.isFinite(d.getTime())) return (/* @__PURE__ */ new Date(0)).toISOString();
|
|
18753
|
-
return d.toISOString();
|
|
18754
|
-
}
|
|
18755
|
-
function isoDateOrOmit(ms) {
|
|
18756
|
-
if (ms == null || !Number.isFinite(ms)) return void 0;
|
|
18757
|
-
const d = new Date(ms);
|
|
18758
|
-
if (!Number.isFinite(d.getTime())) return void 0;
|
|
18759
|
-
return d.toISOString().slice(0, 10);
|
|
18760
19709
|
}
|
|
18761
|
-
|
|
18762
|
-
|
|
18763
|
-
|
|
18764
|
-
|
|
18765
|
-
|
|
18766
|
-
|
|
18767
|
-
...p.position != null ? { position: p.position } : {}
|
|
18768
|
-
};
|
|
19710
|
+
|
|
19711
|
+
// src/utils/formatContext.ts
|
|
19712
|
+
function validateMaxOption(value, name) {
|
|
19713
|
+
if (!isFinite(value) || value < 0) {
|
|
19714
|
+
throw new Error(`Invalid ${name}: must be a non-negative finite number`);
|
|
19715
|
+
}
|
|
18769
19716
|
}
|
|
18770
|
-
|
|
18771
|
-
|
|
18772
|
-
|
|
18773
|
-
|
|
18774
|
-
|
|
18775
|
-
|
|
18776
|
-
|
|
18777
|
-
|
|
18778
|
-
|
|
18779
|
-
|
|
18780
|
-
resource: f.source_ref ?? void 0,
|
|
18781
|
-
id: f.id,
|
|
18782
|
-
entity_id: f.entity_id,
|
|
18783
|
-
confidence: f.confidence,
|
|
18784
|
-
source_type: f.source_type,
|
|
18785
|
-
source_hash: f.source_hash,
|
|
18786
|
-
created_at: f.created_at,
|
|
18787
|
-
access_count: f.access_count,
|
|
18788
|
-
last_accessed_at: f.last_accessed_at,
|
|
18789
|
-
deleted_at: f.deleted_at,
|
|
18790
|
-
// OKF v0.2
|
|
18791
|
-
status: f.lifecycle_status ?? "stable",
|
|
18792
|
-
...isoDateOrOmit(f.stale_after) ? { stale_after: isoDateOrOmit(f.stale_after) } : {},
|
|
18793
|
-
// Omit `generated` entirely when there's no actor on record — never
|
|
18794
|
-
// fabricate a `generated_by` (mirrors the import side's rule in §4.8:
|
|
18795
|
-
// it never invents one either, so export must not manufacture one that
|
|
18796
|
-
// would then round-trip back in as if it had always been asserted).
|
|
18797
|
-
...f.generated_by ? { generated: { by: f.generated_by, at: isoOrFallback(f.updated_at) } } : {},
|
|
18798
|
-
// Omit `verified`/`sources` when empty — an emitted `[]` is not the same
|
|
18799
|
-
// shape as an absent key (spec §5.3 derives `unverified` from "no
|
|
18800
|
-
// `verified` key", not from "empty `verified` list").
|
|
18801
|
-
...f.okf_verified && f.okf_verified.length > 0 ? { verified: f.okf_verified } : {},
|
|
18802
|
-
...f.okf_sources && f.okf_sources.length > 0 ? { sources: f.okf_sources } : {},
|
|
18803
|
-
...f.okf_usage_window ? { usage_window: f.okf_usage_window } : {},
|
|
18804
|
-
// Temporal (spec 2026-09-29 §10.9): flat epoch-ms keys, like created_at.
|
|
18805
|
-
...f.valid_from != null ? { valid_from: f.valid_from } : {},
|
|
18806
|
-
...f.valid_to != null ? { valid_to: f.valid_to } : {},
|
|
18807
|
-
...f.superseded_by != null ? { superseded_by: f.superseded_by } : {},
|
|
18808
|
-
...f.superseded_at != null ? { superseded_at: f.superseded_at } : {},
|
|
18809
|
-
...f.prior_valid_to != null ? { prior_valid_to: f.prior_valid_to } : {},
|
|
18810
|
-
// Source pointer (specs/source-pointers): map only when non-null; null slots omitted.
|
|
18811
|
-
...sourcePointerFrontmatter(f.source_pointer) ? { source_pointer: sourcePointerFrontmatter(f.source_pointer) } : {},
|
|
18812
|
-
// derived_events (specs/inplace-update-provenance §5): optional list, only when non-empty.
|
|
18813
|
-
...f.derived_events && f.derived_events.length > 0 ? { derived_events: f.derived_events } : {}
|
|
18814
|
-
};
|
|
19717
|
+
var CONFIDENCE_WEIGHT = {
|
|
19718
|
+
certain: 1,
|
|
19719
|
+
inferred: 0.6,
|
|
19720
|
+
tentative: 0.3
|
|
19721
|
+
};
|
|
19722
|
+
function scoreFactFor(fact, weights, now) {
|
|
19723
|
+
const confW = CONFIDENCE_WEIGHT[fact.confidence] ?? 0.3;
|
|
19724
|
+
const ageDays = (now - fact.updated_at) / 864e5;
|
|
19725
|
+
const recencyDecay = Math.exp(-ageDays / 30);
|
|
19726
|
+
return confW * weights.confidence + Math.log(1 + fact.access_count) * weights.accessCount + recencyDecay * weights.recency;
|
|
18815
19727
|
}
|
|
18816
|
-
function
|
|
18817
|
-
|
|
18818
|
-
|
|
18819
|
-
|
|
18820
|
-
|
|
18821
|
-
|
|
18822
|
-
|
|
18823
|
-
entity_id: t.entity_id,
|
|
18824
|
-
status: t.lifecycle_status ?? "stable",
|
|
18825
|
-
// OKF v0.2 lifecycle
|
|
18826
|
-
execution_status: t.status,
|
|
18827
|
-
// execution state under renamed key
|
|
18828
|
-
priority: t.priority,
|
|
18829
|
-
created_at: t.created_at,
|
|
18830
|
-
resolved_at: t.resolved_at,
|
|
18831
|
-
deleted_at: t.deleted_at,
|
|
18832
|
-
// OKF v0.2 — symmetric with facts (spec §2.5): stale_after applies to
|
|
18833
|
-
// tasks too (a hallucinated task needs a freshness signal as much as a
|
|
18834
|
-
// hallucinated fact does).
|
|
18835
|
-
...isoDateOrOmit(t.stale_after) ? { stale_after: isoDateOrOmit(t.stale_after) } : {},
|
|
18836
|
-
...t.generated_by ? { generated: { by: t.generated_by, at: isoOrFallback(t.updated_at) } } : {},
|
|
18837
|
-
...t.okf_verified && t.okf_verified.length > 0 ? { verified: t.okf_verified } : {},
|
|
18838
|
-
...t.okf_sources && t.okf_sources.length > 0 ? { sources: t.okf_sources } : {},
|
|
18839
|
-
...t.okf_usage_window ? { usage_window: t.okf_usage_window } : {}
|
|
18840
|
-
};
|
|
19728
|
+
function renderFactMarkdown(fact, includeConfidence, includeTags, includeEntityIds, score) {
|
|
19729
|
+
const confPart = includeConfidence ? ` (${fact.confidence})` : "";
|
|
19730
|
+
const tagPart = includeTags && fact.tags.length > 0 ? ` [${fact.tags.join(", ")}]` : "";
|
|
19731
|
+
const sourcePart = includeEntityIds ? ` {entity_id=${fact.entity_id}}` : "";
|
|
19732
|
+
const scorePart = score !== void 0 ? ` {score=${score.toFixed(4)}}` : "";
|
|
19733
|
+
return `- **${fact.title}**${confPart}${tagPart}${sourcePart}${scorePart}
|
|
19734
|
+
${fact.body.replace(/\n/g, "\n ")}`;
|
|
18841
19735
|
}
|
|
18842
|
-
function
|
|
18843
|
-
|
|
18844
|
-
|
|
18845
|
-
|
|
18846
|
-
|
|
18847
|
-
|
|
18848
|
-
resource: f.source_ref ?? void 0,
|
|
18849
|
-
id: f.id,
|
|
18850
|
-
entity_id: f.entity_id,
|
|
18851
|
-
confidence: f.confidence,
|
|
18852
|
-
source_type: f.source_type,
|
|
18853
|
-
source_hash: f.source_hash,
|
|
18854
|
-
created_at: f.created_at,
|
|
18855
|
-
access_count: f.access_count,
|
|
18856
|
-
last_accessed_at: f.last_accessed_at,
|
|
18857
|
-
deleted_at: f.deleted_at,
|
|
18858
|
-
// Source pointer (specs/source-pointers): same map rule as the v2 path.
|
|
18859
|
-
...sourcePointerFrontmatter(f.source_pointer) ? { source_pointer: sourcePointerFrontmatter(f.source_pointer) } : {},
|
|
18860
|
-
// derived_events (specs/inplace-update-provenance §5): optional list, only when non-empty.
|
|
18861
|
-
...f.derived_events && f.derived_events.length > 0 ? { derived_events: f.derived_events } : {}
|
|
18862
|
-
};
|
|
19736
|
+
function renderFactPlain(fact, includeConfidence, includeTags, includeEntityIds, score) {
|
|
19737
|
+
const confPart = includeConfidence ? ` (${fact.confidence})` : "";
|
|
19738
|
+
const tagPart = includeTags && fact.tags.length > 0 ? ` [${fact.tags.join(", ")}]` : "";
|
|
19739
|
+
const sourcePart = includeEntityIds ? ` {entity_id=${fact.entity_id}}` : "";
|
|
19740
|
+
const scorePart = score !== void 0 ? ` {score=${score.toFixed(4)}}` : "";
|
|
19741
|
+
return `${fact.title}${confPart}${tagPart}${sourcePart}${scorePart}: ${fact.body}`;
|
|
18863
19742
|
}
|
|
18864
|
-
function
|
|
18865
|
-
return {
|
|
18866
|
-
type: t.okf_type ?? "task",
|
|
18867
|
-
title: t.description,
|
|
18868
|
-
timestamp: isoOrFallback(t.updated_at),
|
|
18869
|
-
id: t.id,
|
|
18870
|
-
entity_id: t.entity_id,
|
|
18871
|
-
status: t.status,
|
|
18872
|
-
priority: t.priority,
|
|
18873
|
-
created_at: t.created_at,
|
|
18874
|
-
resolved_at: t.resolved_at,
|
|
18875
|
-
deleted_at: t.deleted_at
|
|
18876
|
-
};
|
|
19743
|
+
function renderTaskMarkdown(task) {
|
|
19744
|
+
return `- [P${task.priority}] ${task.description.replace(/\n/g, "\n ")} (${task.status})`;
|
|
18877
19745
|
}
|
|
18878
|
-
function
|
|
18879
|
-
return
|
|
19746
|
+
function renderTaskPlain(task) {
|
|
19747
|
+
return `[P${task.priority}] ${task.description} (${task.status})`;
|
|
18880
19748
|
}
|
|
18881
|
-
function
|
|
18882
|
-
const
|
|
18883
|
-
|
|
18884
|
-
const targetName = targetFilePath.slice(targetFilePath.lastIndexOf("/") + 1);
|
|
18885
|
-
if (sourceDir === targetDir) return `./${targetName}`;
|
|
18886
|
-
if (sourceDir.endsWith("/facts") && targetDir.endsWith("/tasks")) return `../tasks/${targetName}`;
|
|
18887
|
-
if (sourceDir.endsWith("/tasks") && targetDir.endsWith("/facts")) return `../facts/${targetName}`;
|
|
18888
|
-
return targetFilePath.replace(/^entities\/[^/]+\//, "");
|
|
19749
|
+
function renderEventMarkdown(event) {
|
|
19750
|
+
const ts = new Date(event.created_at).toISOString();
|
|
19751
|
+
return `- [${event.event_type} @ ${ts}] ${event.summary.replace(/\n/g, "\n ")}`;
|
|
18889
19752
|
}
|
|
18890
|
-
function
|
|
18891
|
-
|
|
18892
|
-
|
|
18893
|
-
const summary = e.summary.replace(/\\/g, "\\\\").replace(/\[/g, "\\[").replace(/\]/g, "\\]").replace(/\r?\n/g, " ");
|
|
18894
|
-
const text = factFilename ? `(${e.event_type}) [${summary}](./facts/${factFilename}.md)` : `(${e.event_type}) ${summary}`;
|
|
18895
|
-
const occurred = createdAtValue(e.occurred_at);
|
|
18896
|
-
const logTime = e.occurred_at != null && isUsableDate(occurred) && occurred >= OKF_DATE_MIN && occurred <= OKF_DATE_MAX && occurred <= e.created_at ? occurred : e.created_at;
|
|
18897
|
-
return { date: formatLogDate(logTime), text: coreOkf.appendEventIdComment(text, e.id) };
|
|
18898
|
-
});
|
|
19753
|
+
function renderEventPlain(event) {
|
|
19754
|
+
const ts = new Date(event.created_at).toISOString();
|
|
19755
|
+
return `[${event.event_type} @ ${ts}] ${event.summary}`;
|
|
18899
19756
|
}
|
|
18900
|
-
|
|
18901
|
-
|
|
18902
|
-
|
|
18903
|
-
|
|
18904
|
-
|
|
18905
|
-
const
|
|
18906
|
-
|
|
18907
|
-
|
|
18908
|
-
|
|
18909
|
-
|
|
18910
|
-
|
|
18911
|
-
|
|
18912
|
-
|
|
18913
|
-
|
|
18914
|
-
|
|
18915
|
-
|
|
18916
|
-
|
|
18917
|
-
|
|
18918
|
-
|
|
18919
|
-
bundle.facts.map((f) => [f.id, sanitizeConceptId(f.id)])
|
|
18920
|
-
);
|
|
18921
|
-
const idToConceptPath = /* @__PURE__ */ new Map();
|
|
18922
|
-
for (const f of bundle.facts) {
|
|
18923
|
-
idToConceptPath.set(f.id, `entities/${dir}/facts/${factIdToFilename.get(f.id)}.md`);
|
|
19757
|
+
function renderSourceLabel(p, includeEntityId) {
|
|
19758
|
+
const entity = includeEntityId ? `${p.entityId} ` : "";
|
|
19759
|
+
return `${entity}${p.sourceRef} #${p.seq}${p.truncated ? " (excerpt)" : ""}`;
|
|
19760
|
+
}
|
|
19761
|
+
function formatContext(bundle, options) {
|
|
19762
|
+
const opts = {
|
|
19763
|
+
format: options?.format ?? "markdown",
|
|
19764
|
+
maxFacts: options?.maxFacts ?? 10,
|
|
19765
|
+
maxTasks: options?.maxTasks ?? 10,
|
|
19766
|
+
maxEvents: options?.maxEvents ?? 10,
|
|
19767
|
+
includeConfidence: !(options?.compact ?? false) && (options?.includeConfidence ?? true),
|
|
19768
|
+
includeTags: !(options?.compact ?? false) && (options?.includeTags ?? true),
|
|
19769
|
+
includeEntityIds: !(options?.compact ?? false) && (options?.includeEntityIds ?? false),
|
|
19770
|
+
includeFactScores: !(options?.compact ?? false) && (options?.includeFactScores ?? false),
|
|
19771
|
+
compact: options?.compact ?? false,
|
|
19772
|
+
factWeights: {
|
|
19773
|
+
confidence: options?.factWeights?.confidence ?? 1,
|
|
19774
|
+
accessCount: options?.factWeights?.accessCount ?? 0.3,
|
|
19775
|
+
recency: options?.factWeights?.recency ?? 0.5
|
|
18924
19776
|
}
|
|
18925
|
-
|
|
18926
|
-
|
|
19777
|
+
};
|
|
19778
|
+
validateMaxOption(opts.maxFacts, "maxFacts");
|
|
19779
|
+
validateMaxOption(opts.maxTasks, "maxTasks");
|
|
19780
|
+
validateMaxOption(opts.maxEvents, "maxEvents");
|
|
19781
|
+
const weights = opts.factWeights;
|
|
19782
|
+
const now = Date.now();
|
|
19783
|
+
const sortedFacts = bundle.factScores ? [...bundle.facts].slice(0, opts.maxFacts) : [...bundle.facts].sort((a, b) => scoreFactFor(b, weights, now) - scoreFactFor(a, weights, now)).slice(0, opts.maxFacts);
|
|
19784
|
+
const sortedTasks = [...bundle.tasks].sort((a, b) => b.priority - a.priority || a.created_at - b.created_at).slice(0, opts.maxTasks);
|
|
19785
|
+
const sortedEvents = [...bundle.events].sort((a, b) => b.created_at - a.created_at).slice(0, opts.maxEvents);
|
|
19786
|
+
const sources = bundle.sources ?? [];
|
|
19787
|
+
if (sortedFacts.length === 0 && sortedTasks.length === 0 && sortedEvents.length === 0 && sources.length === 0) {
|
|
19788
|
+
return "";
|
|
19789
|
+
}
|
|
19790
|
+
const isMarkdown = opts.format === "markdown";
|
|
19791
|
+
const lines = [];
|
|
19792
|
+
if (isMarkdown) {
|
|
19793
|
+
lines.push("## Memory");
|
|
19794
|
+
if (sortedFacts.length > 0) {
|
|
19795
|
+
lines.push("");
|
|
19796
|
+
lines.push("### Known Facts");
|
|
19797
|
+
for (const fact of sortedFacts) {
|
|
19798
|
+
lines.push(renderFactMarkdown(fact, opts.includeConfidence, opts.includeTags, opts.includeEntityIds, opts.includeFactScores ? bundle.factScores?.[fact.id] : void 0));
|
|
19799
|
+
}
|
|
18927
19800
|
}
|
|
18928
|
-
|
|
18929
|
-
|
|
18930
|
-
|
|
18931
|
-
|
|
18932
|
-
|
|
19801
|
+
if (sortedTasks.length > 0) {
|
|
19802
|
+
lines.push("");
|
|
19803
|
+
lines.push("### Open Tasks");
|
|
19804
|
+
for (const task of sortedTasks) {
|
|
19805
|
+
lines.push(renderTaskMarkdown(task));
|
|
19806
|
+
}
|
|
18933
19807
|
}
|
|
18934
|
-
|
|
18935
|
-
|
|
18936
|
-
|
|
18937
|
-
|
|
18938
|
-
|
|
18939
|
-
|
|
18940
|
-
|
|
18941
|
-
|
|
18942
|
-
|
|
18943
|
-
|
|
18944
|
-
|
|
19808
|
+
if (sortedEvents.length > 0) {
|
|
19809
|
+
lines.push("");
|
|
19810
|
+
lines.push("### Recent Events");
|
|
19811
|
+
for (const event of sortedEvents) {
|
|
19812
|
+
lines.push(renderEventMarkdown(event));
|
|
19813
|
+
}
|
|
19814
|
+
}
|
|
19815
|
+
if (sources.length > 0) {
|
|
19816
|
+
lines.push("");
|
|
19817
|
+
lines.push("### Sources");
|
|
19818
|
+
for (const p of sources) {
|
|
19819
|
+
lines.push(`- [${renderSourceLabel(p, opts.includeEntityIds)}] ${p.text.replace(/\n/g, "\n ")}`);
|
|
19820
|
+
}
|
|
19821
|
+
}
|
|
19822
|
+
} else {
|
|
19823
|
+
if (sortedFacts.length > 0) {
|
|
19824
|
+
lines.push("KNOWN FACTS:");
|
|
19825
|
+
for (const fact of sortedFacts) {
|
|
19826
|
+
lines.push(renderFactPlain(fact, opts.includeConfidence, opts.includeTags, opts.includeEntityIds, opts.includeFactScores ? bundle.factScores?.[fact.id] : void 0));
|
|
19827
|
+
}
|
|
18945
19828
|
}
|
|
18946
|
-
|
|
18947
|
-
|
|
18948
|
-
|
|
18949
|
-
|
|
18950
|
-
|
|
18951
|
-
|
|
18952
|
-
|
|
18953
|
-
|
|
18954
|
-
|
|
18955
|
-
|
|
18956
|
-
}
|
|
19829
|
+
if (sortedTasks.length > 0) {
|
|
19830
|
+
lines.push("OPEN TASKS:");
|
|
19831
|
+
for (const task of sortedTasks) {
|
|
19832
|
+
lines.push(renderTaskPlain(task));
|
|
19833
|
+
}
|
|
19834
|
+
}
|
|
19835
|
+
if (sortedEvents.length > 0) {
|
|
19836
|
+
lines.push("RECENT EVENTS:");
|
|
19837
|
+
for (const event of sortedEvents) {
|
|
19838
|
+
lines.push(renderEventPlain(event));
|
|
19839
|
+
}
|
|
19840
|
+
}
|
|
19841
|
+
if (sources.length > 0) {
|
|
19842
|
+
lines.push("SOURCES:");
|
|
19843
|
+
for (const p of sources) {
|
|
19844
|
+
lines.push(`[${renderSourceLabel(p, opts.includeEntityIds)}] ${p.text}`);
|
|
19845
|
+
}
|
|
18957
19846
|
}
|
|
18958
|
-
files.push({
|
|
18959
|
-
path: `entities/${dir}/log.md`,
|
|
18960
|
-
content: coreOkf.buildLogMd(buildEventLogEntries(bundle.events, factIdToFilename))
|
|
18961
|
-
});
|
|
18962
|
-
const entityIndexSections = [
|
|
18963
|
-
{ heading: "Facts", entries: factEntries },
|
|
18964
|
-
{ heading: "Tasks", entries: taskEntries }
|
|
18965
|
-
];
|
|
18966
|
-
files.push({
|
|
18967
|
-
path: `entities/${dir}/index.md`,
|
|
18968
|
-
content: coreOkf.buildEntityIndexMd({
|
|
18969
|
-
summary: bundle.summary,
|
|
18970
|
-
sections: entityIndexSections
|
|
18971
|
-
})
|
|
18972
|
-
});
|
|
18973
|
-
rootEntries.push({ path: `entities/${dir}/index.md`, title: entityId });
|
|
18974
19847
|
}
|
|
18975
|
-
|
|
18976
|
-
path: "index.md",
|
|
18977
|
-
content: coreOkf.buildRootIndexMd(
|
|
18978
|
-
okfVersion,
|
|
18979
|
-
rootEntries.length > 0 ? [{ heading: "Entities", entries: rootEntries }] : [],
|
|
18980
|
-
{ profile }
|
|
18981
|
-
)
|
|
18982
|
-
});
|
|
18983
|
-
return { files };
|
|
19848
|
+
return lines.join("\n");
|
|
18984
19849
|
}
|
|
18985
|
-
|
|
18986
|
-
|
|
18987
|
-
|
|
18988
|
-
|
|
18989
|
-
"
|
|
18990
|
-
|
|
18991
|
-
]);
|
|
18992
|
-
|
|
18993
|
-
|
|
18994
|
-
|
|
18995
|
-
|
|
18996
|
-
|
|
19850
|
+
|
|
19851
|
+
// src/utils/formatGraphContext.ts
|
|
19852
|
+
function formatGraphContext(neighborhood) {
|
|
19853
|
+
const { nodes, edges } = neighborhood;
|
|
19854
|
+
if (nodes.length === 0) return "";
|
|
19855
|
+
const nodeById = new Map(nodes.map((n) => [n.id, n]));
|
|
19856
|
+
const nodeIndex = new Map(nodes.map((n, i) => [n.id, i]));
|
|
19857
|
+
const lines = [];
|
|
19858
|
+
for (const node of nodes) {
|
|
19859
|
+
lines.push(`[${node.okf_type ?? "fact"}] ${node.title} (ID: ${node.id})`);
|
|
19860
|
+
const outbound = edgesByDirection(edges, node.id, "source_id", nodeById, nodeIndex);
|
|
19861
|
+
const inbound = edgesByDirection(edges, node.id, "target_id", nodeById, nodeIndex);
|
|
19862
|
+
for (const { edge, other } of outbound) {
|
|
19863
|
+
lines.push(` -[${edge.edge_type}]-> [${other.okf_type ?? "fact"}] ${other.title}`);
|
|
19864
|
+
}
|
|
19865
|
+
for (const { edge, other } of inbound) {
|
|
19866
|
+
lines.push(` <-[${edge.edge_type}]- [${other.okf_type ?? "fact"}] ${other.title}`);
|
|
19867
|
+
}
|
|
19868
|
+
}
|
|
19869
|
+
return lines.join("\n");
|
|
18997
19870
|
}
|
|
18998
|
-
function
|
|
18999
|
-
|
|
19000
|
-
|
|
19001
|
-
|
|
19002
|
-
|
|
19871
|
+
function edgesByDirection(edges, nodeId, endpoint, nodeById, nodeIndex) {
|
|
19872
|
+
const otherEndpoint = endpoint === "source_id" ? "target_id" : "source_id";
|
|
19873
|
+
return edges.filter((e) => e[endpoint] === nodeId).filter((e) => {
|
|
19874
|
+
const otherId = e[otherEndpoint];
|
|
19875
|
+
const selfIdx = nodeIndex.get(nodeId);
|
|
19876
|
+
const otherIdx = nodeIndex.get(otherId);
|
|
19877
|
+
return otherIdx !== void 0 && selfIdx < otherIdx;
|
|
19878
|
+
}).map((edge) => ({ edge, other: nodeById.get(edge[otherEndpoint]) })).sort(
|
|
19879
|
+
(a, b) => a.edge.edge_type.localeCompare(b.edge.edge_type) || a.other.title.localeCompare(b.other.title) || a.other.id.localeCompare(b.other.id) || a.edge.id.localeCompare(b.edge.id)
|
|
19880
|
+
);
|
|
19003
19881
|
}
|
|
19004
|
-
|
|
19005
|
-
|
|
19882
|
+
|
|
19883
|
+
// src/utils/sanitizeForFilename.ts
|
|
19884
|
+
function shortHash(value) {
|
|
19885
|
+
let h1 = 5381;
|
|
19886
|
+
let h2 = 52711;
|
|
19887
|
+
for (let i = 0; i < value.length; i += 1) {
|
|
19888
|
+
const c = value.charCodeAt(i);
|
|
19889
|
+
h1 = Math.imul(h1, 33) ^ c;
|
|
19890
|
+
h2 = Math.imul(h2, 31) ^ c;
|
|
19891
|
+
}
|
|
19892
|
+
return (h1 >>> 0).toString(16).padStart(8, "0") + (h2 >>> 0).toString(16).padStart(8, "0");
|
|
19006
19893
|
}
|
|
19007
|
-
|
|
19008
|
-
|
|
19009
|
-
|
|
19894
|
+
var OKF_RESERVED_CONCEPT_NAMES = /* @__PURE__ */ new Set(["index", "log"]);
|
|
19895
|
+
var WINDOWS_RESERVED_NAMES = /* @__PURE__ */ new Set([
|
|
19896
|
+
"con",
|
|
19897
|
+
"prn",
|
|
19898
|
+
"aux",
|
|
19899
|
+
"nul",
|
|
19900
|
+
"com1",
|
|
19901
|
+
"com2",
|
|
19902
|
+
"com3",
|
|
19903
|
+
"com4",
|
|
19904
|
+
"com5",
|
|
19905
|
+
"com6",
|
|
19906
|
+
"com7",
|
|
19907
|
+
"com8",
|
|
19908
|
+
"com9",
|
|
19909
|
+
"lpt1",
|
|
19910
|
+
"lpt2",
|
|
19911
|
+
"lpt3",
|
|
19912
|
+
"lpt4",
|
|
19913
|
+
"lpt5",
|
|
19914
|
+
"lpt6",
|
|
19915
|
+
"lpt7",
|
|
19916
|
+
"lpt8",
|
|
19917
|
+
"lpt9"
|
|
19918
|
+
]);
|
|
19919
|
+
function isWindowsReservedName(name) {
|
|
19920
|
+
const base = name.split(".")[0];
|
|
19921
|
+
return WINDOWS_RESERVED_NAMES.has(base.toLowerCase());
|
|
19010
19922
|
}
|
|
19011
|
-
function
|
|
19012
|
-
const
|
|
19013
|
-
const
|
|
19014
|
-
const
|
|
19015
|
-
|
|
19016
|
-
|
|
19017
|
-
|
|
19018
|
-
|
|
19019
|
-
|
|
19020
|
-
|
|
19021
|
-
resolved.push(seg);
|
|
19923
|
+
function sanitizeForFilename(value) {
|
|
19924
|
+
const normalized = value.normalize("NFKC");
|
|
19925
|
+
const sanitized = normalized.replace(/[^A-Za-z0-9._-]+/g, "_").replace(/^\.+/, "_").replace(/_+/g, "_").replace(/^[_-]+|[_-]+$/g, "");
|
|
19926
|
+
const MAX_BASE = 200;
|
|
19927
|
+
const trimmed = sanitized.length > MAX_BASE ? sanitized.slice(0, MAX_BASE) : sanitized;
|
|
19928
|
+
let baseName = trimmed && trimmed !== "." && trimmed !== ".." ? trimmed : "entity";
|
|
19929
|
+
const withoutTrailingDotSpace = baseName.replace(/[. ]+$/, "");
|
|
19930
|
+
const hadTrailingDotSpace = withoutTrailingDotSpace !== baseName;
|
|
19931
|
+
if (hadTrailingDotSpace) {
|
|
19932
|
+
baseName = withoutTrailingDotSpace || "entity";
|
|
19022
19933
|
}
|
|
19023
|
-
|
|
19934
|
+
const windowsReserved = isWindowsReservedName(baseName);
|
|
19935
|
+
const needsSuffix = baseName !== value || sanitized.length > MAX_BASE || hadTrailingDotSpace || windowsReserved;
|
|
19936
|
+
if (!needsSuffix) return baseName;
|
|
19937
|
+
const suffix = `-${shortHash(value)}`;
|
|
19938
|
+
return `${baseName}${suffix}`;
|
|
19024
19939
|
}
|
|
19025
|
-
function
|
|
19026
|
-
|
|
19027
|
-
|
|
19028
|
-
return
|
|
19029
|
-
} catch {
|
|
19030
|
-
return path;
|
|
19940
|
+
function sanitizeConceptId(id) {
|
|
19941
|
+
const sanitized = sanitizeForFilename(id);
|
|
19942
|
+
if (OKF_RESERVED_CONCEPT_NAMES.has(sanitized.toLowerCase())) {
|
|
19943
|
+
return `${sanitized}-${shortHash(id)}`;
|
|
19031
19944
|
}
|
|
19945
|
+
return sanitized;
|
|
19032
19946
|
}
|
|
19033
|
-
|
|
19034
|
-
|
|
19035
|
-
|
|
19036
|
-
|
|
19037
|
-
const
|
|
19038
|
-
|
|
19039
|
-
|
|
19040
|
-
|
|
19041
|
-
|
|
19947
|
+
|
|
19948
|
+
// src/utils/formatMemoryDump.ts
|
|
19949
|
+
function renderFact(f) {
|
|
19950
|
+
const tags = (f.tags || []).join(", ");
|
|
19951
|
+
const source = f.source_ref ?? f.source_type;
|
|
19952
|
+
return `### ${f.title}
|
|
19953
|
+
**Tags:** ${tags}
|
|
19954
|
+
**Confidence:** ${f.confidence}
|
|
19955
|
+
**Source:** ${source}
|
|
19956
|
+
|
|
19957
|
+
${f.body}
|
|
19958
|
+
|
|
19959
|
+
---
|
|
19960
|
+
`;
|
|
19042
19961
|
}
|
|
19043
|
-
function
|
|
19044
|
-
const
|
|
19045
|
-
|
|
19962
|
+
function renderTask(t) {
|
|
19963
|
+
const checked = t.status === "done" ? "x" : " ";
|
|
19964
|
+
const note = t.status === "done" ? " (done)" : t.status === "abandoned" ? " (abandoned)" : t.status === "in_progress" ? " (in progress)" : "";
|
|
19965
|
+
return `- [${checked}] ${t.description}${note}
|
|
19966
|
+
`;
|
|
19046
19967
|
}
|
|
19047
|
-
function
|
|
19048
|
-
const
|
|
19049
|
-
|
|
19050
|
-
|
|
19051
|
-
const cut = hashIdx === -1 ? queryIdx : queryIdx === -1 ? hashIdx : Math.min(hashIdx, queryIdx);
|
|
19052
|
-
return linkPath.slice(0, cut);
|
|
19968
|
+
function renderEvent(e) {
|
|
19969
|
+
const ts = new Date(e.created_at).toISOString();
|
|
19970
|
+
return `- [${ts}] (${e.event_type}) ${e.summary}
|
|
19971
|
+
`;
|
|
19053
19972
|
}
|
|
19054
|
-
function
|
|
19055
|
-
|
|
19056
|
-
|
|
19973
|
+
function renderEntity(entityId, bundle, generatedAt) {
|
|
19974
|
+
const lines = [];
|
|
19975
|
+
lines.push(`# Memory Dump: ${entityId}`);
|
|
19976
|
+
lines.push(`Generated: ${new Date(generatedAt).toISOString()}`);
|
|
19977
|
+
lines.push("");
|
|
19978
|
+
lines.push("## Facts");
|
|
19979
|
+
lines.push("");
|
|
19980
|
+
if (bundle.facts.length === 0) {
|
|
19981
|
+
lines.push("_(none)_\n");
|
|
19982
|
+
} else {
|
|
19983
|
+
for (const f of bundle.facts) lines.push(renderFact(f));
|
|
19057
19984
|
}
|
|
19058
|
-
|
|
19059
|
-
|
|
19060
|
-
|
|
19061
|
-
|
|
19062
|
-
|
|
19063
|
-
|
|
19064
|
-
|
|
19065
|
-
|
|
19066
|
-
|
|
19985
|
+
lines.push("## Tasks");
|
|
19986
|
+
lines.push("");
|
|
19987
|
+
if (bundle.tasks.length === 0) {
|
|
19988
|
+
lines.push("_(none)_\n");
|
|
19989
|
+
} else {
|
|
19990
|
+
for (const t of bundle.tasks) lines.push(renderTask(t));
|
|
19991
|
+
}
|
|
19992
|
+
lines.push("");
|
|
19993
|
+
lines.push("## Recent Events");
|
|
19994
|
+
lines.push("");
|
|
19995
|
+
if (bundle.events.length === 0) {
|
|
19996
|
+
lines.push("_(none)_\n");
|
|
19997
|
+
} else {
|
|
19998
|
+
for (const e of bundle.events) lines.push(renderEvent(e));
|
|
19067
19999
|
}
|
|
19068
|
-
return
|
|
20000
|
+
return lines.join("\n");
|
|
19069
20001
|
}
|
|
19070
|
-
function
|
|
19071
|
-
|
|
19072
|
-
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(raw);
|
|
19073
|
-
if (!m) return null;
|
|
19074
|
-
const year = Number(m[1]);
|
|
19075
|
-
const month = Number(m[2]);
|
|
19076
|
-
const day = Number(m[3]);
|
|
19077
|
-
const ms = Date.UTC(year, month - 1, day);
|
|
19078
|
-
if (!Number.isFinite(ms)) return null;
|
|
19079
|
-
const d = new Date(ms);
|
|
19080
|
-
if (d.getUTCFullYear() !== year || d.getUTCMonth() + 1 !== month || d.getUTCDate() !== day) {
|
|
19081
|
-
return null;
|
|
19082
|
-
}
|
|
19083
|
-
return ms;
|
|
20002
|
+
function formatEntityFileName(entityId) {
|
|
20003
|
+
return `${sanitizeForFilename(entityId)}.md`;
|
|
19084
20004
|
}
|
|
19085
|
-
function
|
|
19086
|
-
|
|
19087
|
-
|
|
19088
|
-
|
|
19089
|
-
|
|
19090
|
-
|
|
19091
|
-
|
|
19092
|
-
|
|
19093
|
-
|
|
19094
|
-
|
|
19095
|
-
|
|
19096
|
-
|
|
19097
|
-
|
|
19098
|
-
|
|
19099
|
-
|
|
19100
|
-
|
|
19101
|
-
|
|
20005
|
+
function formatMemoryDump(dump) {
|
|
20006
|
+
const files = Object.entries(dump.entities).map(([entityId, bundle]) => ({
|
|
20007
|
+
name: formatEntityFileName(entityId),
|
|
20008
|
+
content: renderEntity(entityId, bundle, dump.generatedAt)
|
|
20009
|
+
}));
|
|
20010
|
+
const manifestDump = {
|
|
20011
|
+
generatedAt: dump.generatedAt,
|
|
20012
|
+
entities: Object.fromEntries(
|
|
20013
|
+
Object.entries(dump.entities).map(([entityId, bundle]) => [
|
|
20014
|
+
entityId,
|
|
20015
|
+
{
|
|
20016
|
+
...bundle,
|
|
20017
|
+
facts: bundle.facts.map((f) => {
|
|
20018
|
+
const { embedding_blob: _blob, ...rest } = f;
|
|
20019
|
+
return rest;
|
|
20020
|
+
})
|
|
20021
|
+
}
|
|
20022
|
+
])
|
|
20023
|
+
)
|
|
20024
|
+
};
|
|
20025
|
+
return {
|
|
20026
|
+
manifest: JSON.stringify(manifestDump, null, 2),
|
|
20027
|
+
files
|
|
20028
|
+
};
|
|
19102
20029
|
}
|
|
19103
|
-
|
|
19104
|
-
|
|
20030
|
+
var DEFAULT_PROFILE = "llm-wiki/3";
|
|
20031
|
+
var FACT_MAPPED2 = new Set(FACT_MAPPED_KEYS);
|
|
20032
|
+
var TASK_MAPPED2 = new Set(TASK_MAPPED_KEYS);
|
|
20033
|
+
var RAW_SLOT_KEY2 = "x-llm-wiki-raw";
|
|
20034
|
+
function isoOrFallback(updatedAt) {
|
|
20035
|
+
if (!Number.isFinite(updatedAt)) return (/* @__PURE__ */ new Date(0)).toISOString();
|
|
20036
|
+
const d = new Date(updatedAt);
|
|
20037
|
+
if (!Number.isFinite(d.getTime())) return (/* @__PURE__ */ new Date(0)).toISOString();
|
|
20038
|
+
return d.toISOString();
|
|
19105
20039
|
}
|
|
19106
|
-
|
|
19107
|
-
|
|
19108
|
-
const
|
|
19109
|
-
if (!
|
|
19110
|
-
|
|
19111
|
-
const event_type = EVENT_TYPES.has(rawType) ? rawType : "observation";
|
|
19112
|
-
if (linkPath) {
|
|
19113
|
-
return { event_type, summary: unescapeLogSummary(linkedSummary), linkPath };
|
|
19114
|
-
}
|
|
19115
|
-
return { event_type, summary: unescapeLogSummary((plainSummary ?? "").trim()) };
|
|
20040
|
+
function isoDateOrOmit(ms) {
|
|
20041
|
+
if (ms == null || !Number.isFinite(ms)) return void 0;
|
|
20042
|
+
const d = new Date(ms);
|
|
20043
|
+
if (!Number.isFinite(d.getTime())) return void 0;
|
|
20044
|
+
return d.toISOString().slice(0, 10);
|
|
19116
20045
|
}
|
|
19117
|
-
function
|
|
19118
|
-
|
|
19119
|
-
|
|
19120
|
-
|
|
19121
|
-
|
|
19122
|
-
|
|
19123
|
-
|
|
19124
|
-
|
|
19125
|
-
|
|
19126
|
-
|
|
19127
|
-
|
|
19128
|
-
|
|
19129
|
-
const
|
|
19130
|
-
const
|
|
19131
|
-
|
|
19132
|
-
const
|
|
19133
|
-
|
|
19134
|
-
|
|
19135
|
-
|
|
19136
|
-
|
|
19137
|
-
|
|
19138
|
-
|
|
19139
|
-
|
|
19140
|
-
|
|
20046
|
+
function staleAfterFrontmatterV3(staleAfter, staleAfterRaw) {
|
|
20047
|
+
if (staleAfterRaw != null && staleAfterRaw !== "") return { stale_after: staleAfterRaw };
|
|
20048
|
+
if (staleAfter == null || !Number.isFinite(staleAfter)) return {};
|
|
20049
|
+
const d = new Date(staleAfter);
|
|
20050
|
+
if (!Number.isFinite(d.getTime())) return {};
|
|
20051
|
+
const utcMidnight = d.getUTCHours() === 0 && d.getUTCMinutes() === 0 && d.getUTCSeconds() === 0 && d.getUTCMilliseconds() === 0;
|
|
20052
|
+
return { stale_after: utcMidnight ? d.toISOString().slice(0, 10) : d.toISOString() };
|
|
20053
|
+
}
|
|
20054
|
+
function plainObjectOrNull2(value) {
|
|
20055
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
20056
|
+
}
|
|
20057
|
+
function okfExtraEmission(okfExtra, mapped) {
|
|
20058
|
+
const emission = { extras: {}, generatedNested: {}, rawBlocks: [] };
|
|
20059
|
+
const extra = plainObjectOrNull2(okfExtra);
|
|
20060
|
+
if (!extra) return emission;
|
|
20061
|
+
for (const [key, value] of Object.entries(extra)) {
|
|
20062
|
+
if (key === RAW_SLOT_KEY2) continue;
|
|
20063
|
+
if (key === "generated") {
|
|
20064
|
+
const nested = plainObjectOrNull2(value);
|
|
20065
|
+
if (nested) {
|
|
20066
|
+
for (const [k, v] of Object.entries(nested)) {
|
|
20067
|
+
if (k === "by" || k === "at") continue;
|
|
20068
|
+
if (k === "__proto__") continue;
|
|
20069
|
+
emission.generatedNested[k] = v;
|
|
20070
|
+
}
|
|
20071
|
+
}
|
|
20072
|
+
continue;
|
|
20073
|
+
}
|
|
20074
|
+
if (mapped.has(key)) continue;
|
|
20075
|
+
if (key === "__proto__") continue;
|
|
20076
|
+
emission.extras[key] = value;
|
|
20077
|
+
}
|
|
20078
|
+
for (const [key, value] of Object.entries(extra)) {
|
|
20079
|
+
if (key !== RAW_SLOT_KEY2) continue;
|
|
20080
|
+
const slot = plainObjectOrNull2(value);
|
|
20081
|
+
if (slot) {
|
|
20082
|
+
for (const [blockKey, lines] of Object.entries(slot)) {
|
|
20083
|
+
if (mapped.has(blockKey)) continue;
|
|
20084
|
+
if (Object.prototype.hasOwnProperty.call(emission.extras, blockKey)) {
|
|
20085
|
+
const value2 = emission.extras[blockKey];
|
|
20086
|
+
const text = typeof lines === "string" ? lines.slice(lines.indexOf(":") + 1).trim() : "";
|
|
20087
|
+
const same = typeof value2 === "number" && text !== "" && Number(text) === value2 || typeof value2 === "string" && text === value2.trim();
|
|
20088
|
+
if (same && typeof lines === "string" && lines.length > 0) {
|
|
20089
|
+
emission.rawBlocks.push(lines);
|
|
20090
|
+
}
|
|
20091
|
+
continue;
|
|
20092
|
+
}
|
|
20093
|
+
if (typeof lines === "string" && lines.length > 0 && isValidRawBlockEntry(blockKey, lines, mapped)) {
|
|
20094
|
+
emission.rawBlocks.push(lines);
|
|
20095
|
+
}
|
|
20096
|
+
}
|
|
19141
20097
|
}
|
|
20098
|
+
continue;
|
|
19142
20099
|
}
|
|
20100
|
+
return emission;
|
|
20101
|
+
}
|
|
20102
|
+
function sourcePointerFrontmatter(p) {
|
|
20103
|
+
if (!p) return void 0;
|
|
19143
20104
|
return {
|
|
19144
|
-
|
|
19145
|
-
|
|
19146
|
-
|
|
19147
|
-
|
|
19148
|
-
|
|
19149
|
-
|
|
19150
|
-
|
|
19151
|
-
|
|
19152
|
-
|
|
19153
|
-
|
|
19154
|
-
|
|
19155
|
-
|
|
19156
|
-
|
|
19157
|
-
|
|
19158
|
-
|
|
20105
|
+
...p.event_id != null ? { event_id: p.event_id } : {},
|
|
20106
|
+
...p.ref != null ? { ref: p.ref } : {},
|
|
20107
|
+
...p.quote != null ? { quote: p.quote } : {},
|
|
20108
|
+
...p.position != null ? { position: p.position } : {}
|
|
20109
|
+
};
|
|
20110
|
+
}
|
|
20111
|
+
function factFrontmatterV2(f) {
|
|
20112
|
+
return {
|
|
20113
|
+
type: f.okf_type || "fact",
|
|
20114
|
+
title: f.title,
|
|
20115
|
+
tags: f.tags,
|
|
20116
|
+
// `timestamp` rides along deliberately even on the v0.2 path — a naive
|
|
20117
|
+
// consumer that only understands the v0.1 key still gets a readable date
|
|
20118
|
+
// without needing flow-mapping support. `generated.at` is the canonical
|
|
20119
|
+
// v0.2 field and always wins on import when both are present (spec §2.4).
|
|
20120
|
+
timestamp: isoOrFallback(f.updated_at),
|
|
20121
|
+
resource: f.source_ref ?? void 0,
|
|
20122
|
+
id: f.id,
|
|
20123
|
+
entity_id: f.entity_id,
|
|
20124
|
+
confidence: f.confidence,
|
|
20125
|
+
source_type: f.source_type,
|
|
20126
|
+
source_hash: f.source_hash,
|
|
20127
|
+
created_at: f.created_at,
|
|
20128
|
+
access_count: f.access_count,
|
|
20129
|
+
last_accessed_at: f.last_accessed_at,
|
|
20130
|
+
deleted_at: f.deleted_at,
|
|
19159
20131
|
// OKF v0.2
|
|
19160
|
-
lifecycle_status,
|
|
19161
|
-
stale_after,
|
|
19162
|
-
|
|
19163
|
-
|
|
19164
|
-
|
|
19165
|
-
|
|
19166
|
-
|
|
19167
|
-
|
|
19168
|
-
|
|
19169
|
-
|
|
19170
|
-
...
|
|
19171
|
-
...
|
|
19172
|
-
...
|
|
19173
|
-
//
|
|
19174
|
-
|
|
19175
|
-
|
|
19176
|
-
|
|
19177
|
-
|
|
19178
|
-
|
|
19179
|
-
|
|
19180
|
-
|
|
19181
|
-
|
|
19182
|
-
|
|
19183
|
-
if (v === void 0) {
|
|
19184
|
-
droppedPointerValues.push({ factId: id, reason: "malformed" });
|
|
19185
|
-
return {};
|
|
19186
|
-
}
|
|
19187
|
-
return { source_pointer: v };
|
|
19188
|
-
})(),
|
|
19189
|
-
// derived_events (specs/inplace-update-provenance §5): a well-formed list
|
|
19190
|
-
// is restored; absent or empty omits the property (import presence rule);
|
|
19191
|
-
// malformed omits it AND is reported by id + slug, never the raw value.
|
|
19192
|
-
...(() => {
|
|
19193
|
-
const raw = frontmatter.derived_events;
|
|
19194
|
-
if (raw === void 0) return {};
|
|
19195
|
-
const v = validateDerivedEventsValue(raw);
|
|
19196
|
-
if (v === void 0) {
|
|
19197
|
-
droppedPointerValues.push({ factId: id, reason: "derived_events_malformed" });
|
|
19198
|
-
return {};
|
|
19199
|
-
}
|
|
19200
|
-
return v ? { derived_events: v } : {};
|
|
19201
|
-
})()
|
|
20132
|
+
status: f.lifecycle_status ?? "stable",
|
|
20133
|
+
...isoDateOrOmit(f.stale_after) ? { stale_after: isoDateOrOmit(f.stale_after) } : {},
|
|
20134
|
+
// Omit `generated` entirely when there's no actor on record — never
|
|
20135
|
+
// fabricate a `generated_by` (mirrors the import side's rule in §4.8:
|
|
20136
|
+
// it never invents one either, so export must not manufacture one that
|
|
20137
|
+
// would then round-trip back in as if it had always been asserted).
|
|
20138
|
+
...f.generated_by ? { generated: { by: f.generated_by, at: isoOrFallback(f.updated_at) } } : {},
|
|
20139
|
+
// Omit `verified`/`sources` when empty — an emitted `[]` is not the same
|
|
20140
|
+
// shape as an absent key (spec §5.3 derives `unverified` from "no
|
|
20141
|
+
// `verified` key", not from "empty `verified` list").
|
|
20142
|
+
...f.okf_verified && f.okf_verified.length > 0 ? { verified: f.okf_verified } : {},
|
|
20143
|
+
...f.okf_sources && f.okf_sources.length > 0 ? { sources: f.okf_sources } : {},
|
|
20144
|
+
...f.okf_usage_window ? { usage_window: f.okf_usage_window } : {},
|
|
20145
|
+
// Temporal (spec 2026-09-29 §10.9): flat epoch-ms keys, like created_at.
|
|
20146
|
+
...f.valid_from != null ? { valid_from: f.valid_from } : {},
|
|
20147
|
+
...f.valid_to != null ? { valid_to: f.valid_to } : {},
|
|
20148
|
+
...f.superseded_by != null ? { superseded_by: f.superseded_by } : {},
|
|
20149
|
+
...f.superseded_at != null ? { superseded_at: f.superseded_at } : {},
|
|
20150
|
+
...f.prior_valid_to != null ? { prior_valid_to: f.prior_valid_to } : {},
|
|
20151
|
+
// Source pointer (specs/source-pointers): map only when non-null; null slots omitted.
|
|
20152
|
+
...sourcePointerFrontmatter(f.source_pointer) ? { source_pointer: sourcePointerFrontmatter(f.source_pointer) } : {},
|
|
20153
|
+
// derived_events (specs/inplace-update-provenance §5): optional list, only when non-empty.
|
|
20154
|
+
...f.derived_events && f.derived_events.length > 0 ? { derived_events: f.derived_events } : {}
|
|
19202
20155
|
};
|
|
19203
20156
|
}
|
|
19204
|
-
function
|
|
19205
|
-
return
|
|
20157
|
+
function taskFrontmatterV2(t) {
|
|
20158
|
+
return {
|
|
20159
|
+
type: t.okf_type || "task",
|
|
20160
|
+
title: t.description,
|
|
20161
|
+
timestamp: isoOrFallback(t.updated_at),
|
|
20162
|
+
// see factFrontmatterV2 comment — deliberate back-compat duplication
|
|
20163
|
+
id: t.id,
|
|
20164
|
+
entity_id: t.entity_id,
|
|
20165
|
+
status: t.lifecycle_status ?? "stable",
|
|
20166
|
+
// OKF v0.2 lifecycle
|
|
20167
|
+
execution_status: t.status,
|
|
20168
|
+
// execution state under renamed key
|
|
20169
|
+
priority: t.priority,
|
|
20170
|
+
created_at: t.created_at,
|
|
20171
|
+
resolved_at: t.resolved_at,
|
|
20172
|
+
deleted_at: t.deleted_at,
|
|
20173
|
+
// OKF v0.2 — symmetric with facts (spec §2.5): stale_after applies to
|
|
20174
|
+
// tasks too (a hallucinated task needs a freshness signal as much as a
|
|
20175
|
+
// hallucinated fact does).
|
|
20176
|
+
...isoDateOrOmit(t.stale_after) ? { stale_after: isoDateOrOmit(t.stale_after) } : {},
|
|
20177
|
+
...t.generated_by ? { generated: { by: t.generated_by, at: isoOrFallback(t.updated_at) } } : {},
|
|
20178
|
+
...t.okf_verified && t.okf_verified.length > 0 ? { verified: t.okf_verified } : {},
|
|
20179
|
+
...t.okf_sources && t.okf_sources.length > 0 ? { sources: t.okf_sources } : {},
|
|
20180
|
+
...t.okf_usage_window ? { usage_window: t.okf_usage_window } : {}
|
|
20181
|
+
};
|
|
19206
20182
|
}
|
|
19207
|
-
function
|
|
19208
|
-
const
|
|
19209
|
-
const
|
|
19210
|
-
|
|
19211
|
-
|
|
19212
|
-
|
|
19213
|
-
|
|
19214
|
-
|
|
19215
|
-
|
|
19216
|
-
|
|
19217
|
-
|
|
19218
|
-
|
|
19219
|
-
|
|
19220
|
-
|
|
19221
|
-
|
|
19222
|
-
|
|
19223
|
-
|
|
19224
|
-
|
|
19225
|
-
|
|
19226
|
-
|
|
19227
|
-
|
|
19228
|
-
|
|
19229
|
-
|
|
19230
|
-
}
|
|
20183
|
+
function wireProjectionV3(f, dumpGeneratedAt, idToConceptPath) {
|
|
20184
|
+
const stored = f.lifecycle_status ?? "stable";
|
|
20185
|
+
const ended = Number.isFinite(dumpGeneratedAt) && f.valid_to != null && f.valid_to <= dumpGeneratedAt;
|
|
20186
|
+
return {
|
|
20187
|
+
...f.superseded_by != null && idToConceptPath.has(f.superseded_by) ? { superseded_by: `/${idToConceptPath.get(f.superseded_by)}` } : {},
|
|
20188
|
+
...ended && stored !== "deprecated" ? { status: "deprecated", "x-llm-wiki-lifecycle": stored } : {}
|
|
20189
|
+
};
|
|
20190
|
+
}
|
|
20191
|
+
function factFrontmatterV3(f, emission, projection = {}) {
|
|
20192
|
+
return {
|
|
20193
|
+
...factFrontmatterV2(f),
|
|
20194
|
+
...projection,
|
|
20195
|
+
...staleAfterFrontmatterV3(f.stale_after, f.stale_after_raw),
|
|
20196
|
+
...f.generated_by ? { generated: { by: f.generated_by, at: isoOrFallback(f.updated_at), ...emission.generatedNested } } : {},
|
|
20197
|
+
...emission.extras
|
|
20198
|
+
};
|
|
20199
|
+
}
|
|
20200
|
+
function taskFrontmatterV3(t, emission) {
|
|
20201
|
+
return {
|
|
20202
|
+
...taskFrontmatterV2(t),
|
|
20203
|
+
...staleAfterFrontmatterV3(t.stale_after, t.stale_after_raw),
|
|
20204
|
+
...t.generated_by ? { generated: { by: t.generated_by, at: isoOrFallback(t.updated_at), ...emission.generatedNested } } : {},
|
|
20205
|
+
...emission.extras
|
|
20206
|
+
};
|
|
20207
|
+
}
|
|
20208
|
+
function factFrontmatterV1(f) {
|
|
20209
|
+
return {
|
|
20210
|
+
type: f.okf_type || "fact",
|
|
20211
|
+
title: f.title,
|
|
20212
|
+
tags: f.tags,
|
|
20213
|
+
timestamp: isoOrFallback(f.updated_at),
|
|
20214
|
+
resource: f.source_ref ?? void 0,
|
|
20215
|
+
id: f.id,
|
|
20216
|
+
entity_id: f.entity_id,
|
|
20217
|
+
confidence: f.confidence,
|
|
20218
|
+
source_type: f.source_type,
|
|
20219
|
+
source_hash: f.source_hash,
|
|
20220
|
+
created_at: f.created_at,
|
|
20221
|
+
access_count: f.access_count,
|
|
20222
|
+
last_accessed_at: f.last_accessed_at,
|
|
20223
|
+
deleted_at: f.deleted_at,
|
|
20224
|
+
// Source pointer (specs/source-pointers): same map rule as the v2 path.
|
|
20225
|
+
...sourcePointerFrontmatter(f.source_pointer) ? { source_pointer: sourcePointerFrontmatter(f.source_pointer) } : {},
|
|
20226
|
+
// derived_events (specs/inplace-update-provenance §5): optional list, only when non-empty.
|
|
20227
|
+
...f.derived_events && f.derived_events.length > 0 ? { derived_events: f.derived_events } : {}
|
|
20228
|
+
};
|
|
20229
|
+
}
|
|
20230
|
+
function taskFrontmatterV1(t) {
|
|
19231
20231
|
return {
|
|
19232
|
-
|
|
19233
|
-
|
|
19234
|
-
|
|
19235
|
-
|
|
19236
|
-
|
|
19237
|
-
|
|
19238
|
-
|
|
19239
|
-
|
|
19240
|
-
|
|
19241
|
-
|
|
19242
|
-
// OKF v0.2
|
|
19243
|
-
lifecycle_status,
|
|
19244
|
-
stale_after,
|
|
19245
|
-
generated_by: frontmatter.generated?.by ?? null,
|
|
19246
|
-
okf_sources: sources,
|
|
19247
|
-
okf_verified: verified,
|
|
19248
|
-
okf_usage_window: usageWindow,
|
|
19249
|
-
last_verified_at: lastV?.at ?? null,
|
|
19250
|
-
last_verified_by: lastV?.by ?? null
|
|
20232
|
+
type: t.okf_type || "task",
|
|
20233
|
+
title: t.description,
|
|
20234
|
+
timestamp: isoOrFallback(t.updated_at),
|
|
20235
|
+
id: t.id,
|
|
20236
|
+
entity_id: t.entity_id,
|
|
20237
|
+
status: t.status,
|
|
20238
|
+
priority: t.priority,
|
|
20239
|
+
created_at: t.created_at,
|
|
20240
|
+
resolved_at: t.resolved_at,
|
|
20241
|
+
deleted_at: t.deleted_at
|
|
19251
20242
|
};
|
|
19252
20243
|
}
|
|
19253
|
-
function
|
|
19254
|
-
return
|
|
20244
|
+
function formatLogDate(timestampMs) {
|
|
20245
|
+
return new Date(timestampMs).toISOString().slice(0, 10);
|
|
19255
20246
|
}
|
|
19256
|
-
function
|
|
19257
|
-
|
|
19258
|
-
|
|
19259
|
-
|
|
19260
|
-
|
|
19261
|
-
|
|
19262
|
-
|
|
19263
|
-
|
|
19264
|
-
const edgeKey = `${resolvedId}\0${targetId}\0${link.text}`;
|
|
19265
|
-
if (seenEdges.has(edgeKey)) continue;
|
|
19266
|
-
seenEdges.add(edgeKey);
|
|
19267
|
-
edges.push({
|
|
19268
|
-
id: generateId(),
|
|
19269
|
-
entity_id: entityId,
|
|
19270
|
-
source_id: resolvedId,
|
|
19271
|
-
target_id: targetId,
|
|
19272
|
-
edge_type: link.text,
|
|
19273
|
-
created_at: now
|
|
19274
|
-
});
|
|
19275
|
-
}
|
|
20247
|
+
function conceptRelativePath(sourceFilePath, targetFilePath) {
|
|
20248
|
+
const sourceDir = sourceFilePath.slice(0, sourceFilePath.lastIndexOf("/"));
|
|
20249
|
+
const targetDir = targetFilePath.slice(0, targetFilePath.lastIndexOf("/"));
|
|
20250
|
+
const targetName = targetFilePath.slice(targetFilePath.lastIndexOf("/") + 1);
|
|
20251
|
+
if (sourceDir === targetDir) return `./${targetName}`;
|
|
20252
|
+
if (sourceDir.endsWith("/facts") && targetDir.endsWith("/tasks")) return `../tasks/${targetName}`;
|
|
20253
|
+
if (sourceDir.endsWith("/tasks") && targetDir.endsWith("/facts")) return `../facts/${targetName}`;
|
|
20254
|
+
return targetFilePath.replace(/^entities\/[^/]+\//, "");
|
|
19276
20255
|
}
|
|
19277
|
-
function
|
|
19278
|
-
|
|
19279
|
-
|
|
19280
|
-
|
|
19281
|
-
|
|
19282
|
-
|
|
19283
|
-
|
|
19284
|
-
|
|
19285
|
-
|
|
19286
|
-
|
|
19287
|
-
|
|
20256
|
+
function buildEventLogEntries(events, factIdToFilename) {
|
|
20257
|
+
return events.filter((e) => e.forgotten_at == null).map((e) => {
|
|
20258
|
+
const factFilename = e.related_entry_id ? factIdToFilename.get(e.related_entry_id) : void 0;
|
|
20259
|
+
const summary = e.summary.replace(/\\/g, "\\\\").replace(/\[/g, "\\[").replace(/\]/g, "\\]").replace(/\r?\n/g, " ");
|
|
20260
|
+
const text = factFilename ? `(${e.event_type}) [${summary}](./facts/${factFilename}.md)` : `(${e.event_type}) ${summary}`;
|
|
20261
|
+
const occurred = createdAtValue(e.occurred_at);
|
|
20262
|
+
const logTime = e.occurred_at != null && isUsableDate(occurred) && occurred >= OKF_DATE_MIN && occurred <= OKF_DATE_MAX && occurred <= e.created_at ? occurred : e.created_at;
|
|
20263
|
+
return { date: formatLogDate(logTime), text: coreOkf.appendEventIdComment(text, e.id) };
|
|
20264
|
+
});
|
|
20265
|
+
}
|
|
20266
|
+
var OKF_DATE_MIN = -621672192e5;
|
|
20267
|
+
var OKF_DATE_MAX = 253402300799999;
|
|
20268
|
+
function formatOkfBundle(dump, options) {
|
|
20269
|
+
const profile = options?.profile ?? DEFAULT_PROFILE;
|
|
20270
|
+
const isV3 = profile === "llm-wiki/3";
|
|
20271
|
+
const okfVersion = profile === "llm-wiki/1" ? "0.1" : profile === "llm-wiki/2" ? "0.2" : "0.3";
|
|
20272
|
+
const factFm = profile === "llm-wiki/1" ? factFrontmatterV1 : factFrontmatterV2;
|
|
20273
|
+
const taskFm = profile === "llm-wiki/1" ? taskFrontmatterV1 : taskFrontmatterV2;
|
|
20274
|
+
const files = [];
|
|
20275
|
+
const rootEntries = [];
|
|
20276
|
+
const entityBundles = Object.values(dump.entities);
|
|
20277
|
+
const carried = entityBundles.map((b) => b.bundleMetadata).filter((m) => m !== void 0);
|
|
20278
|
+
const bundleMetadata = dump.bundleMetadata !== void 0 ? dump.bundleMetadata : entityBundles.length === 1 && carried.length === 1 ? carried[0] : void 0;
|
|
20279
|
+
for (const [entityId, bundle] of Object.entries(dump.entities)) {
|
|
20280
|
+
let relatedLinksFor2 = function(sourcePath, sourceId) {
|
|
20281
|
+
return (edgesBySource.get(sourceId) ?? []).map((edge) => {
|
|
20282
|
+
const targetPath = idToConceptPath.get(edge.target_id);
|
|
20283
|
+
if (!targetPath) return null;
|
|
20284
|
+
return { edge_type: edge.edge_type, path: conceptRelativePath(sourcePath, targetPath) };
|
|
20285
|
+
}).filter((link) => link != null);
|
|
20286
|
+
};
|
|
20287
|
+
const dir = sanitizeForFilename(entityId);
|
|
20288
|
+
const factIdToFilename = new Map(
|
|
20289
|
+
bundle.facts.map((f) => [f.id, sanitizeConceptId(f.id)])
|
|
19288
20290
|
);
|
|
19289
|
-
|
|
19290
|
-
|
|
19291
|
-
|
|
19292
|
-
const allowedFiles = allowlistedFiles.filter(
|
|
19293
|
-
(f) => f.path === "index.md" || f.path.startsWith(entityPrefix)
|
|
19294
|
-
);
|
|
19295
|
-
const rootIndex = allowedFiles.find((f) => f.path === "index.md");
|
|
19296
|
-
const profileMeta = rootIndex ? coreOkf.parseRootIndexMd(rootIndex.content) : {};
|
|
19297
|
-
const okfVersion = profileMeta.okf_version;
|
|
19298
|
-
const profile = profileMeta.profile;
|
|
19299
|
-
const isProfile1 = profile === "llm-wiki/1";
|
|
19300
|
-
const isProfile2 = profile === "llm-wiki/2";
|
|
19301
|
-
const isLegacyV1 = profile === void 0 && okfVersion === "0.1";
|
|
19302
|
-
const isVersionOnlyV2 = profile === void 0 && okfVersion === "0.2";
|
|
19303
|
-
const isUnknownProfileV2 = profile !== void 0 && profile !== "llm-wiki/1" && profile !== "llm-wiki/2" && okfVersion === "0.2";
|
|
19304
|
-
const summaryEligible = isProfile1 || isProfile2 || isLegacyV1 || isVersionOnlyV2 || isUnknownProfileV2;
|
|
19305
|
-
let entitySummary;
|
|
19306
|
-
const entityIndex = allowedFiles.find((f) => f.path === `${entityPrefix}index.md`);
|
|
19307
|
-
if (summaryEligible && entityIndex) {
|
|
19308
|
-
const summary = coreOkf.parseEntityIndexMd(entityIndex.content).summary;
|
|
19309
|
-
entitySummary = summary || void 0;
|
|
19310
|
-
}
|
|
19311
|
-
const pathToResolvedId = /* @__PURE__ */ new Map();
|
|
19312
|
-
for (const file of allowedFiles) {
|
|
19313
|
-
if (!isConceptFile(file.path)) continue;
|
|
19314
|
-
const { frontmatter } = coreOkf.parseConcept(file.content);
|
|
19315
|
-
const route = resolveRoute(file.path, frontmatter.type ?? "", options);
|
|
19316
|
-
if (route === "ignore") continue;
|
|
19317
|
-
const resolvedId = typeof frontmatter.id === "string" && frontmatter.id ? frontmatter.id : basenameMd(file.path);
|
|
19318
|
-
addPathAliases(pathToResolvedId, file.path, resolvedId);
|
|
19319
|
-
}
|
|
19320
|
-
const facts = [];
|
|
19321
|
-
const tasks = [];
|
|
19322
|
-
const droppedPointerValues = [];
|
|
19323
|
-
const edges = [];
|
|
19324
|
-
let logContent = null;
|
|
19325
|
-
const logMdPath = findLogMdPath(allowedFiles);
|
|
19326
|
-
for (const file of allowedFiles) {
|
|
19327
|
-
if (file.path.endsWith("/log.md") || file.path === "log.md") {
|
|
19328
|
-
logContent = file.content;
|
|
19329
|
-
continue;
|
|
20291
|
+
const idToConceptPath = /* @__PURE__ */ new Map();
|
|
20292
|
+
for (const f of bundle.facts) {
|
|
20293
|
+
idToConceptPath.set(f.id, `entities/${dir}/facts/${factIdToFilename.get(f.id)}.md`);
|
|
19330
20294
|
}
|
|
19331
|
-
|
|
19332
|
-
|
|
19333
|
-
const route = resolveRoute(file.path, frontmatter.type ?? "", options);
|
|
19334
|
-
if (route === "ignore") continue;
|
|
19335
|
-
const resolvedId = typeof frontmatter.id === "string" && frontmatter.id ? frontmatter.id : basenameMd(file.path);
|
|
19336
|
-
const { body: storedBody, relatedLinks } = coreOkf.splitRelatedSection(body);
|
|
19337
|
-
const edgeLinks = isProfile1 || isLegacyV1 ? relatedLinks : [...relatedLinks, ...coreOkf.extractMarkdownLinks(storedBody)];
|
|
19338
|
-
const usesV1StatusRule = isProfile1 || isLegacyV1 || profile === void 0 && okfVersion === void 0;
|
|
19339
|
-
if (route === "fact") {
|
|
19340
|
-
facts.push(frontmatterToFact(entityId, resolvedId, frontmatter, storedBody, now, droppedPointerValues));
|
|
19341
|
-
} else {
|
|
19342
|
-
tasks.push(frontmatterToTask(entityId, resolvedId, frontmatter, now, usesV1StatusRule));
|
|
20295
|
+
for (const t of bundle.tasks) {
|
|
20296
|
+
idToConceptPath.set(t.id, `entities/${dir}/tasks/${sanitizeConceptId(t.id)}.md`);
|
|
19343
20297
|
}
|
|
19344
|
-
const
|
|
19345
|
-
|
|
19346
|
-
|
|
19347
|
-
|
|
19348
|
-
|
|
19349
|
-
|
|
19350
|
-
|
|
19351
|
-
|
|
19352
|
-
|
|
19353
|
-
|
|
19354
|
-
)
|
|
19355
|
-
|
|
19356
|
-
|
|
19357
|
-
|
|
19358
|
-
|
|
19359
|
-
|
|
19360
|
-
|
|
19361
|
-
|
|
19362
|
-
|
|
19363
|
-
|
|
19364
|
-
|
|
19365
|
-
|
|
19366
|
-
|
|
19367
|
-
logPath,
|
|
19368
|
-
stripLinkSuffix(decodeLinkPath(parsed.linkPath))
|
|
20298
|
+
const edgesBySource = /* @__PURE__ */ new Map();
|
|
20299
|
+
for (const edge of bundle.edges ?? []) {
|
|
20300
|
+
const group = edgesBySource.get(edge.source_id) ?? [];
|
|
20301
|
+
group.push(edge);
|
|
20302
|
+
edgesBySource.set(edge.source_id, group);
|
|
20303
|
+
}
|
|
20304
|
+
const factEntries = bundle.facts.map((f) => ({
|
|
20305
|
+
path: `facts/${factIdToFilename.get(f.id)}.md`,
|
|
20306
|
+
title: f.title
|
|
20307
|
+
}));
|
|
20308
|
+
for (const f of bundle.facts) {
|
|
20309
|
+
const factPath = `entities/${dir}/facts/${factIdToFilename.get(f.id)}.md`;
|
|
20310
|
+
const factBody = coreOkf.appendRelatedSection(f.body, relatedLinksFor2(factPath, f.id));
|
|
20311
|
+
let content;
|
|
20312
|
+
if (isV3) {
|
|
20313
|
+
const emission = okfExtraEmission(f.okf_extra, FACT_MAPPED2);
|
|
20314
|
+
content = coreOkf.buildConceptDocument(
|
|
20315
|
+
factFrontmatterV3(f, emission, wireProjectionV3(f, dump.generatedAt, idToConceptPath)),
|
|
20316
|
+
factBody,
|
|
20317
|
+
// §A7/§B8: the stored raw lines go out verbatim, after the builder's
|
|
20318
|
+
// keys; the option is omitted so an extras-free row keeps the exact
|
|
20319
|
+
// pre-v0.3 bytes.
|
|
20320
|
+
emission.rawBlocks.length > 0 ? { rawBlocks: emission.rawBlocks } : void 0
|
|
19369
20321
|
);
|
|
19370
|
-
|
|
19371
|
-
|
|
19372
|
-
}
|
|
20322
|
+
} else {
|
|
20323
|
+
content = coreOkf.buildConceptDocument(factFm(f), factBody);
|
|
19373
20324
|
}
|
|
19374
|
-
|
|
19375
|
-
if (!Number.isFinite(created_at)) continue;
|
|
19376
|
-
if (eventId === void 0) pending.push({ index: events.length, date: entry.date });
|
|
19377
|
-
events.push({
|
|
19378
|
-
id: eventId ?? "",
|
|
19379
|
-
entity_id: entityId,
|
|
19380
|
-
event_type: parsed.event_type,
|
|
19381
|
-
summary: parsed.summary,
|
|
19382
|
-
related_entry_id,
|
|
19383
|
-
created_at
|
|
19384
|
-
});
|
|
20325
|
+
files.push({ path: factPath, content });
|
|
19385
20326
|
}
|
|
19386
|
-
const
|
|
19387
|
-
|
|
19388
|
-
|
|
19389
|
-
|
|
19390
|
-
|
|
19391
|
-
|
|
19392
|
-
const
|
|
19393
|
-
let
|
|
19394
|
-
|
|
19395
|
-
|
|
19396
|
-
|
|
20327
|
+
const taskEntries = bundle.tasks.map((t) => ({
|
|
20328
|
+
path: `tasks/${sanitizeConceptId(t.id)}.md`,
|
|
20329
|
+
title: t.description
|
|
20330
|
+
}));
|
|
20331
|
+
for (const t of bundle.tasks) {
|
|
20332
|
+
const taskPath = `entities/${dir}/tasks/${sanitizeConceptId(t.id)}.md`;
|
|
20333
|
+
const taskBody = coreOkf.appendRelatedSection("", relatedLinksFor2(taskPath, t.id));
|
|
20334
|
+
let content;
|
|
20335
|
+
if (isV3) {
|
|
20336
|
+
const emission = okfExtraEmission(t.okf_extra, TASK_MAPPED2);
|
|
20337
|
+
content = coreOkf.buildConceptDocument(
|
|
20338
|
+
taskFrontmatterV3(t, emission),
|
|
20339
|
+
taskBody,
|
|
20340
|
+
emission.rawBlocks.length > 0 ? { rawBlocks: emission.rawBlocks } : void 0
|
|
20341
|
+
);
|
|
20342
|
+
} else {
|
|
20343
|
+
content = coreOkf.buildConceptDocument(taskFm(t), taskBody);
|
|
19397
20344
|
}
|
|
19398
|
-
|
|
19399
|
-
nextOccurrence.set(key, occurrence + 1);
|
|
19400
|
-
e.id = id;
|
|
20345
|
+
files.push({ path: taskPath, content });
|
|
19401
20346
|
}
|
|
20347
|
+
files.push({
|
|
20348
|
+
path: `entities/${dir}/log.md`,
|
|
20349
|
+
content: coreOkf.buildLogMd(buildEventLogEntries(bundle.events, factIdToFilename))
|
|
20350
|
+
});
|
|
20351
|
+
const entityIndexSections = [
|
|
20352
|
+
{ heading: "Facts", entries: factEntries },
|
|
20353
|
+
{ heading: "Tasks", entries: taskEntries }
|
|
20354
|
+
];
|
|
20355
|
+
files.push({
|
|
20356
|
+
path: `entities/${dir}/index.md`,
|
|
20357
|
+
content: coreOkf.buildEntityIndexMd({
|
|
20358
|
+
summary: bundle.summary,
|
|
20359
|
+
sections: entityIndexSections
|
|
20360
|
+
})
|
|
20361
|
+
});
|
|
20362
|
+
rootEntries.push({ path: `entities/${dir}/index.md`, title: entityId });
|
|
19402
20363
|
}
|
|
19403
|
-
|
|
19404
|
-
|
|
19405
|
-
|
|
19406
|
-
|
|
19407
|
-
|
|
19408
|
-
|
|
19409
|
-
|
|
20364
|
+
files.push({
|
|
20365
|
+
path: "index.md",
|
|
20366
|
+
content: coreOkf.buildRootIndexMd(
|
|
20367
|
+
okfVersion,
|
|
20368
|
+
rootEntries.length > 0 ? [{ heading: "Entities", entries: rootEntries }] : [],
|
|
20369
|
+
// Omitted when no record is emitted — a metadata-free dump keeps its
|
|
20370
|
+
// exact current root index, byte for byte.
|
|
20371
|
+
{ profile, ...bundleMetadata !== void 0 ? { bundleMetadata } : {} }
|
|
20372
|
+
)
|
|
20373
|
+
});
|
|
20374
|
+
return { files };
|
|
19410
20375
|
}
|
|
19411
20376
|
|
|
19412
20377
|
// src/utils/contextBudget.ts
|