@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.
@@ -44,6 +44,7 @@ export const FACT_PREDICATE_PHRASES = Object.freeze({
44
44
  "mgx:hasPrerequisite": "requires",
45
45
  "mgx:ownedBy": "is owned by", // the teach lane's ownership frame ("Priya owns tasks.mjs")
46
46
  "mgx:rendersAs": "renders as", // the render-template binding ("a disk renders as a block")
47
+ "mgx:nameFor": "is the name for", // the definitional frame's edge ("latency is the name for time period")
47
48
  "mgx:synonym": "means the same as",
48
49
  "mgx:antonym": "is the opposite of",
49
50
  "mgx:similarTo": "is similar to",
@@ -174,6 +175,45 @@ export function factSentence(row) {
174
175
  return `${row.subject} ${predicatePhrase(row.predicate)} ${row.object}`;
175
176
  }
176
177
 
178
+ /**
179
+ * The short curated caveat each KEPT extraction finding reads as beside a
180
+ * citation. One template per finding, byte-pinned, so an answer that leans on a
181
+ * row the extractor had something to say about says so in the same words every
182
+ * time.
183
+ *
184
+ * `definitional-frame` is deliberately absent: its own phrase ("is the name
185
+ * for") already says how the row was read, so a caveat would repeat it. So are
186
+ * the decline reasons — a declined candidate was never stored, so no answer can
187
+ * lean on it.
188
+ */
189
+ export const FINDING_CAVEATS = Object.freeze({
190
+ "clause-fallback": "(read from a clause fragment)",
191
+ "pronoun-carry": "(subject carried from the previous sentence)",
192
+ "identifier-token": "(identifier token)",
193
+ });
194
+
195
+ /**
196
+ * The caveat text for one fact row's findings, or "" when it has none to
197
+ * declare. Takes a row ({ extraction: [...] }, readFactRows' shape), a bare
198
+ * finding name, or a list of them, so a renderer can pass whatever it holds.
199
+ *
200
+ * A row carrying several findings reads them in the table's own order above,
201
+ * never the row's, so the same finding set always renders the same string.
202
+ * Returns the caveats alone — the caller owns the space before them and the
203
+ * citation after.
204
+ */
205
+ export function findingCaveat(finding) {
206
+ const named = typeof finding === "string"
207
+ ? [finding]
208
+ : Array.isArray(finding) ? finding : finding?.extraction;
209
+ if (!Array.isArray(named) || !named.length) return "";
210
+ const held = new Set(named.map((f) => String(f)));
211
+ return Object.entries(FINDING_CAVEATS)
212
+ .filter(([name]) => held.has(name))
213
+ .map(([, caveat]) => caveat)
214
+ .join(" ");
215
+ }
216
+
177
217
  /** The phrase layer as browser source, for a generated page that renders fact
178
218
  * rows in its own inline script. The page supplies FACT_PREDICATE_PHRASES
179
219
  * (it embeds the table as JSON) and this supplies everything the reader
@@ -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,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
+ }
@@ -150,7 +150,9 @@ export async function createSession({
150
150
  // retired from routing. "memory" selects Backend B (zero disk I/O,
151
151
  // session-scoped). This is `tmct chat --memory-backend <...>`'s
152
152
  // already-resolved value; full precedence (this param > TMCT_MEMORY_BACKEND
153
- // env > tmct.toml > the sqlite default) resolved below.
153
+ // env > tmct.toml > the sqlite default) resolved below. A row backend OBJECT
154
+ // (or a wrapRowBackend handle) selects Backend D and bypasses that
155
+ // precedence entirely — a caller injecting a store has already chosen.
154
156
  memoryBackend = null,
155
157
  // The tool-name prefix a host's own follow-up hints should use in place of
156
158
  // "tmct_" (e.g. seonix's own tool names) — threaded onto `config` below so
@@ -411,14 +413,23 @@ export async function createSession({
411
413
  };
412
414
 
413
415
  // `memoryDir` is the opaque token every memory/core.mjs call in this file
414
- // threads through unchanged — always a Backend B/C handle from
416
+ // threads through unchanged — always a Backend B/C/D handle from
415
417
  // openMemoryBackend now that the flat-file Backend A is retired from
416
418
  // routing. Precedence — CLI flag > env > tmct.toml > the sqlite default.
417
- const backendChoice = String(memoryBackend || env.TMCT_MEMORY_BACKEND || toml?.memory?.backend || "").trim().toLowerCase();
419
+ //
420
+ // A caller can also INJECT its own row store as `memoryBackend`: a backend
421
+ // object, or a handle wrapRowBackend already produced (which is how a seed
422
+ // overlay arrives). That object goes to openMemoryBackend as-is — config
423
+ // resolution never sees it, and it must be tested before the String()
424
+ // coercion below or it stringifies into a meaningless token.
425
+ const { openMemoryBackend, isRowBackend, isRowHandle } = await import("../adapters/memory/core.mjs");
426
+ const injectedRowStore = isRowBackend(memoryBackend) || isRowHandle(memoryBackend);
427
+ const backendChoice = injectedRowStore
428
+ ? memoryBackend
429
+ : String(memoryBackend || env.TMCT_MEMORY_BACKEND || toml?.memory?.backend || "").trim().toLowerCase();
418
430
  // openMemoryBackend is the ONE shared resolver for this seam — init.mjs's
419
431
  // corpus seed calls the exact same function, so a repo's seeded facts and
420
432
  // its chat-taught facts always land in the same backend.
421
- const { openMemoryBackend } = await import("../adapters/memory/core.mjs");
422
433
  const { dir: memoryDir, close: closeMemoryStore } = await openMemoryBackend(repo, backendChoice);
423
434
 
424
435
  const empty = graph.individuals.length === 0;
@@ -430,8 +441,9 @@ export async function createSession({
430
441
  //
431
442
  // Known residual split: seedBootstrapMemory/hasSeededVocabulary resolve
432
443
  // their marker file off the STRING `repo` path (correct — the marker is a
433
- // file, not store content), so W3 seeding still only fires on the default
434
- // token. And sessions.mjs's per-turn utterance mirror still writes an
444
+ // file, not store content), so W3 seeding only fires on the default token —
445
+ // an injected row store carries whatever seed its owner bundled and never
446
+ // gets one written into it here. And sessions.mjs's per-turn utterance mirror still writes an
435
447
  // ordinary .tmct/memory/graph.json off the repo string — a file no routed
436
448
  // reader opens now that Backend A is retired from routing. Taught FACTS
437
449
  // themselves are unaffected: only the conversational transcript mirror
@@ -455,10 +467,14 @@ export async function createSession({
455
467
  // A discarding session must not say the conversation is kept. Ephemeral
456
468
  // diverts every write to a temp dir and suppresses the graph upsert; the
457
469
  // "memory" backend keeps the store in-process. Both end when the process does.
470
+ // An injected row store is durable but not tmct's file, so it gets its own
471
+ // line rather than a path this session never writes.
458
472
  const discardsWrites = ephemeral || backendChoice === "memory";
459
473
  const whereItGoes = discardsWrites
460
474
  ? "nothing is written back — this session's facts and log are dropped when it ends"
461
- : `the conversation is remembered to ${DEFAULT_GRAPH_REL} — log ${logFile}`;
475
+ : injectedRowStore
476
+ ? `the conversation is kept in your configured store — log ${logFile}`
477
+ : `the conversation is remembered to ${DEFAULT_GRAPH_REL} — log ${logFile}`;
462
478
  const bannerLines = [
463
479
  noCodeGraph
464
480
  // No code graph: honest, orienting messaging — never an error before the prompt.