@superbee/core 0.2.0-pre.56 → 0.2.0-pre.58

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.
Files changed (99) hide show
  1. package/dist/backend.d.ts.map +1 -1
  2. package/dist/backend.js +4 -3
  3. package/dist/backend.js.map +1 -1
  4. package/dist/dependencies.d.ts +10 -0
  5. package/dist/dependencies.d.ts.map +1 -1
  6. package/dist/dependencies.js +27 -0
  7. package/dist/dependencies.js.map +1 -1
  8. package/dist/document-mutation.d.ts +4 -0
  9. package/dist/document-mutation.d.ts.map +1 -1
  10. package/dist/document-mutation.js +3 -0
  11. package/dist/document-mutation.js.map +1 -1
  12. package/dist/edge-harness/corpus.d.ts +9 -0
  13. package/dist/edge-harness/corpus.d.ts.map +1 -0
  14. package/dist/edge-harness/corpus.js +57 -0
  15. package/dist/edge-harness/corpus.js.map +1 -0
  16. package/dist/edge-harness/index.d.ts +21 -0
  17. package/dist/edge-harness/index.d.ts.map +1 -0
  18. package/dist/edge-harness/index.js +486 -0
  19. package/dist/edge-harness/index.js.map +1 -0
  20. package/dist/edges/find.d.ts +12 -0
  21. package/dist/edges/find.d.ts.map +1 -0
  22. package/dist/edges/find.js +42 -0
  23. package/dist/edges/find.js.map +1 -0
  24. package/dist/edges/index.d.ts +12 -0
  25. package/dist/edges/index.d.ts.map +1 -0
  26. package/dist/edges/index.js +4 -0
  27. package/dist/edges/index.js.map +1 -0
  28. package/dist/edges/memory-source.d.ts +8 -0
  29. package/dist/edges/memory-source.d.ts.map +1 -0
  30. package/dist/edges/memory-source.js +138 -0
  31. package/dist/edges/memory-source.js.map +1 -0
  32. package/dist/edges/source.d.ts +104 -0
  33. package/dist/edges/source.d.ts.map +1 -0
  34. package/dist/edges/source.js +2 -0
  35. package/dist/edges/source.js.map +1 -0
  36. package/dist/edges/walk.d.ts +7 -0
  37. package/dist/edges/walk.d.ts.map +1 -0
  38. package/dist/edges/walk.js +14 -0
  39. package/dist/edges/walk.js.map +1 -0
  40. package/dist/engine.d.ts +4 -0
  41. package/dist/engine.d.ts.map +1 -1
  42. package/dist/engine.js +13 -45
  43. package/dist/engine.js.map +1 -1
  44. package/dist/filesystem-lock.d.ts +3 -0
  45. package/dist/filesystem-lock.d.ts.map +1 -1
  46. package/dist/filesystem-lock.js +4 -1
  47. package/dist/filesystem-lock.js.map +1 -1
  48. package/dist/hosted-transport/answer-rows.d.ts +5 -2
  49. package/dist/hosted-transport/answer-rows.d.ts.map +1 -1
  50. package/dist/hosted-transport/answer-rows.js +4 -2
  51. package/dist/hosted-transport/answer-rows.js.map +1 -1
  52. package/dist/hosted-transport/whole-document-transport.d.ts.map +1 -1
  53. package/dist/hosted-transport/whole-document-transport.js +15 -4
  54. package/dist/hosted-transport/whole-document-transport.js.map +1 -1
  55. package/dist/index.d.ts +3 -3
  56. package/dist/index.d.ts.map +1 -1
  57. package/dist/index.js +3 -3
  58. package/dist/index.js.map +1 -1
  59. package/dist/kind-field-mutation.d.ts +1 -1
  60. package/dist/kind-field-mutation.d.ts.map +1 -1
  61. package/dist/kind-undeclared-fields.d.ts +2 -0
  62. package/dist/kind-undeclared-fields.d.ts.map +1 -1
  63. package/dist/kind-undeclared-fields.js +3 -0
  64. package/dist/kind-undeclared-fields.js.map +1 -1
  65. package/dist/local-search-index.d.ts +25 -1
  66. package/dist/local-search-index.d.ts.map +1 -1
  67. package/dist/local-search-index.js +397 -41
  68. package/dist/local-search-index.js.map +1 -1
  69. package/dist/okf-actor.d.ts +10 -1
  70. package/dist/okf-actor.d.ts.map +1 -1
  71. package/dist/okf-actor.js +17 -1
  72. package/dist/okf-actor.js.map +1 -1
  73. package/dist/recipe-lifecycle/index.d.ts +1 -0
  74. package/dist/recipe-lifecycle/index.d.ts.map +1 -1
  75. package/dist/recipe-lifecycle/index.js +1 -0
  76. package/dist/recipe-lifecycle/index.js.map +1 -1
  77. package/dist/recipe-lifecycle/install.d.ts +5 -3
  78. package/dist/recipe-lifecycle/install.d.ts.map +1 -1
  79. package/dist/recipe-lifecycle/install.js +6 -7
  80. package/dist/recipe-lifecycle/install.js.map +1 -1
  81. package/dist/recipe-lifecycle/set-commit.d.ts +5 -2
  82. package/dist/recipe-lifecycle/set-commit.d.ts.map +1 -1
  83. package/dist/recipe-lifecycle/set-commit.js +5 -2
  84. package/dist/recipe-lifecycle/set-commit.js.map +1 -1
  85. package/dist/relationships.d.ts +9 -2
  86. package/dist/relationships.d.ts.map +1 -1
  87. package/dist/relationships.js +33 -24
  88. package/dist/relationships.js.map +1 -1
  89. package/dist/search-index.d.ts +3 -1
  90. package/dist/search-index.d.ts.map +1 -1
  91. package/dist/search-index.js +3 -1
  92. package/dist/search-index.js.map +1 -1
  93. package/dist/source-profiles/index.d.ts +1 -1
  94. package/dist/source-profiles/index.js +1 -1
  95. package/dist/storage.d.ts +2 -2
  96. package/dist/storage.d.ts.map +1 -1
  97. package/dist/storage.js +2 -2
  98. package/dist/storage.js.map +1 -1
  99. package/package.json +9 -1
@@ -11,6 +11,11 @@
11
11
  * only records the new stamp. The index holds no corpus-size limit; `maxTermsPerDocument` still
12
12
  * skips and counts an over-long document.
13
13
  *
14
+ * The same file keeps the bundle's link facts, refreshed by the same pass: a document read again
15
+ * has its links derived again, in the same write transaction as its search row, and `edgeSource()`
16
+ * answers Core's `EdgeSource` with indexed queries over them, as `edgeSourceFromBackend` answers on
17
+ * the same folder.
18
+ *
14
19
  * The file is derived state: a missing, corrupt, foreign, older-schema or other-text-version file is
15
20
  * rebuilt. Several processes may share it: SQLite's WAL journal and a busy timeout serialize the
16
21
  * short write transactions, and each search reads one consistent snapshot.
@@ -20,15 +25,21 @@ import path from "node:path";
20
25
  import { FilesystemBackend, filesystemDocumentStamp } from "./backend.js";
21
26
  import { isConventionRecord } from "./convention-record.js";
22
27
  import { readManyExisting } from "./document-scan.js";
23
- import { readBundleOkfVersion } from "./engine.js";
28
+ import { assertWalkBounds } from "./edges/walk.js";
29
+ import { deriveRelationshipSource, readBundleOkfVersion } from "./engine.js";
30
+ import { InvalidInputError } from "./errors.js";
24
31
  import { headsDigest } from "./heads-digest.js";
25
32
  import { sha256HexOfUtf8 } from "./sha256.js";
26
33
  import { SEARCH_LIMITS, SEARCH_MATCH_FIELDS, SIGNAL_INTERVAL, documentDescription, documentTags, documentTitle, documentType, } from "./search/contract.js";
27
34
  import { stopIfAsked } from "./search/errors.js";
28
35
  import { canonicalJson, codeUnitCompare } from "./search/identity.js";
29
36
  import { searchRowText, textVersion } from "./search/row-text.js";
30
- /** Bumped whenever the tables below change shape; an index of another schema is rebuilt. */
31
- const SCHEMA_VERSION = "1";
37
+ import { RELATIONSHIP_PROJECTION_VERSIONS, relationshipProjectionForEdition } from "./relationships.js";
38
+ /** Bumped whenever the tables below change shape; an index of another schema is rebuilt. 2: the
39
+ * link facts (`edges`, and the node columns of `docs`). */
40
+ const SCHEMA_VERSION = "2";
41
+ /** The link projections the `edges` rows were derived under; another set rebuilds the file. */
42
+ const LINKS_VERSION = RELATIONSHIP_PROJECTION_VERSIONS.join(" ");
32
43
  /**
33
44
  * Names what an index file was built by: this file's schema and `textVersion()` (the ranking
34
45
  * algorithm, the text revision and the runtime's normalizer fingerprint). Two builds with different
@@ -37,7 +48,7 @@ const SCHEMA_VERSION = "1";
37
48
  * Sixteen lowercase hex characters. The file still records and checks these inputs itself.
38
49
  */
39
50
  export function localSearchIndexFileKey() {
40
- return sha256HexOfUtf8(`local-search-index\u0000${SCHEMA_VERSION}\u0000${textVersion()}`).slice(0, 16);
51
+ return sha256HexOfUtf8(`local-search-index\u0000${SCHEMA_VERSION}\u0000${textVersion()}\u0000${LINKS_VERSION}`).slice(0, 16);
41
52
  }
42
53
  /** Documents read and derived between cancellation checks and memory bounds. */
43
54
  const BATCH = 128;
@@ -54,6 +65,9 @@ const INDEXED = 0;
54
65
  const OVER_TERM_CAP = 1;
55
66
  /** Unreadable: reported in `skipped` with its reason, as the in-memory path reports it. */
56
67
  const MALFORMED = 2;
68
+ /** The host refused to read it (EACCES, EPERM). Kept only by a link refresh, which skips such a
69
+ * file as Core's link reads do; never trusted, so a search reads it again and fails as before. */
70
+ const DENIED = 3;
57
71
  /** The local index cannot be used here. A caller can fall back to the in-memory source. */
58
72
  export class LocalSearchIndexUnavailableError extends Error {
59
73
  reason;
@@ -111,24 +125,68 @@ export async function openLocalSearchIndexWith(options, seams) {
111
125
  return body();
112
126
  }
113
127
  };
128
+ /** A busy, full, read-only or failing index is one typed condition a caller can fall back on. */
129
+ const typed = async (body) => {
130
+ if (closed)
131
+ throw new TypeError("the local search index is closed");
132
+ try {
133
+ return await body();
134
+ }
135
+ catch (error) {
136
+ if (isSqliteError(error))
137
+ throw new LocalSearchIndexUnavailableError("index-unusable", { cause: error });
138
+ throw error;
139
+ }
140
+ };
114
141
  const source = {
115
142
  async evidence(terms, filters, bounds, stop) {
116
143
  if (closed)
117
144
  throw new TypeError("the local search index is closed");
118
145
  stopIfAsked(stop);
119
- try {
120
- return await recovering(async () => {
121
- await refresh(db, backend, contentStamp, stop);
122
- stopIfAsked(stop);
123
- return readEvidence(db, terms, filters, bounds, stop);
124
- });
125
- }
126
- catch (error) {
127
- // A busy, full, read-only or failing index is one typed condition a caller can fall back on.
128
- if (isSqliteError(error))
129
- throw new LocalSearchIndexUnavailableError("index-unusable", { cause: error });
130
- throw error;
131
- }
146
+ return typed(() => recovering(async () => {
147
+ await refresh(db, backend, contentStamp, stop, false);
148
+ stopIfAsked(stop);
149
+ return readEvidence(db, terms, filters, bounds, stop);
150
+ }));
151
+ },
152
+ edgeSource(options = {}) {
153
+ let opened;
154
+ const snapshot = () => (opened ??= typed(() => recovering(async () => {
155
+ const listed = await refresh(db, backend, contentStamp, undefined, true);
156
+ return openEdgeSnapshot(db, backend, listed, options.onSkip);
157
+ })));
158
+ return Object.freeze({
159
+ async edges(selection, limit) {
160
+ if (!(limit === undefined || limit === Infinity || (Number.isSafeInteger(limit) && limit >= 0)))
161
+ throw new TypeError("An edge read's limit must be a non-negative integer");
162
+ const state = await snapshot();
163
+ return typed(() => readEdges(db, state, selection, limit));
164
+ },
165
+ async heads(ids) {
166
+ const state = await snapshot();
167
+ return typed(() => readHeads(db, state, ids));
168
+ },
169
+ async walk(start, hops, limit) {
170
+ assertWalkBounds(start, hops, limit);
171
+ const state = await snapshot();
172
+ return typed(() => readWalk(db, state, start, hops, limit));
173
+ },
174
+ });
175
+ },
176
+ async linksOf(documents, okfVersion) {
177
+ const projection = relationshipProjectionForEdition(okfVersion);
178
+ // Rows of exactly these versions were derived from exactly these bytes, so a file that already
179
+ // holds them answers without a refresh; one that does not is brought up to the folder first.
180
+ const read = () => readLinksOf(db, documents, projection);
181
+ return typed(() => recovering(async () => {
182
+ if (ownSchema(readMeta(db))) {
183
+ const held = read();
184
+ if (held !== undefined)
185
+ return held;
186
+ }
187
+ await refresh(db, backend, contentStamp, undefined, true);
188
+ return read();
189
+ }));
132
190
  },
133
191
  async text(hits) {
134
192
  if (closed)
@@ -321,7 +379,7 @@ const FTS_COLUMNS = SEARCH_MATCH_FIELDS;
321
379
  function dropOwnNames(db) {
322
380
  db.exec("DROP TABLE IF EXISTS temp.vocab_instance; DROP TABLE IF EXISTS temp.vocab_row;");
323
381
  const objects = db
324
- .prepare("SELECT type, name FROM main.sqlite_master WHERE name IN ('meta', 'docs', 'fts') OR name LIKE 'fts\\_%' ESCAPE '\\'")
382
+ .prepare("SELECT type, name FROM main.sqlite_master WHERE name IN ('meta', 'docs', 'fts', 'edges', 'edges_by_target') OR name LIKE 'fts\\_%' ESCAPE '\\'")
325
383
  .all();
326
384
  const order = ["trigger", "view", "index", "table"];
327
385
  objects.sort((a, b) => order.indexOf(a.type) - order.indexOf(b.type) || (a.name === "fts" ? -1 : b.name === "fts" ? 1 : 0));
@@ -346,14 +404,29 @@ function createSchema(db, edition) {
346
404
  type TEXT,
347
405
  tags TEXT NOT NULL,
348
406
  title_phrase TEXT NOT NULL,
349
- id_phrase TEXT NOT NULL
407
+ id_phrase TEXT NOT NULL,
408
+ node INTEGER NOT NULL,
409
+ head_title TEXT,
410
+ head_type TEXT,
411
+ link_error TEXT
350
412
  );
351
413
  CREATE VIRTUAL TABLE main.fts USING fts5(${FTS_COLUMNS.join(", ")}, tokenize = 'ascii', content = '', contentless_delete = 1, detail = full);
414
+ CREATE TABLE main.edges (
415
+ source TEXT NOT NULL,
416
+ ordinal INTEGER NOT NULL,
417
+ target TEXT NOT NULL,
418
+ text TEXT NOT NULL,
419
+ href TEXT NOT NULL,
420
+ PRIMARY KEY (source, ordinal)
421
+ ) WITHOUT ROWID;
422
+ CREATE INDEX main.edges_by_target ON edges (target, source, ordinal);
352
423
  `);
353
424
  const put = db.prepare("INSERT INTO main.meta (key, value) VALUES (?, ?)");
354
425
  put.run("schema", SCHEMA_VERSION);
355
426
  put.run("textVersion", textVersion());
427
+ put.run("links", LINKS_VERSION);
356
428
  put.run("edition", edition);
429
+ put.run("generation", "0");
357
430
  }
358
431
  function readMeta(db) {
359
432
  try {
@@ -368,11 +441,15 @@ function readMeta(db) {
368
441
  return undefined;
369
442
  }
370
443
  }
371
- function current(meta, edition) {
444
+ /** The file holds this schema's tables, derived by this build. */
445
+ function ownSchema(meta) {
372
446
  return (meta !== undefined &&
373
447
  meta.get("schema") === SCHEMA_VERSION &&
374
448
  meta.get("textVersion") === textVersion() &&
375
- meta.get("edition") === edition);
449
+ meta.get("links") === LINKS_VERSION);
450
+ }
451
+ function current(meta, edition) {
452
+ return ownSchema(meta) && meta.get("edition") === edition;
376
453
  }
377
454
  /** Rebuilds the tables when the file holds another schema, text version or bundle edition. */
378
455
  function ensureSchema(db, edition) {
@@ -411,13 +488,19 @@ function transaction(db, body) {
411
488
  throw error;
412
489
  }
413
490
  }
414
- /** Brings the index up to the bundle: re-reads every file whose stamp cannot vouch for its row. */
415
- async function refresh(db, backend, contentStamp, stop) {
491
+ /**
492
+ * Brings the index up to the bundle: re-reads every file whose stamp cannot vouch for its row, and
493
+ * derives its search row and its links together. `links`: a file the host refuses to read is kept
494
+ * as skipped, as Core's link reads skip it, rather than failing the refresh as a search does.
495
+ */
496
+ async function refresh(db, backend, contentStamp, stop, links) {
416
497
  // The edition decides how every document parses, so a change re-derives every row.
417
- const edition = JSON.stringify((await readBundleOkfVersion(backend, { allowMalformedRoot: true })) ?? null);
498
+ const okfVersion = await readBundleOkfVersion(backend, { allowMalformedRoot: true });
499
+ const edition = JSON.stringify(okfVersion ?? null);
500
+ const projection = relationshipProjectionForEdition(okfVersion);
418
501
  ensureSchema(db, edition);
419
502
  const manifest = new Map();
420
- for (const row of db.prepare("SELECT id, version, stamp, settled, state FROM main.docs").all())
503
+ for (const row of db.prepare("SELECT id, version, stamp, settled, state, reason FROM main.docs").all())
421
504
  manifest.set(row.id, row);
422
505
  const ids = await backend.list();
423
506
  const stale = [];
@@ -437,7 +520,7 @@ async function refresh(db, backend, contentStamp, stop) {
437
520
  let pending = [];
438
521
  let pendingText = 0;
439
522
  const flush = () => {
440
- apply(db, pending);
523
+ apply(db, pending, manifest);
441
524
  pending = [];
442
525
  pendingText = 0;
443
526
  };
@@ -453,14 +536,24 @@ async function refresh(db, backend, contentStamp, stop) {
453
536
  stopIfAsked(stop);
454
537
  const batch = stale.slice(start, start + BATCH);
455
538
  const malformed = new Map();
456
- const results = await readManyExisting(backend, batch.map((entry) => entry.id), (skip) => void malformed.set(skip.id, skip));
539
+ const denied = new Map();
540
+ const results = await readManyExisting(backend, batch.map((entry) => entry.id), (skip) => void malformed.set(skip.id, skip), undefined, links ? (skip) => void denied.set(skip.id, skip) : undefined);
457
541
  let next = 0;
458
542
  for (const [position, { id, stamp }] of batch.entries()) {
459
543
  if (position % SIGNAL_INTERVAL === 0)
460
544
  stopIfAsked(stop);
461
- const skip = malformed.get(id);
462
- if (skip !== undefined) {
463
- queue(malformedRow(id, stamp, skip.reason));
545
+ const unread = malformed.has(id)
546
+ ? [MALFORMED, malformed.get(id).reason, stamp]
547
+ : denied.has(id)
548
+ ? [DENIED, denied.get(id).reason, undefined]
549
+ : undefined;
550
+ if (unread !== undefined) {
551
+ const [state, reason, kept] = unread;
552
+ // Unreadable as recorded: nothing to write.
553
+ const row = manifest.get(id);
554
+ const same = row !== undefined && row.state === state && row.reason === reason && row.stamp === (kept?.value ?? null) && row.settled === (kept?.settled ? 1 : 0);
555
+ if (!same)
556
+ queue(unreadRow(id, kept, state, reason));
464
557
  continue;
465
558
  }
466
559
  const result = results[next];
@@ -477,7 +570,7 @@ async function refresh(db, backend, contentStamp, stop) {
477
570
  queue({ kind: "stamp", id, version: result.version, stamp });
478
571
  continue;
479
572
  }
480
- queue(derivedRow({ ...result.doc, version: result.version }, stamp));
573
+ queue(derivedRow({ ...result.doc, version: result.version }, stamp, projection));
481
574
  }
482
575
  if (next !== results.length)
483
576
  throw new TypeError("Search backend returned a different document identity.");
@@ -487,11 +580,48 @@ async function refresh(db, backend, contentStamp, stop) {
487
580
  if (!listed.has(id))
488
581
  queue({ kind: "delete", id });
489
582
  flush();
583
+ return { ids, edition: okfVersion };
584
+ }
585
+ function unreadRow(id, stamp, state, reason) {
586
+ return {
587
+ kind: "row",
588
+ id,
589
+ version: null,
590
+ stamp,
591
+ state,
592
+ reason,
593
+ title: null,
594
+ type: null,
595
+ tags: "[]",
596
+ titlePhrase: "",
597
+ idPhrase: "",
598
+ node: 0,
599
+ headTitle: null,
600
+ headType: null,
601
+ linkError: null,
602
+ links: [],
603
+ };
490
604
  }
491
- function malformedRow(id, stamp, reason) {
492
- return { kind: "row", id, version: null, stamp, state: MALFORMED, reason, title: null, type: null, tags: "[]", titlePhrase: "", idPhrase: "" };
605
+ /** A document's links as Core's link reads derive them (`deriveRelationshipSource`): its node
606
+ * status, head and occurrences, or the error that fails a link read. */
607
+ function derivedLinks(document, projection) {
608
+ try {
609
+ const source = deriveRelationshipSource(document, projection);
610
+ const node = projection?.conceptsOnly ? source.concept === true : true;
611
+ return {
612
+ node: node ? 1 : 0,
613
+ headTitle: source.title,
614
+ headType: source.type ?? null,
615
+ linkError: null,
616
+ links: node ? source.links : [],
617
+ };
618
+ }
619
+ catch (error) {
620
+ // A search still indexes the document; only a link read fails, with Core's own error.
621
+ return { node: 0, headTitle: null, headType: null, linkError: error instanceof Error ? error.message : String(error), links: [] };
622
+ }
493
623
  }
494
- function derivedRow(document, stamp) {
624
+ function derivedRow(document, stamp, projection) {
495
625
  const text = searchRowText(document);
496
626
  const searched = text.bodyTermCount <= SEARCH_LIMITS.maxTermsPerDocument;
497
627
  const byField = {
@@ -515,35 +645,52 @@ function derivedRow(document, stamp) {
515
645
  titlePhrase: text.titlePhrase,
516
646
  idPhrase: text.idPhrase,
517
647
  ...(searched ? { columns: FTS_COLUMNS.map((field) => byField[field]) } : {}),
648
+ ...derivedLinks(document, projection),
518
649
  };
519
650
  }
520
651
  /**
521
- * One write transaction. Each change is applied against the row as it is now, not as this process
522
- * last saw it, so two processes refreshing at once both leave a row derived from a real read.
652
+ * One write transaction. A stored row is replaced only while it still has the version this refresh
653
+ * found in `manifest`: when another process wrote it in between, that write stands, so a slower
654
+ * process never puts back an older read over a newer one. A file changed again since is read on the
655
+ * next refresh, as its stamp no longer matches.
523
656
  */
524
- function apply(db, changes) {
657
+ function apply(db, changes, manifest) {
525
658
  if (changes.length === 0)
526
659
  return;
527
- const find = db.prepare("SELECT rowid, state FROM main.docs WHERE id = ?");
660
+ const find = db.prepare("SELECT rowid, state, version FROM main.docs WHERE id = ?");
528
661
  const stampOnly = db.prepare("UPDATE main.docs SET stamp = ?, settled = ? WHERE id = ? AND version = ? AND state != ?");
529
- const update = db.prepare("UPDATE main.docs SET version = ?, stamp = ?, settled = ?, state = ?, reason = ?, title = ?, type = ?, tags = ?, title_phrase = ?, id_phrase = ? WHERE rowid = ?");
530
- const insert = db.prepare("INSERT INTO main.docs (id, version, stamp, settled, state, reason, title, type, tags, title_phrase, id_phrase) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING rowid");
662
+ const update = db.prepare("UPDATE main.docs SET version = ?, stamp = ?, settled = ?, state = ?, reason = ?, title = ?, type = ?, tags = ?, title_phrase = ?, id_phrase = ?, node = ?, head_title = ?, head_type = ?, link_error = ? WHERE rowid = ?");
663
+ const insert = db.prepare("INSERT INTO main.docs (id, version, stamp, settled, state, reason, title, type, tags, title_phrase, id_phrase, node, head_title, head_type, link_error) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING rowid");
531
664
  const remove = db.prepare("DELETE FROM main.docs WHERE rowid = ?");
532
665
  const unindex = db.prepare("DELETE FROM main.fts WHERE rowid = ?");
533
666
  const index = db.prepare(`INSERT INTO main.fts (rowid, ${FTS_COLUMNS.join(", ")}) VALUES (?, ${FTS_COLUMNS.map(() => "?").join(", ")})`);
667
+ const dropLinks = db.prepare("DELETE FROM main.edges WHERE source = ?");
668
+ const addLink = db.prepare("INSERT INTO main.edges (source, ordinal, target, text, href) VALUES (?, ?, ?, ?, ?)");
669
+ // A change to any row moves the generation, so an edge source that read before it can tell; a
670
+ // new stamp alone changes no answer.
671
+ const advance = db.prepare("UPDATE main.meta SET value = CAST(CAST(value AS INTEGER) + 1 AS TEXT) WHERE key = 'generation'");
534
672
  // A write through FTS5 can report a shadow-table rowid past 2^53 as its last insert rowid, which
535
673
  // Node 26 refuses to convert to a number; nothing here reads it.
536
- for (const statement of [stampOnly, update, insert, remove, unindex, index])
674
+ for (const statement of [stampOnly, update, insert, remove, unindex, index, dropLinks, addLink, advance])
537
675
  statement.setReadBigInts(true);
538
676
  transaction(db, () => {
677
+ let changed = false;
539
678
  for (const change of changes) {
540
679
  const existing = find.get(change.id);
541
680
  if (change.kind === "stamp") {
542
681
  stampOnly.run(change.stamp?.value ?? null, change.stamp?.settled ? 1 : 0, change.id, change.version, MALFORMED);
543
682
  continue;
544
683
  }
684
+ // Another process wrote this row since the manifest was read: its write stands. A missing row is
685
+ // always written (a file every reader lists must have one, even after another rebuilt the file).
686
+ const seen = manifest.get(change.id);
687
+ if (existing !== undefined && (seen === undefined || existing.version !== seen.version))
688
+ continue;
689
+ changed = true;
545
690
  if (existing !== undefined && existing.state === INDEXED)
546
691
  unindex.run(existing.rowid);
692
+ // A document's links change with its row, in this transaction.
693
+ dropLinks.run(change.id);
547
694
  if (change.kind === "delete") {
548
695
  if (existing !== undefined)
549
696
  remove.run(existing.rowid);
@@ -560,6 +707,10 @@ function apply(db, changes) {
560
707
  change.tags,
561
708
  change.titlePhrase,
562
709
  change.idPhrase,
710
+ change.node,
711
+ change.headTitle,
712
+ change.headType,
713
+ change.linkError,
563
714
  ];
564
715
  let rowid;
565
716
  if (existing !== undefined) {
@@ -571,7 +722,11 @@ function apply(db, changes) {
571
722
  }
572
723
  if (change.columns !== undefined)
573
724
  index.run(rowid, ...change.columns);
725
+ for (const [ordinal, occurrence] of change.links.entries())
726
+ addLink.run(change.id, ordinal, occurrence.to, occurrence.text, occurrence.href);
574
727
  }
728
+ if (changed)
729
+ advance.run();
575
730
  });
576
731
  }
577
732
  /** One read transaction: the corpus identity and sizes, the volume and the evidence agree. */
@@ -673,6 +828,207 @@ function readEvidence(db, terms, filters, bounds, stop) {
673
828
  db.exec("COMMIT");
674
829
  }
675
830
  }
831
+ /** Inside one read transaction; `pending` once another refresh has changed the file since `state`. */
832
+ function readSnapshot(db, state, body) {
833
+ db.exec("BEGIN");
834
+ try {
835
+ if (generationOf(db) !== state.generation)
836
+ return { status: "pending" };
837
+ return body();
838
+ }
839
+ finally {
840
+ db.exec("COMMIT");
841
+ }
842
+ }
843
+ function generationOf(db) {
844
+ return db.prepare("SELECT value FROM main.meta WHERE key = 'generation'").get().value;
845
+ }
846
+ /**
847
+ * Pins an edge source to the file as its own refresh left it, and reports the unreadable documents
848
+ * in listing order. As Core's in-memory link read, it fails on the first document (in listing
849
+ * order) whose links cannot be derived, or that cannot be read when nobody takes `onSkip`: that
850
+ * document is read again here, so the failure is Core's own error.
851
+ */
852
+ async function openEdgeSnapshot(db, backend, listed, onSkip) {
853
+ db.exec("BEGIN");
854
+ let generation;
855
+ let unread;
856
+ let failed;
857
+ try {
858
+ generation = generationOf(db);
859
+ const rows = db
860
+ .prepare("SELECT id, state, reason, link_error FROM main.docs WHERE state IN (?, ?) OR link_error IS NOT NULL")
861
+ .all(MALFORMED, DENIED);
862
+ unread = new Map(rows.filter((row) => row.link_error === null).map((row) => [row.id, row.reason ?? ""]));
863
+ failed = new Map(rows.filter((row) => row.link_error !== null).map((row) => [row.id, row.link_error]));
864
+ }
865
+ finally {
866
+ db.exec("COMMIT");
867
+ }
868
+ const projection = relationshipProjectionForEdition(listed.edition);
869
+ for (const id of listed.ids) {
870
+ const message = failed.get(id);
871
+ if (message === undefined && (onSkip !== undefined || !unread.has(id)))
872
+ continue;
873
+ const { doc } = await backend.read(id);
874
+ if (message !== undefined)
875
+ deriveRelationshipSource(doc, projection);
876
+ // Readable and derivable now: it changed after the refresh, which a later read picks up.
877
+ throw new InvalidInputError(message ?? `'${id}' changed while its links were read. Read again.`);
878
+ }
879
+ if (onSkip !== undefined)
880
+ for (const id of listed.ids)
881
+ if (unread.has(id))
882
+ onSkip({ id, reason: unread.get(id) });
883
+ return { generation, conceptsOnly: projection?.conceptsOnly === true };
884
+ }
885
+ /** The least string above every string that starts with `prefix`, in code point (UTF-8 byte) order;
886
+ * undefined when there is none. */
887
+ function prefixEnd(prefix) {
888
+ const points = [...prefix];
889
+ while (points.length > 0) {
890
+ const last = points.pop().codePointAt(0);
891
+ if (last === 0x10ffff)
892
+ continue;
893
+ return points.join("") + String.fromCodePoint(last === 0xd7ff ? 0xe000 : last + 1);
894
+ }
895
+ return undefined;
896
+ }
897
+ /** A facet as SQL over `column`: exact ids, and each prefix as a range seek under BINARY collation
898
+ * (exact bytes: no case folding, no wildcards). An empty facet matches nothing. */
899
+ function facetSql(column, facet, params) {
900
+ const terms = [];
901
+ if (facet.ids.length > 0) {
902
+ terms.push(`e.${column} IN (SELECT value FROM json_each(?))`);
903
+ params.push(JSON.stringify(facet.ids));
904
+ }
905
+ for (const prefix of facet.prefixes) {
906
+ const end = prefixEnd(prefix);
907
+ terms.push(end === undefined ? `e.${column} >= ?` : `(e.${column} >= ? AND e.${column} < ?)`);
908
+ params.push(prefix, ...(end === undefined ? [] : [end]));
909
+ }
910
+ return terms.length === 0 ? "0" : `(${terms.join(" OR ")})`;
911
+ }
912
+ function readEdges(db, state, selection, limit) {
913
+ const params = [];
914
+ const where = [];
915
+ if (selection.from !== undefined)
916
+ where.push(facetSql("source", selection.from, params));
917
+ if (selection.to !== undefined)
918
+ where.push(facetSql("target", selection.to, params));
919
+ if (selection.text !== undefined) {
920
+ where.push("e.text = ?");
921
+ params.push(selection.text);
922
+ }
923
+ // In OKF 0.3 a link counts only between nodes; only a node's links are stored.
924
+ if (state.conceptsOnly)
925
+ where.push("EXISTS (SELECT 1 FROM main.docs n WHERE n.id = e.target AND n.node = 1)");
926
+ const bounded = limit !== undefined && limit !== Infinity;
927
+ const sql = `SELECT e.source AS "from", e.target AS "to", e.text AS text, e.href AS href FROM main.edges e` +
928
+ (where.length === 0 ? "" : ` WHERE ${where.join(" AND ")}`) +
929
+ ` ORDER BY e.source, e.ordinal${bounded ? ` LIMIT ${limit + 1}` : ""}`;
930
+ return readSnapshot(db, state, () => {
931
+ const rows = db.prepare(sql).all(...params);
932
+ const more = bounded && rows.length > limit;
933
+ const edges = (more ? rows.slice(0, limit) : rows).map(({ from, to, text, href }) => ({ from, to, text, href }));
934
+ return { status: "ready", edges, more };
935
+ });
936
+ }
937
+ /** In one read transaction: every link, when the file holds exactly `documents`, all derived under
938
+ * `projection`'s link rule. */
939
+ function readLinksOf(db, documents, projection) {
940
+ db.exec("BEGIN");
941
+ try {
942
+ // Derived under another edition's link rule: not these documents' links.
943
+ const edition = readMeta(db)?.get("edition");
944
+ if (edition === undefined || relationshipProjectionForEdition(JSON.parse(edition) ?? undefined) !== projection)
945
+ return undefined;
946
+ const conceptsOnly = projection?.conceptsOnly === true;
947
+ const rows = db.prepare("SELECT id, version, link_error FROM main.docs").all();
948
+ if (rows.length !== documents.length)
949
+ return undefined;
950
+ const held = new Map(rows.map((row) => [row.id, row]));
951
+ for (const { id, version } of documents) {
952
+ const row = held.get(id);
953
+ if (row === undefined || row.version !== version || row.link_error !== null)
954
+ return undefined;
955
+ }
956
+ const node = conceptsOnly ? " WHERE EXISTS (SELECT 1 FROM main.docs n WHERE n.id = e.target AND n.node = 1)" : "";
957
+ const links = db
958
+ .prepare(`SELECT e.source AS "from", e.target AS "to", e.text AS text, e.href AS href FROM main.edges e${node} ORDER BY e.source, e.ordinal`)
959
+ .all();
960
+ return links.map(({ from, to, text, href }) => ({ from, to, text, href }));
961
+ }
962
+ finally {
963
+ db.exec("COMMIT");
964
+ }
965
+ }
966
+ function readHeads(db, state, ids) {
967
+ return readSnapshot(db, state, () => {
968
+ const rows = db
969
+ .prepare("SELECT id, head_title, head_type FROM main.docs WHERE node = 1 AND id IN (SELECT value FROM json_each(?))")
970
+ .all(JSON.stringify(ids));
971
+ const found = new Map(rows.map((row) => [row.id, row]));
972
+ const heads = new Map();
973
+ for (const id of ids) {
974
+ const row = found.get(id);
975
+ if (row !== undefined)
976
+ heads.set(id, Object.freeze({ id, title: row.head_title, type: row.head_type }));
977
+ }
978
+ return { status: "ready", heads };
979
+ });
980
+ }
981
+ /**
982
+ * One hop of a walk: every node not in `reached` that one link joins to a node of `frontier` (ranked
983
+ * by its position there), each with its least candidate link (rank, outgoing first, written
984
+ * position), ordered by rank, direction and id, at most `bound` of them. A link counts only between
985
+ * nodes: the frontier holds nodes, and the joined end must be one.
986
+ */
987
+ const WALK_HOP_SQL = `
988
+ WITH f AS (SELECT key AS rank, value AS id FROM json_each(?)),
989
+ c AS (
990
+ SELECT f.rank AS rank, 0 AS dir, e.target AS id, e.source AS "from", e.target AS "to", e.text AS text, e.href AS href, e.ordinal AS ordinal
991
+ FROM f JOIN main.edges e ON e.source = f.id
992
+ UNION ALL
993
+ SELECT f.rank, 1, e.source, e.source, e.target, e.text, e.href, e.ordinal
994
+ FROM f JOIN main.edges e INDEXED BY edges_by_target ON e.target = f.id
995
+ ),
996
+ k AS (
997
+ SELECT c.*, ROW_NUMBER() OVER (PARTITION BY c.id ORDER BY c.rank, c.dir, c.ordinal) AS n
998
+ FROM c WHERE c.id NOT IN (SELECT value FROM json_each(?))
999
+ )
1000
+ SELECT k.id AS id, k.dir AS dir, k."from" AS "from", k."to" AS "to", k.text AS text, k.href AS href,
1001
+ d.head_title AS title, d.head_type AS type
1002
+ FROM k JOIN main.docs d ON d.id = k.id AND d.node = 1
1003
+ WHERE k.n = 1
1004
+ ORDER BY k.rank, k.dir, k.id
1005
+ LIMIT ?`;
1006
+ /** A walk (`EdgeSource.walk`) in one read transaction, one query per hop. */
1007
+ function readWalk(db, state, start, hops, limit) {
1008
+ return readSnapshot(db, state, () => {
1009
+ const nodes = new Set(db.prepare("SELECT id FROM main.docs WHERE node = 1 AND id IN (SELECT value FROM json_each(?))").all(JSON.stringify(start)).map(({ id }) => id));
1010
+ const reached = [...new Set(start.filter((id) => nodes.has(id)))];
1011
+ let frontier = [...reached];
1012
+ const steps = [];
1013
+ let more = false;
1014
+ const hop = db.prepare(WALK_HOP_SQL);
1015
+ for (let h = 1; h <= hops && frontier.length > 0 && !more; h++) {
1016
+ const room = limit - steps.length;
1017
+ const rows = hop.all(JSON.stringify(frontier), JSON.stringify(reached), room + 1);
1018
+ if (rows.length > room) {
1019
+ more = true;
1020
+ rows.length = room;
1021
+ }
1022
+ frontier = [];
1023
+ for (const { id, dir, from, to, text, href, title, type } of rows) {
1024
+ steps.push(Object.freeze({ id, title, type, hop: h, direction: dir === 0 ? "outgoing" : "incoming", link: { from, to, text, href } }));
1025
+ reached.push(id);
1026
+ frontier.push(id);
1027
+ }
1028
+ }
1029
+ return { status: "ready", steps, more };
1030
+ });
1031
+ }
676
1032
  /** Description and body of the hits, read again; a file changed since its evidence gives none. */
677
1033
  async function readTexts(backend, hits) {
678
1034
  const texts = new Map();