@polycode-projects/the-mechanical-code-talker 5.0.46 → 6.0.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.
@@ -48,6 +48,13 @@
48
48
  //
49
49
  // Never claims full coverage: the summary this prints always states how many
50
50
  // sentences were found, how many were recognized, and how many were skipped.
51
+ //
52
+ // The extractor also says HOW it read a sentence, as named structural findings
53
+ // with their own detectors — never a score. A candidate the detectors show was
54
+ // mis-read is declined by name (`relative-clause-verb`, `fragment-term`), and a
55
+ // definitional frame ("X is the name for Y") declines the false isa and mints
56
+ // the edge the sentence actually states (`mgx:nameFor`, `definitional-frame`).
57
+ // The ingest result reports both as `declined` and `minted`.
51
58
 
52
59
  import { readFile, writeFile, mkdtemp, rm } from "node:fs/promises";
53
60
  import { tmpdir } from "node:os";
@@ -60,6 +67,7 @@ import { loadMemory, readFactRows, appendFact, removeFacts } from "../adapters/m
60
67
  import { loadConfig } from "../adapters/config.mjs";
61
68
  import { touchedFactRows } from "../domain/memory/touched-facts.mjs";
62
69
  import { normFactTerm } from "../domain/hash.mjs";
70
+ import { splitIdentifierWords } from "../domain/prose.mjs";
63
71
  import { winkInstance } from "../adapters/wink-model.mjs";
64
72
  import {
65
73
  loadLexicon, lookupNoun, lookupVerb, lookupAdjective, lookupProperName, predicateOf,
@@ -143,6 +151,14 @@ const COPULA_NAMING_PARTICIPLES = new Set(["termed", "known", "defined", "descri
143
151
  // subject: "a mountain that has lava" is a fact about the volcano, so the
144
152
  // relative clause's verb binds to the copula's own subject, not to its object.
145
153
  const RELATIVE_PRONOUNS = new Set(["that", "which", "who", "whom", "whose"]);
154
+ // The copula-object heads that define a subject rather than classify it. "X is
155
+ // the name for Y" says what X names; it does not put X under the class "name".
156
+ // Followed by "for" or "of", one of these declines the isa and mints the edge
157
+ // the sentence states instead.
158
+ const DEFINITIONAL_HEADS = new Set(["name", "word", "term", "label", "title"]);
159
+ // The predicate that edge carries: the subject is a name for the object's
160
+ // concept, minted at the extraction tier beside the other mgx: relations.
161
+ const NAME_FOR_PREDICATE = "mgx:nameFor";
146
162
  // At most this many triples from one sentence — a bound so a run-on can never
147
163
  // shatter into noise, not a first-wins cap.
148
164
  const MAX_TRIPLES_PER_SENTENCE = 4;
@@ -233,14 +249,14 @@ function ungroundedTermOccurrences(sentences, rows, { lexicon, nlp }) {
233
249
  * predicate). Adjectives, determiners and prepositions are never mistaken for
234
250
  * the entity, so "the quick brown fox jumps over something" yields nothing.
235
251
  * The entity scan stops at punctuation so it never crosses a clause. */
236
- function optimisticTriplesPos(sentence, lexicon, nlp) {
252
+ function optimisticTriplesPos(sentence, lexicon, nlp, { mintDefinitional = false } = {}) {
237
253
  let values;
238
254
  let pos;
239
255
  try {
240
256
  const doc = nlp.readDoc(String(sentence || ""));
241
257
  values = doc.tokens().out(nlp.its.value);
242
258
  pos = doc.tokens().out(nlp.its.pos);
243
- } catch { return []; }
259
+ } catch { return { triples: [], declined: [], minted: [] }; }
244
260
  // A found noun is read as its whole contiguous NOUN/PROPN run, head-lemma
245
261
  // folded — "a string instrument" is the class "string instrument", never
246
262
  // its modifier "string"; a single-word run keeps the plain lemma fold.
@@ -305,13 +321,14 @@ function optimisticTriplesPos(sentence, lexicon, nlp) {
305
321
  };
306
322
  // A relation verb whose nearest content token leftward (skipping adverbs and
307
323
  // the auxiliaries of its own verb complex) is a relative pronoun sits in a
308
- // "that/which …" relative clause — its subject is the sentence subject.
309
- const inRelativeFrame = (i) => {
324
+ // "that/which …" relative clause. Returns that pronoun's own index, or -1 when
325
+ // the verb heads a main clause.
326
+ const relativePronounBefore = (i) => {
310
327
  for (let k = i - 1; k >= 0; k -= 1) {
311
328
  if (pos[k] === "ADV" || pos[k] === "AUX") continue;
312
- return RELATIVE_PRONOUNS.has(String(values[k]).toLowerCase());
329
+ return RELATIVE_PRONOUNS.has(String(values[k]).toLowerCase()) ? k : -1;
313
330
  }
314
- return false;
331
+ return -1;
315
332
  };
316
333
  // An isa needs a CLEAN copula frame: only determiners/adjectives/adverbs/
317
334
  // numerals may sit between each entity and the copula. Crossing a verb or
@@ -356,7 +373,18 @@ function optimisticTriplesPos(sentence, lexicon, nlp) {
356
373
  while (hi + 1 < values.length && isNounish(hi + 1)) hi += 1;
357
374
  }
358
375
  const headWord = String(values[hi]).toLowerCase();
359
- const nextIsOf = values[hi + 1]?.toLowerCase() === "of";
376
+ const nextWord = values[hi + 1]?.toLowerCase();
377
+ // "latency is the name for the time period …" defines latency; it does not
378
+ // put latency under the class "name". The isa is declined and the object
379
+ // is re-read past the "for"/"of" as what the subject names.
380
+ if (DEFINITIONAL_HEADS.has(headWord) && (nextWord === "for" || nextWord === "of")) {
381
+ const named = nearestEntityIndex(hi + 1, +1, COPULA_FRAME_BLOCKERS);
382
+ return {
383
+ definitional: true, label: entityRunAt(j), hi,
384
+ names: named === null ? null : entityRunAt(named),
385
+ };
386
+ }
387
+ const nextIsOf = nextWord === "of";
360
388
  if (!nextIsOf) return { label: entityRunAt(j), hi };
361
389
  if (OF_CLASSIFIER_HEADS.has(headWord)) { i = hi + 1; j = hi + 1; continue; }
362
390
  if (OF_PARTITIVE_HEADS.has(headWord)) return null;
@@ -386,14 +414,19 @@ function optimisticTriplesPos(sentence, lexicon, nlp) {
386
414
  };
387
415
 
388
416
  const triples = [];
417
+ const declined = [];
418
+ const minted = [];
389
419
  const seen = new Set();
390
420
  const push = (subject, predicate, object) => {
391
- if (!(subject && object && subject !== object)) return;
421
+ if (!(subject && object && subject !== object)) return null;
392
422
  const key = `${subject}\0${predicate}\0${object}`;
393
- if (seen.has(key) || triples.length >= MAX_TRIPLES_PER_SENTENCE) return;
423
+ if (seen.has(key) || triples.length >= MAX_TRIPLES_PER_SENTENCE) return null;
394
424
  seen.add(key);
395
- triples.push({ subject, predicate, object });
425
+ const triple = { subject, predicate, object };
426
+ triples.push(triple);
427
+ return triple;
396
428
  };
429
+ const decline = (finding, candidate) => { declined.push({ finding, candidate }); };
397
430
 
398
431
  // Pass 1 — the first clean copula frame yields the isa (all guards unchanged);
399
432
  // its subject and object-run end anchor the relative-clause continuation.
@@ -403,6 +436,16 @@ function optimisticTriplesPos(sentence, lexicon, nlp) {
403
436
  if (pos[i] === "AUX" && OPTIMISTIC_COPULAS.has(values[i].toLowerCase())) {
404
437
  const subject = copulaSubjectAt(i);
405
438
  const object = copulaObjectAt(i);
439
+ // A definitional frame declines its isa and mints the naming edge in its
440
+ // place. The rest of the sentence still reads, through Pass 2b.
441
+ if (subject && object?.definitional) {
442
+ decline("definitional-frame", { subject: subject.label, predicate: "rdfs:subClassOf", object: object.label });
443
+ if (mintDefinitional) {
444
+ const fact = push(subject.label, NAME_FOR_PREDICATE, object.names);
445
+ if (fact) minted.push({ finding: "definitional-frame", fact });
446
+ }
447
+ break;
448
+ }
406
449
  if (subject && object && subject.label !== object.label) {
407
450
  // "is" only, never are/was/were/be/been/being/am — the same G2 rule
408
451
  // every other individual-vs-class anchor holds to: a plural/non-
@@ -424,6 +467,12 @@ function optimisticTriplesPos(sentence, lexicon, nlp) {
424
467
  // relation verb keeps its nearest-entity-leftward subject. AUX relation verbs
425
468
  // ("has") count here — but only inside a copula frame that already resolved,
426
469
  // so a bare "… is that Earth has …" complement never mints "earth has lot".
470
+ //
471
+ // The bind is adjacency-bound: the relative pronoun must directly follow the
472
+ // copula object's own run end, so the clause restricts the class the subject
473
+ // was just given ("a mountain that has lava"). A pronoun hanging off a noun
474
+ // deeper in the object's complement ("the name for the time period that needs
475
+ // …") restricts that noun, not the subject, so the verb is declined.
427
476
  if (copulaSubject) {
428
477
  for (let i = copulaObjHi + 1; i < values.length; i += 1) {
429
478
  if (pos[i] !== "VERB" && pos[i] !== "AUX") continue;
@@ -431,26 +480,38 @@ function optimisticTriplesPos(sentence, lexicon, nlp) {
431
480
  if (OPTIMISTIC_COPULAS.has(word)) continue;
432
481
  const verb = lookupVerb(lexicon, word);
433
482
  if (!verb) continue;
434
- const subject = inRelativeFrame(i) ? copulaSubject : climbedSubjectAt(i);
483
+ const relative = relativePronounBefore(i);
484
+ if (relative >= 0 && relative - 1 !== copulaObjHi) {
485
+ decline("relative-clause-verb", { subject: copulaSubject, predicate: predicateOf(verb), object: nearestEntity(i, +1) });
486
+ continue;
487
+ }
488
+ const subject = relative >= 0 ? copulaSubject : climbedSubjectAt(i);
435
489
  if (subject === null) continue;
436
490
  push(subject, predicateOf(verb), nearestEntity(i, +1));
437
491
  }
438
- return triples;
492
+ return { triples, declined, minted };
439
493
  }
440
494
 
441
495
  // Pass 2b — no copula isa: the relation-verb tier over the whole sentence,
442
496
  // climbing an of-chain subject to its head ("the weight of the snow creates
443
497
  // pressure" → weight creates pressure, not snow). VERB-tagged only, so a bare
444
498
  // AUX ("Earth has …") in a non-frame sentence stays an honest miss.
499
+ //
500
+ // With no main predication resolved, a relative clause's verb has nothing to
501
+ // bind to, so any relative frame declines here rather than guess a subject.
445
502
  for (let i = 1; i < values.length - 1; i += 1) {
446
503
  if (pos[i] !== "VERB") continue;
447
504
  const verb = lookupVerb(lexicon, values[i].toLowerCase());
448
505
  if (!verb) continue;
449
506
  const subject = climbedSubjectAt(i);
507
+ if (relativePronounBefore(i) >= 0) {
508
+ decline("relative-clause-verb", { subject, predicate: predicateOf(verb), object: nearestEntity(i, +1) });
509
+ continue;
510
+ }
450
511
  if (subject === null) continue;
451
512
  push(subject, predicateOf(verb), nearestEntity(i, +1));
452
513
  }
453
- return triples;
514
+ return { triples, declined, minted };
454
515
  }
455
516
 
456
517
  /** The lexical fallback for a checkout with no wink model: a copula flanked by
@@ -505,10 +566,24 @@ function optimisticTriplesLexical(sentence, lexicon) {
505
566
  * opts.lexicon a loaded lexicon (the core vocabulary when absent).
506
567
  * opts.nlp a wink instance (winkInstance() when absent); null forces the
507
568
  * lexical fallback.
569
+ * opts.findings mint the definitional edge a `definitional-frame` sentence
570
+ * states. Off by default, the same flag ingestText gates the
571
+ * finding-bearing rows behind.
508
572
  */
509
- export function optimisticTriples(sentence, { lexicon = loadLexicon(), nlp } = {}) {
573
+ export function optimisticTriples(sentence, opts = {}) {
574
+ return optimisticReading(sentence, opts).triples;
575
+ }
576
+
577
+ /**
578
+ * The same read as `optimisticTriples`, with how it read the sentence:
579
+ * { triples, declined, minted }. `declined` holds { finding, candidate } for
580
+ * every candidate a detector turned down; `minted` holds { finding, fact } for
581
+ * each edge minted in a declined candidate's place. Takes the same options.
582
+ */
583
+ export function optimisticReading(sentence, { lexicon = loadLexicon(), nlp, findings = false } = {}) {
510
584
  const engine = nlp === undefined ? winkInstance() : nlp;
511
- return engine ? optimisticTriplesPos(sentence, lexicon, engine) : optimisticTriplesLexical(sentence, lexicon);
585
+ if (!engine) return { triples: optimisticTriplesLexical(sentence, lexicon), declined: [], minted: [] };
586
+ return optimisticTriplesPos(sentence, lexicon, engine, { mintDefinitional: findings });
512
587
  }
513
588
 
514
589
  // A closed set of clause markers a compound sentence hinges on. A candidate
@@ -587,12 +662,18 @@ const MAX_TERM_WORDS = 6;
587
662
  // one-word term is exempt: a bare verb is a perfectly good object for a
588
663
  // capability or relation fact ("a cell is capable of grow"), and a single word
589
664
  // is never the clause fragment this rule exists to catch.
590
- const FRAGMENT_LEAD_TAGS = new Set(["VERB", "AUX", "ADP", "CCONJ", "SCONJ", "PART"]);
665
+ const FRAGMENT_LEAD_TAGS = new Set(["VERB", "AUX", "ADP", "CCONJ", "SCONJ", "PART", "ADV"]);
666
+ // The particles a phrasal verb leaves behind when a frame over-reads its
667
+ // remainder as a term: "falls back to the link" surfaces as "back to the link",
668
+ // which names nothing. Read lexically so a checkout with no wink model catches
669
+ // it too, and only for a multi-word term — "back" alone is a fine noun.
670
+ const PARTICLE_LEAD_WORDS = new Set(["back", "up", "down", "out", "off", "away", "along", "around"]);
591
671
 
592
672
  /** Does `term` read as a thing's name rather than a clause fragment? Bounds
593
- * the word count and rejects a leading conjunction, auxiliary or preposition.
594
- * Used to keep an over-read recognizer frame's predicate remainder out of the
595
- * graph, where it would otherwise hub a feed card. */
673
+ * the word count and rejects a leading conjunction, auxiliary, preposition,
674
+ * adverb or phrasal-verb particle. Used to keep an over-read recognizer
675
+ * frame's predicate remainder out of the graph, where it would otherwise hub
676
+ * a feed card. */
596
677
  export function readsAsEntityTerm(term, nlp) {
597
678
  const text = String(term ?? "").trim();
598
679
  if (!text) return false;
@@ -602,6 +683,7 @@ export function readsAsEntityTerm(term, nlp) {
602
683
  if (!first) return false;
603
684
  if (FRAGMENT_LEAD_WORDS.has(first)) return false;
604
685
  if (words.length === 1) return true;
686
+ if (PARTICLE_LEAD_WORDS.has(first)) return false;
605
687
  const engine = nlp === undefined ? winkInstance() : nlp;
606
688
  if (!engine) return true;
607
689
  try {
@@ -613,6 +695,49 @@ export function readsAsEntityTerm(term, nlp) {
613
695
 
614
696
  const readsAsEntityFact = (fact, nlp) => readsAsEntityTerm(fact.subject, nlp) && readsAsEntityTerm(fact.object, nlp);
615
697
 
698
+ /** Does one raw token read as a code identifier rather than a word? camelCase
699
+ * and snake_case split into several words, and a dot between letters or a path
700
+ * separator names a module or a file. Read on the sentence's own surface,
701
+ * before normFactTerm lower-cases the shape away: "normalizeFeedItems" is one,
702
+ * "guitar" is not. */
703
+ export function readsAsIdentifierToken(raw) {
704
+ const token = String(raw ?? "").trim();
705
+ if (!token || /\s/.test(token)) return false;
706
+ if (token.includes("_")) return true;
707
+ if (/[A-Za-z]\.[A-Za-z]/.test(token)) return true;
708
+ if (/[/\\]/.test(token)) return true;
709
+ return splitIdentifierWords(token).length > 1;
710
+ }
711
+
712
+ // The punctuation a raw sentence wraps a token in. Stripped from both ends
713
+ // before the identifier test, so "(normalizeFeedItems)," still reads as one.
714
+ const IDENTIFIER_TOKEN_EDGE_RE = /^[^A-Za-z0-9_/\\.]+|[^A-Za-z0-9_/\\.]+$/g;
715
+
716
+ /** The stored term keys `sentence` names with an identifier-shaped token. An
717
+ * endpoint whose key is in this set carries the `identifier-token` finding. */
718
+ export function identifierTermsIn(sentence) {
719
+ const terms = new Set();
720
+ for (const raw of String(sentence ?? "").match(/\S+/g) || []) {
721
+ const token = raw.replace(IDENTIFIER_TOKEN_EDGE_RE, "");
722
+ if (!token || !readsAsIdentifierToken(token)) continue;
723
+ const term = normFactTerm(token);
724
+ if (term) terms.add(term);
725
+ }
726
+ return terms;
727
+ }
728
+
729
+ /** The findings one stored row carries: whatever the sentence's own reading
730
+ * contributed (a clause fallback, a carried pronoun subject), plus
731
+ * `identifier-token` when either endpoint's stored key came from an
732
+ * identifier-shaped token. `identifierTerms` null means this run records no
733
+ * findings at all, so nothing is attached. */
734
+ function findingsForRow(fact, readingFindings, identifierTerms) {
735
+ if (!identifierTerms) return [];
736
+ const named = [...readingFindings];
737
+ if (identifierTerms.has(fact.subject) || identifierTerms.has(fact.object)) named.push("identifier-token");
738
+ return named;
739
+ }
740
+
616
741
  // A host that shares one thread with a UI hands the thread back through this;
617
742
  // a Node run leaves it unset and pays nothing.
618
743
  let ingestYield = null;
@@ -680,18 +805,31 @@ function canonicalLines(facts, storeRows) {
680
805
  * ingested fact.
681
806
  * config a loaded config; derived from the write dir when absent.
682
807
  * lexicon a loaded lexicon; the core vocabulary when absent.
808
+ * findings record how each sentence read: mint the edge a definitional
809
+ * frame states (`mgx:nameFor`) where the false isa was
810
+ * declined, and attach the kept findings (`identifier-token`,
811
+ * `clause-fallback`, `pronoun-carry`, `definitional-frame`) to
812
+ * the assertions this call writes. Off by default; the declines
813
+ * themselves are reported either way.
683
814
  *
684
- * Returns { sentences, recognized, extracted, optimistic, skipped, canonical? }.
815
+ * Returns { sentences, recognized, extracted, optimistic, skipped, declined,
816
+ * minted, canonical? }.
685
817
  * recognized — strict-recognized sentence count.
686
818
  * extracted — strict fact rows ({subject, predicate, object, provenance,
687
- * quantifier, sentence}).
819
+ * quantifier, sentence}), plus `extraction` when the row was
820
+ * stored carrying findings.
688
821
  * optimistic — fuzzy candidate rows ({subject, predicate, object, provenance,
689
- * sentence}); always [] unless options.optimistic.
822
+ * sentence}, same optional `extraction`); always [] unless
823
+ * options.optimistic.
690
824
  * skipped — sentences neither tier grounded.
825
+ * declined — every candidate a detector turned down, as
826
+ * { sentence, finding, candidate }.
827
+ * minted — every edge minted in a declined candidate's place, as
828
+ * { sentence, finding, fact }.
691
829
  */
692
830
  export async function ingestText(text, {
693
831
  memoryDir = null, sourceTag = "text", optimistic = false,
694
- canonical = false, config = null, lexicon = null, observedAt = "",
832
+ canonical = false, config = null, lexicon = null, observedAt = "", findings = false,
695
833
  } = {}) {
696
834
  // Paragraphs first (blank-line separated), so the pronoun carry never bridges
697
835
  // a topic break: a fresh paragraph clears the last-subject it would resolve
@@ -723,6 +861,10 @@ export async function ingestText(text, {
723
861
 
724
862
  const extracted = [];
725
863
  const optimisticFacts = [];
864
+ // How each sentence read: the candidates a detector turned down, and the
865
+ // edges minted where one was declined.
866
+ const declined = [];
867
+ const minted = [];
726
868
  let sentenceCount = 0;
727
869
  let recognizedSentences = 0;
728
870
  let optimisticSentences = 0;
@@ -751,6 +893,9 @@ export async function ingestText(text, {
751
893
  // — the recognizer has already written it by the time this sees it — and
752
894
  // the sentence falls through to the optimistic tier instead.
753
895
  let lastDecline = "";
896
+ // The sentence every decline and mint below is reported against, threaded the
897
+ // same way `lastDecline` is.
898
+ let currentSentence = "";
754
899
  const strictRows = async (form) => {
755
900
  if (ingestYield) await ingestYield();
756
901
  const knownIds = new Set(currentRows.map((r) => r.id));
@@ -762,6 +907,14 @@ export async function ingestText(text, {
762
907
  const fresh = rows.filter((row) => !taggedIds.has(row.id));
763
908
  const kept = fresh.filter((row) => readsAsEntityFact(row, termNlp));
764
909
  if (kept.length !== fresh.length) {
910
+ for (const row of fresh) {
911
+ if (kept.includes(row)) continue;
912
+ declined.push({
913
+ sentence: currentSentence,
914
+ finding: "fragment-term",
915
+ candidate: { subject: row.subject, predicate: row.predicate, object: row.object },
916
+ });
917
+ }
765
918
  const retractIds = fresh.filter((row) => !kept.includes(row) && !knownIds.has(row.id)).map((row) => row.id);
766
919
  if (retractIds.length) {
767
920
  await removeFacts(dir, retractIds);
@@ -781,13 +934,25 @@ export async function ingestText(text, {
781
934
  for (const sentence of splitSentencesPreservingPaths(paragraph)) {
782
935
  sentenceCount += 1;
783
936
  lastDecline = "";
937
+ currentSentence = sentence;
784
938
  const cleaned = stripCitationResidue(sentence);
785
939
  cleanedSentences.push(cleaned);
940
+ // The stored term keys this sentence names with an identifier-shaped
941
+ // token, read off the surface before normFactTerm folds the shape away.
942
+ // Null when this run records no findings.
943
+ const identifierTerms = findings ? identifierTermsIn(cleaned) : null;
944
+ // How the strict tier reached its rows, when it did: the whole sentence
945
+ // carries nothing, a later candidate is a clause fragment, and the
946
+ // pronoun retry carried its subject in from an earlier sentence.
947
+ let readingFindings = [];
786
948
  // Whole sentence first, then each closed-marker clause as a fallback.
787
949
  let rows = null;
788
- for (const candidate of clauseCandidates(cleaned, { nlp })) {
789
- rows = await strictRows(candidate);
790
- if (rows) break;
950
+ const candidates = clauseCandidates(cleaned, { nlp });
951
+ for (let i = 0; i < candidates.length; i += 1) {
952
+ rows = await strictRows(candidates[i]);
953
+ if (!rows) continue;
954
+ if (i > 0) readingFindings = ["clause-fallback"];
955
+ break;
791
956
  }
792
957
  // Bounded pronoun carry: a "they/it/these/those/this …" sentence the
793
958
  // recognizer skipped is retried once with the paragraph's last grounded
@@ -799,6 +964,7 @@ export async function ingestText(text, {
799
964
  const threaded = stripLeadingDiscourseAdverb(cleaned);
800
965
  if (!rows && carrySubject && PRONOUN_LEAD_RE.test(threaded)) {
801
966
  rows = await strictRows(threaded.replace(PRONOUN_LEAD_RE, `${articledSubject(carrySubject)} `));
967
+ if (rows) readingFindings = ["pronoun-carry"];
802
968
  }
803
969
  if (rows) {
804
970
  recognizedSentences += 1;
@@ -806,13 +972,16 @@ export async function ingestText(text, {
806
972
  if (subjects.size === 1) carrySubject = [...subjects][0];
807
973
  const tag = `extracted:${sourceTag}`;
808
974
  for (const row of rows) {
975
+ const extraction = findingsForRow(row, readingFindings, identifierTerms);
809
976
  await appendFact(dir, {
810
977
  subject: row.subject, predicate: row.predicate, object: row.object,
811
978
  provenance: tag, quantifier: row.quantifier || "", observedAt,
979
+ ...(extraction.length ? { extraction } : {}),
812
980
  });
813
981
  extracted.push({
814
982
  subject: row.subject, predicate: row.predicate, object: row.object,
815
983
  provenance: tag, quantifier: row.quantifier || "", sentence,
984
+ ...(extraction.length ? { extraction } : {}),
816
985
  });
817
986
  taggedIds.add(row.id);
818
987
  }
@@ -821,15 +990,32 @@ export async function ingestText(text, {
821
990
  const ungrounded = ungroundedTermsIn(lastDecline);
822
991
  if (ungrounded) for (const term of ungrounded) ungroundedTerms.add(term);
823
992
  if (!optimistic) continue;
824
- const candidates = optimisticTriples(cleaned, { lexicon: lex, nlp }).filter((t) => readsAsEntityFact(t, termNlp));
825
- if (!candidates.length) continue;
993
+ const reading = optimisticReading(cleaned, { lexicon: lex, nlp, findings });
994
+ for (const { finding, candidate } of reading.declined) declined.push({ sentence, finding, candidate });
995
+ const keptCandidates = [];
996
+ for (const t of reading.triples) {
997
+ if (readsAsEntityFact(t, termNlp)) keptCandidates.push(t);
998
+ else declined.push({ sentence, finding: "fragment-term", candidate: t });
999
+ }
1000
+ // A minted edge rides its own finding: minted[].fact is the very object
1001
+ // the candidate list holds, so the mint and its row match by identity
1002
+ // rather than by re-deriving the triple.
1003
+ const mintFindings = new Map();
1004
+ for (const { finding, fact } of reading.minted) {
1005
+ if (!keptCandidates.includes(fact)) continue;
1006
+ minted.push({ sentence, finding, fact });
1007
+ mintFindings.set(fact, finding);
1008
+ }
1009
+ if (!keptCandidates.length) continue;
826
1010
  optimisticSentences += 1;
827
1011
  const tag = `optimistic-extract:${sourceTag}`;
828
- for (const t of candidates) {
1012
+ for (const t of keptCandidates) {
1013
+ const extraction = findingsForRow(t, mintFindings.has(t) ? [mintFindings.get(t)] : [], identifierTerms);
829
1014
  const written = await appendFact(dir, {
830
1015
  subject: t.subject, predicate: t.predicate, object: t.object, provenance: tag, observedAt,
1016
+ ...(extraction.length ? { extraction } : {}),
831
1017
  });
832
- optimisticFacts.push({ ...t, provenance: tag, sentence });
1018
+ optimisticFacts.push({ ...t, provenance: tag, sentence, ...(extraction.length ? { extraction } : {}) });
833
1019
  taggedIds.add(written.id);
834
1020
  }
835
1021
  }
@@ -862,6 +1048,8 @@ export async function ingestText(text, {
862
1048
  skipped: sentenceCount - recognizedSentences - optimisticSentences,
863
1049
  ungroundedTerms: [...ungroundedTerms],
864
1050
  ungroundedCounts,
1051
+ declined,
1052
+ minted,
865
1053
  };
866
1054
  if (canonical) {
867
1055
  result.canonical = canonicalLines([...extracted, ...optimisticFacts], finalRows);
@@ -872,6 +1060,14 @@ export async function ingestText(text, {
872
1060
  }
873
1061
  }
874
1062
 
1063
+ /** "relative-clause-verb 1, fragment-term 2" — how many rows each named finding
1064
+ * accounts for, in the order the findings first appeared. */
1065
+ function countsByFinding(rows) {
1066
+ const counts = new Map();
1067
+ for (const row of rows) counts.set(row.finding, (counts.get(row.finding) || 0) + 1);
1068
+ return [...counts].map(([finding, n]) => `${finding} ${n}`).join(", ");
1069
+ }
1070
+
875
1071
  /**
876
1072
  * `argv` defaults to the real CLI args (process.argv.slice(2)) but takes an
877
1073
  * explicit array too, so a test can drive this exactly like the CLI does
@@ -885,7 +1081,7 @@ export async function main(argv = process.argv.slice(2)) {
885
1081
  if (!file) {
886
1082
  console.error(USAGE);
887
1083
  process.exitCode = 1;
888
- return { sentences: 0, recognized: 0, extracted: [], optimistic: [], skipped: 0 };
1084
+ return { sentences: 0, recognized: 0, extracted: [], optimistic: [], skipped: 0, declined: [], minted: [] };
889
1085
  }
890
1086
 
891
1087
  const filePath = resolve(process.cwd(), file);
@@ -903,7 +1099,7 @@ export async function main(argv = process.argv.slice(2)) {
903
1099
  result = await ingestText(text, {
904
1100
  memoryDir: store ? store.dir : null,
905
1101
  config: repoRoot ? loadConfig(process.env, repoRoot) : null,
906
- sourceTag, optimistic, canonical,
1102
+ sourceTag, optimistic, canonical, findings: true,
907
1103
  });
908
1104
  } finally {
909
1105
  if (store) await store.close();
@@ -934,7 +1130,22 @@ export async function main(argv = process.argv.slice(2)) {
934
1130
  + `Ground one side first (e.g. "every ${result.ungroundedTerms[0]} is a thing") and re-run.`
935
1131
  : ""),
936
1132
  );
1133
+ if (result.declined.length) {
1134
+ console.error(
1135
+ `${result.declined.length} candidate${result.declined.length === 1 ? "" : "s"} declined `
1136
+ + `on how the sentence read: ${countsByFinding(result.declined)}.`,
1137
+ );
1138
+ }
1139
+ if (result.minted.length) {
1140
+ console.error(
1141
+ `${result.minted.length} edge${result.minted.length === 1 ? "" : "s"} minted `
1142
+ + `in a declined candidate's place: ${countsByFinding(result.minted)}.`,
1143
+ );
1144
+ }
937
1145
  if (repo) console.error(`facts written into ${repoRoot}'s tmct memory, tagged ${sourceTag}`);
938
1146
  if (out) console.error(`facts written to ${out}`);
939
- return { sentences, recognized, extracted: result.extracted, optimistic: result.optimistic, skipped: result.skipped };
1147
+ return {
1148
+ sentences, recognized, extracted: result.extracted, optimistic: result.optimistic,
1149
+ skipped: result.skipped, declined: result.declined, minted: result.minted,
1150
+ };
940
1151
  }
@@ -228,9 +228,11 @@ function seedRequested({ optSeed, configEnabled, env }) {
228
228
  * @param {object} [opts.env] environment (for TMCT_NO_SEED); defaults to process.env.
229
229
  * @param {object} [opts.persona] a resolved PERSONA_PRESETS entry ({extensions?, bias?})
230
230
  * merged into a FRESH config only; name resolution is the caller's job (bin/tmct.mjs).
231
- * @param {string} [opts.memoryBackend] "default" | "memory" | "sqlite" — merged into a
231
+ * @param {string|object} [opts.memoryBackend] "default" | "memory" | "sqlite" — merged into a
232
232
  * FRESH config's `[memory] backend`, and selects which backend the corpus seed writes
233
- * into (via src/adapters/memory/core.mjs's openMemoryBackend).
233
+ * into (via src/adapters/memory/core.mjs's openMemoryBackend). A row backend object (or a
234
+ * wrapRowBackend handle) instead seeds straight into that injected store and is never
235
+ * written to tmct.toml — a config file has no way to name a live object.
234
236
  * @param {string} [opts.researchSource] "wikipedia" | "wikidata" | "simple-wikipedia-pack" — merged into a
235
237
  * FRESH config's `[research] source`, the tmct.toml tier of the research lane's
236
238
  * source precedence (src/services/chat-session.mjs createSession).
@@ -314,7 +316,12 @@ export async function initRepo(dir, { force = false, seed, env = process.env, pe
314
316
  if (persona.extensions && Object.keys(persona.extensions).length) config.extensions = persona.extensions;
315
317
  if (persona.bias && Object.keys(persona.bias).length) config.bias = persona.bias;
316
318
  }
317
- if (memoryBackend) config.memory = { ...(config.memory || {}), backend: memoryBackend };
319
+ // A backend passed as an OBJECT is an injected row store (or a handle over
320
+ // one): it seeds directly and stays out of the written config, because a
321
+ // config file can only name a string backend. openMemoryBackend does the real
322
+ // shape check and refuses an object that is not a row backend.
323
+ const injectedRowStore = !!memoryBackend && typeof memoryBackend === "object";
324
+ if (memoryBackend && !injectedRowStore) config.memory = { ...(config.memory || {}), backend: memoryBackend };
318
325
  if (researchSource) config.research = { ...(config.research || {}), source: researchSource };
319
326
  const tomlPresent = await exists(paths.toml);
320
327
  if (!tomlPresent || force) {
@@ -337,9 +344,12 @@ export async function initRepo(dir, { force = false, seed, env = process.env, pe
337
344
  } else if ((await exists(paths.marker)) && !force) {
338
345
  seedNote = "seed skipped (already seeded — marker present)";
339
346
  } else {
340
- // Seeds into whichever backend config.memory.backend names. "memory" is skipped
347
+ // Seeds into whichever backend config.memory.backend names, or straight into
348
+ // an injected row store when the caller passed one. "memory" is skipped
341
349
  // outright: it's an in-process-only store that vanishes when this process exits.
342
- const backendChoice = String(config.memory?.backend || "").trim().toLowerCase();
350
+ const backendChoice = injectedRowStore
351
+ ? memoryBackend
352
+ : String(config.memory?.backend || "").trim().toLowerCase();
343
353
  if (backendChoice === "memory") {
344
354
  seedNote = "seed skipped (memory backend is in-process only — nothing would persist past this command)";
345
355
  } else {
@@ -335,7 +335,9 @@ async function ingestSnapshotFacts(ctx, snapshot) {
335
335
  const lex = lexicon || loadLexicon();
336
336
  const text = joinTitleAndSummary(snapshot.title, snapshot.summary);
337
337
  const sourceTag = `news:${snapshot.sourceId}@${snapshot.id}`;
338
- const result = await ingestText(text, { memoryDir, sourceTag, optimistic: true, lexicon: lex, observedAt: nowVal });
338
+ const result = await ingestText(text, {
339
+ memoryDir, sourceTag, optimistic: true, lexicon: lex, observedAt: nowVal, findings: true,
340
+ });
339
341
  invalidateCache(cache);
340
342
 
341
343
  const allFacts = [...result.extracted, ...result.optimistic];
@@ -623,7 +625,7 @@ async function ingestResearchArticle(ctx, term, provider, article) {
623
625
  if (prose) {
624
626
  ingested = await ingestText(prose, {
625
627
  memoryDir, sourceTag: provenance, optimistic: true,
626
- lexicon: lexicon || loadLexicon(), observedAt: resolveNow(now),
628
+ lexicon: lexicon || loadLexicon(), observedAt: resolveNow(now), findings: true,
627
629
  });
628
630
  invalidateCache(ctx.cache);
629
631
  }