@polycode-projects/the-mechanical-code-talker 5.0.46 → 6.0.1
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 +27 -0
- package/bin/tmct.mjs +61 -0
- package/package.json +14 -2
- package/src/adapters/memory/backends-exports.mjs +8 -0
- package/src/adapters/memory/core.mjs +812 -175
- package/src/adapters/memory/corpus-bands.mjs +155 -0
- package/src/adapters/memory/dynamo-circuit-breaker.mjs +266 -0
- package/src/adapters/memory/row-backend-dynamo.mjs +315 -0
- package/src/adapters/memory/row-backend-memory.mjs +85 -0
- package/src/adapters/memory/row-backend.mjs +162 -0
- package/src/adapters/memory/rows.mjs +328 -0
- package/src/adapters/memory/shacl.mjs +24 -0
- package/src/adapters/memory/systemic-failure.mjs +28 -0
- package/src/adapters/research-queue-store.mjs +215 -32
- package/src/domain/ask.mjs +341 -75
- package/src/domain/cli-verbs.mjs +17 -0
- package/src/domain/fact-phrase.mjs +40 -0
- package/src/domain/news-feed.mjs +42 -4
- package/src/domain/phrase-exports.mjs +4 -0
- package/src/domain/retrieval-marker.mjs +120 -0
- package/src/domain/retrieval-modes.mjs +13 -0
- package/src/domain/retrieval-plan.mjs +224 -0
- package/src/services/chat-session.mjs +36 -9
- package/src/services/chat.mjs +73 -16
- package/src/services/corpus-loader.mjs +222 -0
- package/src/services/extract-facts.mjs +244 -33
- package/src/services/init.mjs +15 -5
- package/src/services/news.mjs +4 -2
- package/src/services/subgraph-retrieval.mjs +332 -0
- package/src/surfaces/web/http-row-backend.mjs +150 -0
- package/src/surfaces/web/memory-ask-browser.bundle.js +134 -131
- package/src/surfaces/web/news-browser-entry.mjs +6 -2
- package/src/tools/handlers/tmct-ingest.mjs +3 -1
- package/src/tools/memory-backend-conformance.mjs +238 -0
package/src/domain/news-feed.mjs
CHANGED
|
@@ -83,7 +83,9 @@ export function newsWindowRows(rows, { now, windowMs }) {
|
|
|
83
83
|
// happened to it, so a row under any of these bands background whoever wrote
|
|
84
84
|
// it. Distinct from renderNewsParagraph's own narrower IDENTITY_PREDICATES
|
|
85
85
|
// (below), which only needs the two positive forms for its identity sentence.
|
|
86
|
-
|
|
86
|
+
// `mgx:nameFor` joins this set too: "X is the name for Y" defines X, and a
|
|
87
|
+
// definition is never a card head, whatever the row's own findings say.
|
|
88
|
+
const GATE_IDENTITY_PREDICATES = new Set(["rdf:type", "rdfs:subClassOf", "mgxneg:subClassOf", "owl:disjointWith", "mgx:nameFor"]);
|
|
87
89
|
|
|
88
90
|
// Every determiner a universal quantifier is ever stored under — today only
|
|
89
91
|
// "every" is written (chat.mjs's own teach lane), "all"/"each" kept here so a
|
|
@@ -230,16 +232,27 @@ const ENTITY_FRAGMENT_LEAD_WORDS = new Set([
|
|
|
230
232
|
"against", "among", "within", "without", "per",
|
|
231
233
|
]);
|
|
232
234
|
|
|
235
|
+
// The particles a phrasal verb leaves behind when a frame over-reads its
|
|
236
|
+
// remainder as a term ("falls back to the link" surfaces as "back to the
|
|
237
|
+
// link", which names nothing) — mirrors extract-facts.mjs's own
|
|
238
|
+
// PARTICLE_LEAD_WORDS lexically, with no POS-tag rule, since the domain layer
|
|
239
|
+
// never imports the services-layer wink engine. Applies only to a multi-word
|
|
240
|
+
// term; "back" alone is a fine noun.
|
|
241
|
+
const ENTITY_PARTICLE_LEAD_WORDS = new Set(["back", "up", "down", "out", "off", "away", "along", "around"]);
|
|
242
|
+
|
|
233
243
|
/** Does `term` read as a thing's name rather than a clause fragment? Bounds
|
|
234
244
|
* the word count and rejects a leading conjunction, auxiliary or
|
|
235
|
-
* preposition (test E's condition 3, PLAN_NEWSWORTHINESS.md section 2)
|
|
245
|
+
* preposition (test E's condition 3, PLAN_NEWSWORTHINESS.md section 2), plus
|
|
246
|
+
* a leading phrasal-verb particle on a multi-word term. */
|
|
236
247
|
function looksLikeEntityTerm(term) {
|
|
237
248
|
const text = String(term ?? "").trim();
|
|
238
249
|
if (!text) return false;
|
|
239
250
|
const words = text.split(/\s+/);
|
|
240
251
|
if (words.length > ENTITY_TERM_MAX_WORDS) return false;
|
|
241
252
|
const first = words[0].toLowerCase().replace(/^[^a-z0-9]+/, "");
|
|
242
|
-
|
|
253
|
+
if (!first || ENTITY_FRAGMENT_LEAD_WORDS.has(first)) return false;
|
|
254
|
+
if (words.length > 1 && ENTITY_PARTICLE_LEAD_WORDS.has(first)) return false;
|
|
255
|
+
return true;
|
|
243
256
|
}
|
|
244
257
|
|
|
245
258
|
// The Wikidata research provenance tag (researchSourceTag in
|
|
@@ -252,6 +265,21 @@ function looksLikeEntityTerm(term) {
|
|
|
252
265
|
const WIKIDATA_RESEARCH_PROVENANCE_RE = /(?:^|:)research:wikidata:/;
|
|
253
266
|
const WIKIDATA_QID_TERM_RE = /^q[1-9]\d*$/;
|
|
254
267
|
|
|
268
|
+
// The two attached findings a row's own extraction may carry that disqualify
|
|
269
|
+
// it from heading a card or anchoring novelty (PLAN_EXTRACTION_CONFIDENCE.md
|
|
270
|
+
// section 2.5): an identifier-shaped token or a clause-fallback read is a
|
|
271
|
+
// structural tell the row was mis-read, not a report a card should lead
|
|
272
|
+
// with. `pronoun-carry` is deliberately absent — a subject carried from the
|
|
273
|
+
// paragraph's own prose is not a mis-read, and barring it would suppress
|
|
274
|
+
// real hubs. A row with no `extraction` at all (nothing recorded, or an old
|
|
275
|
+
// row from before this plan) never matches.
|
|
276
|
+
const GATE_DECLINING_FINDINGS = new Set(["identifier-token", "clause-fallback"]);
|
|
277
|
+
|
|
278
|
+
function rowCarriesGateDecliningFinding(row) {
|
|
279
|
+
const extraction = row.extraction;
|
|
280
|
+
return Array.isArray(extraction) && extraction.some((finding) => GATE_DECLINING_FINDINGS.has(finding));
|
|
281
|
+
}
|
|
282
|
+
|
|
255
283
|
function hasWikidataQidAnchor(term, rows) {
|
|
256
284
|
for (const row of rows) {
|
|
257
285
|
if (!WIKIDATA_RESEARCH_PROVENANCE_RE.test(String(row.provenance || ""))) continue;
|
|
@@ -284,14 +312,23 @@ export function newsworthyHubs(rows, reported, {
|
|
|
284
312
|
|
|
285
313
|
const counts = new Map();
|
|
286
314
|
const subjectRowsByTerm = new Map();
|
|
315
|
+
// A term with at least one occurrence in a row the gate did not decline —
|
|
316
|
+
// test E's own condition (below): a term backed ONLY by declined rows never
|
|
317
|
+
// heads a card, but one clean occurrence is enough even when a tainted one
|
|
318
|
+
// also mentions it.
|
|
319
|
+
const hasUndeclinedOccurrence = new Map();
|
|
287
320
|
for (const row of reported) {
|
|
288
321
|
const s = normFactTerm(row.subject);
|
|
289
322
|
const o = normFactTerm(row.object);
|
|
323
|
+
const declined = rowCarriesGateDecliningFinding(row);
|
|
290
324
|
for (const term of [s, o]) {
|
|
291
325
|
if (!term || STOP_SET.has(term)) continue;
|
|
292
326
|
counts.set(term, (counts.get(term) || 0) + 1);
|
|
327
|
+
if (!declined) hasUndeclinedOccurrence.set(term, true);
|
|
293
328
|
}
|
|
294
|
-
|
|
329
|
+
// A declined row is excluded from `subjectRowsByTerm` outright — test A's
|
|
330
|
+
// own anchor never comes from a row the gate declined.
|
|
331
|
+
if (s && !STOP_SET.has(s) && !declined) {
|
|
295
332
|
let subjRows = subjectRowsByTerm.get(s);
|
|
296
333
|
if (!subjRows) subjectRowsByTerm.set(s, (subjRows = []));
|
|
297
334
|
subjRows.push(row);
|
|
@@ -301,6 +338,7 @@ export function newsworthyHubs(rows, reported, {
|
|
|
301
338
|
function passesEntityTest(term) {
|
|
302
339
|
if (concepts.has(term) || isQuantityTerm(term)) return false;
|
|
303
340
|
if (!readsAsEntityTerm(term)) return false;
|
|
341
|
+
if (!hasUndeclinedOccurrence.get(term)) return false;
|
|
304
342
|
return isNovelTerm(term, priorSet);
|
|
305
343
|
}
|
|
306
344
|
|
|
@@ -15,6 +15,10 @@ export {
|
|
|
15
15
|
thirdPersonSingularSurface,
|
|
16
16
|
baseVerbSurface,
|
|
17
17
|
gerundVerbSurface,
|
|
18
|
+
// The short caveat a row carrying an extraction finding reads with, so an
|
|
19
|
+
// embedding host renders the same honesty beside the same rows tmct does.
|
|
20
|
+
FINDING_CAVEATS,
|
|
21
|
+
findingCaveat,
|
|
18
22
|
} from "./fact-phrase.mjs";
|
|
19
23
|
|
|
20
24
|
// Provenance: the `reference:<pack>:<Title>@<revid>` tag a reference-grounded
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
// retrieval-marker.mjs — the trailing line an answer carries when a corpus
|
|
2
|
+
// retrieval stood behind it, or when one was supposed to and did not.
|
|
3
|
+
//
|
|
4
|
+
// A bounded retrieval reads a slice of the corpus, never the whole of it. A
|
|
5
|
+
// point answer is unaffected: it either grounds on what came back or misses.
|
|
6
|
+
// An answer that reports the extent of a set is different. Reporting the
|
|
7
|
+
// slice's contents as the store's would be a completeness claim nothing
|
|
8
|
+
// checked, so those answers say what they counted over.
|
|
9
|
+
//
|
|
10
|
+
// Three states, three fixed lines. The wording is written once here and pinned
|
|
11
|
+
// byte for byte, because it lands in prose a reader judges the whole product
|
|
12
|
+
// by.
|
|
13
|
+
|
|
14
|
+
import { SUPPLEMENTED_MODE, SEED_SESSION_MODE } from "./retrieval-modes.mjs";
|
|
15
|
+
|
|
16
|
+
export { SUPPLEMENTED_MODE, SEED_SESSION_MODE };
|
|
17
|
+
|
|
18
|
+
/** Retrieval ran and nothing stopped it early. */
|
|
19
|
+
export const CORPUS_SCOPE_LINE = "Corpus scope: the rows this query pulled from the corpus.";
|
|
20
|
+
|
|
21
|
+
/** Retrieval ran and a budget stopped it, or a read failed. Over a dense
|
|
22
|
+
* corpus this is the ordinary case rather than the exception — the
|
|
23
|
+
* subClassOf closure branches, so a grounded turn spends its query budget
|
|
24
|
+
* and comes back with a prefix. The line reads as a routine statement of
|
|
25
|
+
* scope for that reason. */
|
|
26
|
+
export const CORPUS_SCOPE_BOUNDED_LINE = "Corpus scope: the rows this query pulled from the corpus. The corpus may hold more.";
|
|
27
|
+
|
|
28
|
+
/** No corpus read happened while bands were configured — the breaker is open,
|
|
29
|
+
* so the turn answered from the bundled seed and the session alone. Under
|
|
30
|
+
* that floor this line is the reader's only signal that a thin answer came
|
|
31
|
+
* from the degraded mode, so it rides every answer, not only the ones that
|
|
32
|
+
* count a set. */
|
|
33
|
+
export const CORPUS_SUPPLEMENT_ABSENT_LINE = "Corpus scope: none. Answered without the corpus supplement.";
|
|
34
|
+
|
|
35
|
+
/** The enumeration-class lanes: the answers that report a set's extent, and so
|
|
36
|
+
* have to say what they counted over.
|
|
37
|
+
*
|
|
38
|
+
* Every entry is referenced from the composer that mints it, and the lane
|
|
39
|
+
* inventory test holds that both ways — a registered lane no composer sets is
|
|
40
|
+
* dead, and a composer naming a lane that is not registered is a lane nobody
|
|
41
|
+
* classified. */
|
|
42
|
+
export const ENUMERATION_LANES = Object.freeze({
|
|
43
|
+
/** "how many facts do you know" — a tally of a memory-store kind. */
|
|
44
|
+
MEMORY_COUNT: "memory-count",
|
|
45
|
+
/** "list facts" / "how many sessions are there" — the stored individuals. */
|
|
46
|
+
MEMORY_CLASS: "memory-class",
|
|
47
|
+
/** "which words have a p in them" — the store's own vocabulary, filtered. */
|
|
48
|
+
LETTER_WORDS: "letter-words",
|
|
49
|
+
/** "list the letters in the alphabet" — a declared collection's contents. */
|
|
50
|
+
COLLECTION_CONTENTS: "collection-contents",
|
|
51
|
+
/** "how many animals are there" — a taught class's members, tallied. */
|
|
52
|
+
TAUGHT_CLASS_COUNT: "taught-class-count",
|
|
53
|
+
/** "list the animals" — a taught class's members, named. */
|
|
54
|
+
MEMBERSHIP_LIST: "membership-list",
|
|
55
|
+
/** "name an animal" — one member, and a count of the rest. */
|
|
56
|
+
MEMBERSHIP_EXAMPLE: "membership-example",
|
|
57
|
+
/** "another word for dog" — the remembered synonym neighbourhood. */
|
|
58
|
+
SKOS_NEIGHBOURHOOD: "skos-neighbourhood",
|
|
59
|
+
/** "what else about a dog" — everything past the primary definition. */
|
|
60
|
+
WHAT_ELSE: "what-else",
|
|
61
|
+
/** "which animals can fly" and its siblings, read out of the fact store. */
|
|
62
|
+
FACT_SET: "fact-set",
|
|
63
|
+
/** "what did you learn about dogs" — the read-back cascade's listings. */
|
|
64
|
+
FACT_READBACK: "fact-readback",
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
const REGISTERED_LANES = Object.freeze(Object.values(ENUMERATION_LANES));
|
|
68
|
+
|
|
69
|
+
/** Is this a lane name the registry knows? */
|
|
70
|
+
export function isEnumerationLane(lane) {
|
|
71
|
+
return typeof lane === "string" && REGISTERED_LANES.includes(lane);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Does this answer report the extent of a set?
|
|
75
|
+
*
|
|
76
|
+
* A truncated listing does by definition — it is holding a remainder. So does
|
|
77
|
+
* any answer that renders more than one fact line: two lines are a set, and a
|
|
78
|
+
* reader takes them as everything there was. One line is a point answer and
|
|
79
|
+
* changes nothing.
|
|
80
|
+
*
|
|
81
|
+
* The fact-store lanes derive their marker through this rather than tagging
|
|
82
|
+
* each of their twenty-odd return sites, which means a reader added to those
|
|
83
|
+
* cascades later is covered the moment it renders a set. */
|
|
84
|
+
export function answerAssertsASet(text, { pending = null } = {}) {
|
|
85
|
+
if (pending) return true;
|
|
86
|
+
return String(text ?? "").split("\n").filter((line) => line.trim() !== "").length > 1;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** The retrieval context in the shape the marker reads, or null when the
|
|
90
|
+
* caller passed none. Accepts `retrieveSubgraph`'s own metrics object
|
|
91
|
+
* unchanged, and the smaller `{mode, bounded, bands}` literal a handler may
|
|
92
|
+
* build by hand. Anything without a recognised mode reads as no context, so a
|
|
93
|
+
* malformed input can never mint a marker. */
|
|
94
|
+
export function retrievalContextOf(input) {
|
|
95
|
+
if (!input || typeof input !== "object") return null;
|
|
96
|
+
const mode = input.mode;
|
|
97
|
+
if (mode !== SUPPLEMENTED_MODE && mode !== SEED_SESSION_MODE) return null;
|
|
98
|
+
return {
|
|
99
|
+
mode,
|
|
100
|
+
bounded: Boolean(input.bounded),
|
|
101
|
+
bands: Array.isArray(input.bands) ? input.bands : [],
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** The trailing line this turn's answer carries, or null for no line.
|
|
106
|
+
*
|
|
107
|
+
* No context at all means no line, which is what every caller that never
|
|
108
|
+
* retrieves gets: the local shell, the browser page, every existing test.
|
|
109
|
+
*
|
|
110
|
+
* A seed-session turn with no bands configured is not a degraded mode, it is
|
|
111
|
+
* a deployment without a corpus, so it says nothing either. */
|
|
112
|
+
export function retrievalMarkerLine(retrieval, { enumerationLane = null } = {}) {
|
|
113
|
+
const context = retrievalContextOf(retrieval);
|
|
114
|
+
if (!context) return null;
|
|
115
|
+
if (context.mode === SEED_SESSION_MODE) {
|
|
116
|
+
return context.bands.length ? CORPUS_SUPPLEMENT_ABSENT_LINE : null;
|
|
117
|
+
}
|
|
118
|
+
if (!isEnumerationLane(enumerationLane)) return null;
|
|
119
|
+
return context.bounded ? CORPUS_SCOPE_BOUNDED_LINE : CORPUS_SCOPE_LINE;
|
|
120
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// retrieval-modes.mjs — the two honest modes a turn's retrieval payload can
|
|
2
|
+
// carry. Every layer that needs to say "the corpus supplement ran" or "it
|
|
3
|
+
// did not" reads these two strings rather than minting its own, so a
|
|
4
|
+
// retrieval-layer skip and a breaker-forced skip land in an answer looking
|
|
5
|
+
// identical.
|
|
6
|
+
|
|
7
|
+
/** Retrieval ran and the answer stands on the corpus supplement as well as
|
|
8
|
+
* the seed and the session. */
|
|
9
|
+
export const SUPPLEMENTED_MODE = "supplemented";
|
|
10
|
+
|
|
11
|
+
/** No corpus read happened — no bands are configured, or the breaker is
|
|
12
|
+
* open. The answer stands on the bundled seed and the session alone. */
|
|
13
|
+
export const SEED_SESSION_MODE = "seed-session";
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
// retrieval-plan.mjs — what a turn asks a corpus for, worked out before any
|
|
2
|
+
// read happens. Pure: the same text, the same fuzzy mode and the same caps give
|
|
3
|
+
// the same plan, on any machine, in any order.
|
|
4
|
+
//
|
|
5
|
+
// The plan mirrors the engine's own reach rather than guessing at relevance.
|
|
6
|
+
// The engine chases aliases two hops and widens inheritance one stored
|
|
7
|
+
// rdfs:subClassOf hop, so the plan pulls two hops of relations plus the whole
|
|
8
|
+
// subClassOf ancestry chain above whatever it finds. A subgraph that covers
|
|
9
|
+
// those bounds holds everything the engine could have reached anyway.
|
|
10
|
+
//
|
|
11
|
+
// Nothing here is scored or ranked. Terms come out sorted, variants come out
|
|
12
|
+
// sorted and capped, and a cap always cuts the same tail. That is what lets a
|
|
13
|
+
// smaller budget return a prefix of a larger one's answer instead of a
|
|
14
|
+
// different answer.
|
|
15
|
+
|
|
16
|
+
import { normFactTerm } from "./hash.mjs";
|
|
17
|
+
import { loadLexicon, lookupNoun, classify } from "./grammar/lexicon.mjs";
|
|
18
|
+
import { editDistance, fuzzyBound, FUZZY_REPAIR_MIN_LENGTH } from "./interpret/fuzzy.mjs";
|
|
19
|
+
import { STOPWORDS, splitWords, normalizeQuery } from "./interpret/normalize.mjs";
|
|
20
|
+
import collisionData from "./real-word-collisions.json" with { type: "json" };
|
|
21
|
+
|
|
22
|
+
/** The row class a fact projects onto. The closed set itself lives with the
|
|
23
|
+
* backend contract, one layer out, so the one value this module reads is
|
|
24
|
+
* spelled here rather than imported upward. */
|
|
25
|
+
const FACT_ROW_CLASS = "fact";
|
|
26
|
+
|
|
27
|
+
/** The predicate whose object is a superclass. The ancestry chase follows this
|
|
28
|
+
* and nothing else. */
|
|
29
|
+
export const ANCESTRY_PREDICATE = "rdfs:subClassOf";
|
|
30
|
+
|
|
31
|
+
/** Real English words the fuzzy tier attracts. A word already in the language
|
|
32
|
+
* is not a typo, so retrieval spends no variants on it: the exact query is the
|
|
33
|
+
* answer path, and variants of a real word only pull rows about something
|
|
34
|
+
* else. The fuzzy tier keeps its own copy of this set behind an accessor that
|
|
35
|
+
* answers a different question (which repair to make), so this module reads
|
|
36
|
+
* the committed table directly. */
|
|
37
|
+
const REAL_ENGLISH_WORDS = new Set(collisionData.words);
|
|
38
|
+
|
|
39
|
+
/** Word classes that never name a fact's subject. Retrieval keys on subjects,
|
|
40
|
+
* which are nominal, so a known verb, adjective, determiner or quantifier is
|
|
41
|
+
* dropped before it costs a Query. An unknown word survives: it may be an
|
|
42
|
+
* entity the lexicon has never heard of, or the typo fuzzy mode exists for. */
|
|
43
|
+
const NON_SUBJECT_PARTS_OF_SPEECH = new Set(["verb", "adjective", "determiner", "quantifier", "number"]);
|
|
44
|
+
|
|
45
|
+
const MIN_TERM_LENGTH = 2;
|
|
46
|
+
|
|
47
|
+
/** Function words that cannot name a subject, on top of the parser's own
|
|
48
|
+
* stopword list: pronouns, auxiliaries and conjunctions.
|
|
49
|
+
*
|
|
50
|
+
* Prepositions and degree words are deliberately absent, though they look like
|
|
51
|
+
* the obvious next thing to drop. "above", "below", "between", "always" and
|
|
52
|
+
* "never" are all real corpus terms carrying real facts, and a term this list
|
|
53
|
+
* refuses is a miss that never had to happen. Asking for a word that grounds
|
|
54
|
+
* nothing costs one Query, and the budgets already cap those. */
|
|
55
|
+
const FUNCTION_WORDS = new Set([
|
|
56
|
+
"am", "and", "as", "be", "because", "been", "being", "but", "he", "her", "hers", "herself",
|
|
57
|
+
"him", "himself", "his", "i", "if", "it", "its", "itself", "me", "mine", "my", "myself",
|
|
58
|
+
"nor", "or", "our", "ours", "ourselves", "she", "so", "that", "their", "theirs", "them",
|
|
59
|
+
"themselves", "these", "they", "this", "those", "though", "us", "we", "whether", "while",
|
|
60
|
+
"you", "your", "yours", "yourself",
|
|
61
|
+
]);
|
|
62
|
+
|
|
63
|
+
/** The regular singular folds, applied to a word the lexicon does not know.
|
|
64
|
+
* A known noun folds through `lookupNoun`, which already runs these; a corpus
|
|
65
|
+
* term the lexicon never declared ("tariffs") needs them applied directly. */
|
|
66
|
+
function regularSingularForms(word) {
|
|
67
|
+
const forms = [];
|
|
68
|
+
if (word.length > 4 && /[a-z]ies$/.test(word)) forms.push(`${word.slice(0, -3)}y`);
|
|
69
|
+
if (/(ses|xes|zes|ches|shes|oes)$/.test(word)) forms.push(word.slice(0, -2));
|
|
70
|
+
// "analysis", "basis", "status", "virus" are singular already, and stripping
|
|
71
|
+
// the s buys a term no corpus stores.
|
|
72
|
+
if (/[a-z]s$/.test(word) && !/(ss|is|us)$/.test(word)) forms.push(word.slice(0, -1));
|
|
73
|
+
return forms;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const sortedUnique = (values) => [...new Set(values)].sort();
|
|
77
|
+
|
|
78
|
+
/** The words in `text` that could name a subject, each with the position it
|
|
79
|
+
* held in the normalized turn, so only words the writer actually wrote side by
|
|
80
|
+
* side pair up into a two-word term. The turn goes through the same
|
|
81
|
+
* normalization the parser applies, so retrieval and the engine read one text.
|
|
82
|
+
* Dotted tokens survive: a module name is a subject. */
|
|
83
|
+
export function subjectWordsOf(text, { lexicon = loadLexicon() } = {}) {
|
|
84
|
+
const words = [];
|
|
85
|
+
const tokens = splitWords(normalizeQuery(String(text ?? "")));
|
|
86
|
+
for (let position = 0; position < tokens.length; position += 1) {
|
|
87
|
+
const word = tokens[position].toLowerCase().replace(/^[^a-z0-9]+/, "").replace(/[^a-z0-9.\-_]+$/, "");
|
|
88
|
+
if (word.length < MIN_TERM_LENGTH) continue;
|
|
89
|
+
if (STOPWORDS.has(word) || FUNCTION_WORDS.has(word)) continue;
|
|
90
|
+
const reading = classify(word, lexicon);
|
|
91
|
+
if (reading && NON_SUBJECT_PARTS_OF_SPEECH.has(reading.pos)) continue;
|
|
92
|
+
words.push({ word, position });
|
|
93
|
+
}
|
|
94
|
+
return words;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Every canonical form one surface word could be stored under: the normalized
|
|
98
|
+
* word itself, the lexicon's lemma for it, and the regular singular when the
|
|
99
|
+
* lexicon has no entry to fold through. */
|
|
100
|
+
export function foldedFormsOf(word, { lexicon = loadLexicon() } = {}) {
|
|
101
|
+
const base = normFactTerm(word);
|
|
102
|
+
if (!base) return [];
|
|
103
|
+
const forms = [base];
|
|
104
|
+
const noun = lookupNoun(lexicon, base);
|
|
105
|
+
if (noun?.lemma && noun.lemma !== base) forms.push(normFactTerm(noun.lemma));
|
|
106
|
+
else for (const folded of regularSingularForms(base)) forms.push(normFactTerm(folded));
|
|
107
|
+
return sortedUnique(forms.filter(Boolean));
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** The exact terms a turn offers retrieval: each subject word's folded forms,
|
|
111
|
+
* plus the adjacent-word pairs, because a corpus subject is routinely two
|
|
112
|
+
* words ("roman letter", "time period"). Sorted and deduped. */
|
|
113
|
+
export function queryTerms(text, { lexicon = loadLexicon() } = {}) {
|
|
114
|
+
const words = subjectWordsOf(text, { lexicon });
|
|
115
|
+
const terms = [];
|
|
116
|
+
for (const { word } of words) terms.push(...foldedFormsOf(word, { lexicon }));
|
|
117
|
+
for (let i = 1; i < words.length; i += 1) {
|
|
118
|
+
if (words[i].position !== words[i - 1].position + 1) continue;
|
|
119
|
+
const pair = normFactTerm(`${words[i - 1].word} ${words[i].word}`);
|
|
120
|
+
if (pair) terms.push(pair);
|
|
121
|
+
}
|
|
122
|
+
return sortedUnique(terms);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Deterministic fuzzy variants for one term: the words of a closed vocabulary
|
|
126
|
+
* within a fixed edit distance, capped, and ordered by that same distance with
|
|
127
|
+
* alphabetical order breaking every tie. Nothing is scored. The order is the
|
|
128
|
+
* bound the tier already measures, so a cap keeps the nearest forms instead of
|
|
129
|
+
* whatever the alphabet happened to put first.
|
|
130
|
+
*
|
|
131
|
+
* `vocabulary` is any iterable of candidate words. It defaults to the grammar
|
|
132
|
+
* lexicon's nouns, which is the vocabulary available with no store loaded; a
|
|
133
|
+
* caller holding a seeded payload passes that store's own terms instead and
|
|
134
|
+
* reaches everything the seed knows about.
|
|
135
|
+
*
|
|
136
|
+
* A term that is already vocabulary, already real English, too short for the
|
|
137
|
+
* bound to mean anything, or not plain alphabetic gets no variants. */
|
|
138
|
+
export function fuzzyVariantsFor(term, { lexicon = loadLexicon(), vocabulary = null, cap } = {}) {
|
|
139
|
+
if (!Number.isInteger(cap) || cap < 0) throw new TypeError(`cap must be a non-negative integer, got ${JSON.stringify(cap)}`);
|
|
140
|
+
if (cap === 0) return [];
|
|
141
|
+
if (!/^[a-z]+$/.test(term)) return [];
|
|
142
|
+
if (term.length < FUZZY_REPAIR_MIN_LENGTH) return [];
|
|
143
|
+
if (STOPWORDS.has(term)) return [];
|
|
144
|
+
if (REAL_ENGLISH_WORDS.has(term)) return [];
|
|
145
|
+
const words = vocabulary ?? lexicon.nouns.keys();
|
|
146
|
+
const bound = fuzzyBound(term);
|
|
147
|
+
const hits = [];
|
|
148
|
+
let termIsVocabulary = false;
|
|
149
|
+
for (const candidate of words) {
|
|
150
|
+
if (candidate === term) { termIsVocabulary = true; continue; }
|
|
151
|
+
if (Math.abs(candidate.length - term.length) > bound) continue;
|
|
152
|
+
const distance = editDistance(term, candidate, bound);
|
|
153
|
+
if (distance <= bound) hits.push({ candidate, distance });
|
|
154
|
+
}
|
|
155
|
+
if (termIsVocabulary) return [];
|
|
156
|
+
hits.sort((a, b) => a.distance - b.distance || (a.candidate < b.candidate ? -1 : a.candidate > b.candidate ? 1 : 0));
|
|
157
|
+
return hits.slice(0, cap).map((hit) => hit.candidate);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** The plan a turn's retrieval executes. `terms` is sorted and deduped, an
|
|
161
|
+
* exact term always beating a fuzzy variant that spells the same word. */
|
|
162
|
+
export function buildRetrievalPlan({
|
|
163
|
+
text, fuzzy = true, hopDepth, fuzzyVariantsPerTerm, lexicon = loadLexicon(), vocabulary = null,
|
|
164
|
+
}) {
|
|
165
|
+
if (!Number.isInteger(hopDepth) || hopDepth < 0) throw new TypeError(`hopDepth must be a non-negative integer, got ${JSON.stringify(hopDepth)}`);
|
|
166
|
+
const exact = queryTerms(text, { lexicon });
|
|
167
|
+
const byTerm = new Map(exact.map((term) => [term, { term, origin: "exact", from: term }]));
|
|
168
|
+
if (fuzzy) {
|
|
169
|
+
for (const term of exact) {
|
|
170
|
+
for (const variant of fuzzyVariantsFor(term, { lexicon, vocabulary, cap: fuzzyVariantsPerTerm })) {
|
|
171
|
+
if (!byTerm.has(variant)) byTerm.set(variant, { term: variant, origin: "fuzzy", from: term });
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
const terms = [...byTerm.values()].sort((a, b) => (a.term < b.term ? -1 : a.term > b.term ? 1 : 0));
|
|
176
|
+
return Object.freeze({
|
|
177
|
+
fuzzy: Boolean(fuzzy),
|
|
178
|
+
hopDepth,
|
|
179
|
+
ancestryPredicate: ANCESTRY_PREDICATE,
|
|
180
|
+
terms: Object.freeze(terms.map((entry) => Object.freeze(entry))),
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** The triple a fact row carries, or null when the row is not a fact or its
|
|
185
|
+
* stored record cannot be read. */
|
|
186
|
+
export function factTripleOf(row) {
|
|
187
|
+
if (!row || row.rowClass !== FACT_ROW_CLASS || typeof row.json !== "string") return null;
|
|
188
|
+
let record;
|
|
189
|
+
try { record = JSON.parse(row.json); } catch { return null; }
|
|
190
|
+
const attributes = record?.individual?.attributes;
|
|
191
|
+
if (!Array.isArray(attributes)) return null;
|
|
192
|
+
const valueOf = (prop) => attributes.find((a) => a?.prop === prop)?.value || "";
|
|
193
|
+
const subject = valueOf("rdf:subject");
|
|
194
|
+
const predicate = valueOf("rdf:predicate");
|
|
195
|
+
const object = valueOf("rdf:object");
|
|
196
|
+
if (!subject || !predicate || !object) return null;
|
|
197
|
+
return { subject, predicate, object };
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** The terms one hop out from a row set: every fact's object, folded and
|
|
201
|
+
* sorted, minus anything already asked for. */
|
|
202
|
+
export function expandedTerms(rows, { seen = new Set() } = {}) {
|
|
203
|
+
const next = [];
|
|
204
|
+
for (const row of rows || []) {
|
|
205
|
+
const triple = factTripleOf(row);
|
|
206
|
+
if (!triple) continue;
|
|
207
|
+
const term = normFactTerm(triple.object);
|
|
208
|
+
if (term && !seen.has(term)) next.push(term);
|
|
209
|
+
}
|
|
210
|
+
return sortedUnique(next);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** The superclass terms a row set names, for the ancestry chase. Sorted, minus
|
|
214
|
+
* anything already asked for. */
|
|
215
|
+
export function ancestryTerms(rows, { seen = new Set() } = {}) {
|
|
216
|
+
const next = [];
|
|
217
|
+
for (const row of rows || []) {
|
|
218
|
+
const triple = factTripleOf(row);
|
|
219
|
+
if (!triple || triple.predicate !== ANCESTRY_PREDICATE) continue;
|
|
220
|
+
const term = normFactTerm(triple.object);
|
|
221
|
+
if (term && !seen.has(term)) next.push(term);
|
|
222
|
+
}
|
|
223
|
+
return sortedUnique(next);
|
|
224
|
+
}
|
|
@@ -117,6 +117,8 @@ const promptFor = (focus) => (focus ? `tmct(${shortLabel(focus.label)})> ` : PRO
|
|
|
117
117
|
* logFile, sidecarFile, bannerLines, empty, focus, lastAnswer, turns, promptFor(),
|
|
118
118
|
* turn(line), close() }. `turn(line)` runs one dispatched turn through runTurn and the
|
|
119
119
|
* full sink sequencing, returning { answer, end, prompt }; `close()` is idempotent.
|
|
120
|
+
* `turn(line, {retrieval})` passes this turn's own corpus-retrieval context,
|
|
121
|
+
* overriding the session-level `retrieval` option for that turn.
|
|
120
122
|
*/
|
|
121
123
|
export async function createSession({
|
|
122
124
|
repoPath,
|
|
@@ -150,7 +152,9 @@ export async function createSession({
|
|
|
150
152
|
// retired from routing. "memory" selects Backend B (zero disk I/O,
|
|
151
153
|
// session-scoped). This is `tmct chat --memory-backend <...>`'s
|
|
152
154
|
// already-resolved value; full precedence (this param > TMCT_MEMORY_BACKEND
|
|
153
|
-
// env > tmct.toml > the sqlite default) resolved below.
|
|
155
|
+
// env > tmct.toml > the sqlite default) resolved below. A row backend OBJECT
|
|
156
|
+
// (or a wrapRowBackend handle) selects Backend D and bypasses that
|
|
157
|
+
// precedence entirely — a caller injecting a store has already chosen.
|
|
154
158
|
memoryBackend = null,
|
|
155
159
|
// The tool-name prefix a host's own follow-up hints should use in place of
|
|
156
160
|
// "tmct_" (e.g. seonix's own tool names) — threaded onto `config` below so
|
|
@@ -166,6 +170,15 @@ export async function createSession({
|
|
|
166
170
|
// lifetime (four mud.html characters means four sessions, not one session
|
|
167
171
|
// switching identity turn to turn).
|
|
168
172
|
actingSubject,
|
|
173
|
+
// What the corpus retrieval behind this session's turns did, in
|
|
174
|
+
// retrieve-subgraph's own metrics shape ({mode, bounded, bands}). It decides
|
|
175
|
+
// the corpus-scope line an answer carries: what the query pulled in, whether
|
|
176
|
+
// a budget cut it short, or that the supplement was absent altogether. A
|
|
177
|
+
// caller that retrieves per turn passes its own context to `turn(line,
|
|
178
|
+
// {retrieval})` instead, which wins over this one. Omitted (the default)
|
|
179
|
+
// means no corpus behind this session, and every answer is byte-identical to
|
|
180
|
+
// a run without the seam.
|
|
181
|
+
retrieval = null,
|
|
169
182
|
// The session-log filesystem seam: mkdir/createWriteStream, injectable so a
|
|
170
183
|
// test can exercise the unwritable-log guard by rejecting at the seam
|
|
171
184
|
// itself rather than by making a real directory unwritable — chmod-based
|
|
@@ -411,14 +424,23 @@ export async function createSession({
|
|
|
411
424
|
};
|
|
412
425
|
|
|
413
426
|
// `memoryDir` is the opaque token every memory/core.mjs call in this file
|
|
414
|
-
// threads through unchanged — always a Backend B/C handle from
|
|
427
|
+
// threads through unchanged — always a Backend B/C/D handle from
|
|
415
428
|
// openMemoryBackend now that the flat-file Backend A is retired from
|
|
416
429
|
// routing. Precedence — CLI flag > env > tmct.toml > the sqlite default.
|
|
417
|
-
|
|
430
|
+
//
|
|
431
|
+
// A caller can also INJECT its own row store as `memoryBackend`: a backend
|
|
432
|
+
// object, or a handle wrapRowBackend already produced (which is how a seed
|
|
433
|
+
// overlay arrives). That object goes to openMemoryBackend as-is — config
|
|
434
|
+
// resolution never sees it, and it must be tested before the String()
|
|
435
|
+
// coercion below or it stringifies into a meaningless token.
|
|
436
|
+
const { openMemoryBackend, isRowBackend, isRowHandle } = await import("../adapters/memory/core.mjs");
|
|
437
|
+
const injectedRowStore = isRowBackend(memoryBackend) || isRowHandle(memoryBackend);
|
|
438
|
+
const backendChoice = injectedRowStore
|
|
439
|
+
? memoryBackend
|
|
440
|
+
: String(memoryBackend || env.TMCT_MEMORY_BACKEND || toml?.memory?.backend || "").trim().toLowerCase();
|
|
418
441
|
// openMemoryBackend is the ONE shared resolver for this seam — init.mjs's
|
|
419
442
|
// corpus seed calls the exact same function, so a repo's seeded facts and
|
|
420
443
|
// its chat-taught facts always land in the same backend.
|
|
421
|
-
const { openMemoryBackend } = await import("../adapters/memory/core.mjs");
|
|
422
444
|
const { dir: memoryDir, close: closeMemoryStore } = await openMemoryBackend(repo, backendChoice);
|
|
423
445
|
|
|
424
446
|
const empty = graph.individuals.length === 0;
|
|
@@ -430,8 +452,9 @@ export async function createSession({
|
|
|
430
452
|
//
|
|
431
453
|
// Known residual split: seedBootstrapMemory/hasSeededVocabulary resolve
|
|
432
454
|
// their marker file off the STRING `repo` path (correct — the marker is a
|
|
433
|
-
// file, not store content), so W3 seeding
|
|
434
|
-
//
|
|
455
|
+
// file, not store content), so W3 seeding only fires on the default token —
|
|
456
|
+
// an injected row store carries whatever seed its owner bundled and never
|
|
457
|
+
// gets one written into it here. And sessions.mjs's per-turn utterance mirror still writes an
|
|
435
458
|
// ordinary .tmct/memory/graph.json off the repo string — a file no routed
|
|
436
459
|
// reader opens now that Backend A is retired from routing. Taught FACTS
|
|
437
460
|
// themselves are unaffected: only the conversational transcript mirror
|
|
@@ -455,10 +478,14 @@ export async function createSession({
|
|
|
455
478
|
// A discarding session must not say the conversation is kept. Ephemeral
|
|
456
479
|
// diverts every write to a temp dir and suppresses the graph upsert; the
|
|
457
480
|
// "memory" backend keeps the store in-process. Both end when the process does.
|
|
481
|
+
// An injected row store is durable but not tmct's file, so it gets its own
|
|
482
|
+
// line rather than a path this session never writes.
|
|
458
483
|
const discardsWrites = ephemeral || backendChoice === "memory";
|
|
459
484
|
const whereItGoes = discardsWrites
|
|
460
485
|
? "nothing is written back — this session's facts and log are dropped when it ends"
|
|
461
|
-
:
|
|
486
|
+
: injectedRowStore
|
|
487
|
+
? `the conversation is kept in your configured store — log ${logFile}`
|
|
488
|
+
: `the conversation is remembered to ${DEFAULT_GRAPH_REL} — log ${logFile}`;
|
|
462
489
|
const bannerLines = [
|
|
463
490
|
noCodeGraph
|
|
464
491
|
// No code graph: honest, orienting messaging — never an error before the prompt.
|
|
@@ -537,10 +564,10 @@ export async function createSession({
|
|
|
537
564
|
* (empty when the turn wrote nothing). A throwing runTurn must never abort
|
|
538
565
|
* the session: a piped/non-interactive driver has no other chance to see
|
|
539
566
|
* this turn's answer. */
|
|
540
|
-
async turn(line) {
|
|
567
|
+
async turn(line, { retrieval: turnRetrieval = null } = {}) {
|
|
541
568
|
let result;
|
|
542
569
|
try {
|
|
543
|
-
result = await runTurn(line, { config, source, graph, focus, last, memoryDir, sessionId, env, lexicon, narrate: narrateOn, liveReference: liveReferenceOn, researchSource: researchSourceOn, vocabHint, tel, biasByBundle, planState, gameConfig, recognitionConfig, researchState, researchConfig, newsState, newsConfig, newsProviders, discourse: discourseRecord, actingSubject, codeDomainActive: domainActive, laneVocab, domainPacks });
|
|
570
|
+
result = await runTurn(line, { config, source, graph, focus, last, memoryDir, sessionId, env, lexicon, narrate: narrateOn, liveReference: liveReferenceOn, researchSource: researchSourceOn, vocabHint, tel, biasByBundle, planState, gameConfig, recognitionConfig, researchState, researchConfig, newsState, newsConfig, newsProviders, discourse: discourseRecord, actingSubject, codeDomainActive: domainActive, laneVocab, domainPacks, retrieval: turnRetrieval ?? retrieval });
|
|
544
571
|
} catch (e) {
|
|
545
572
|
const ts = new Date().toISOString();
|
|
546
573
|
const message = e instanceof Error ? e.message : String(e);
|