@polycode-projects/the-mechanical-code-talker 5.0.45 → 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.
- package/bin/tmct.mjs +11 -10
- package/package.json +15 -2
- package/src/adapters/corpus/research-source.mjs +4 -2
- package/src/adapters/corpus/simple-wikipedia-pack.mjs +138 -0
- package/src/adapters/memory/backends-exports.mjs +8 -0
- package/src/adapters/memory/core.mjs +291 -30
- 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/research-queue-store.mjs +215 -32
- package/src/domain/cli-verbs.mjs +2 -2
- package/src/domain/fact-phrase.mjs +170 -13
- package/src/domain/memory/capability.mjs +1 -1
- package/src/domain/phrase-exports.mjs +33 -0
- package/src/domain/reference-pack.mjs +46 -0
- package/src/domain/retrieval-plan.mjs +224 -0
- package/src/services/chat-session.mjs +23 -7
- package/src/services/chat.mjs +49 -98
- package/src/services/extract-facts.mjs +244 -33
- package/src/services/index.mjs +2 -0
- package/src/services/init.mjs +17 -6
- package/src/services/news-viz.mjs +2 -3
- package/src/services/news.mjs +4 -2
- package/src/services/subgraph-retrieval.mjs +361 -0
- package/src/surfaces/web/memory-ask-browser.bundle.js +127 -126
- 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
|
@@ -1,12 +1,15 @@
|
|
|
1
|
-
// fact-phrase.mjs — the one predicate -> English-phrase table
|
|
2
|
-
// news paraphrase renderer
|
|
3
|
-
//
|
|
4
|
-
//
|
|
1
|
+
// fact-phrase.mjs — the one predicate -> English-phrase table AND the one
|
|
2
|
+
// reader over it. The news paraphrase renderer, the news page's own inline
|
|
3
|
+
// script and chat.mjs's answer path all render a stored fact through the
|
|
4
|
+
// functions below, so no two surfaces can disagree about what a predicate
|
|
5
|
+
// says in English.
|
|
5
6
|
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
8
|
-
//
|
|
9
|
-
//
|
|
7
|
+
// The reader is layered: a curated table hit first, then the mechanical
|
|
8
|
+
// surface forms for the predicates tmct MINTS at teach time (polarity flips,
|
|
9
|
+
// comparatives, participle + preposition, "same <attribute> as", and the
|
|
10
|
+
// "mgx:<lemma>[-<prep>]" verb fold), and last the predicate's bare local
|
|
11
|
+
// name. Every layer is mechanical — a phrase is derived from the predicate or
|
|
12
|
+
// it is the predicate's own local name. Nothing here guesses.
|
|
10
13
|
|
|
11
14
|
export const FACT_PREDICATE_PHRASES = Object.freeze({
|
|
12
15
|
"rdfs:subClassOf": "is a kind of",
|
|
@@ -41,6 +44,7 @@ export const FACT_PREDICATE_PHRASES = Object.freeze({
|
|
|
41
44
|
"mgx:hasPrerequisite": "requires",
|
|
42
45
|
"mgx:ownedBy": "is owned by", // the teach lane's ownership frame ("Priya owns tasks.mjs")
|
|
43
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")
|
|
44
48
|
"mgx:synonym": "means the same as",
|
|
45
49
|
"mgx:antonym": "is the opposite of",
|
|
46
50
|
"mgx:similarTo": "is similar to",
|
|
@@ -58,16 +62,169 @@ export const FACT_PREDICATE_PHRASES = Object.freeze({
|
|
|
58
62
|
"mgx:guards": "guards",
|
|
59
63
|
});
|
|
60
64
|
|
|
61
|
-
/**
|
|
62
|
-
*
|
|
65
|
+
/** The closed participle set the relational teach frames read as "X is
|
|
66
|
+
* <participle> <prep> Y" — a past participle whose own form is the word, so it
|
|
67
|
+
* reads back with no morphology. Closed by list (templates over general
|
|
68
|
+
* grammar), so the frame can never widen onto an arbitrary "-ed" adjective.
|
|
69
|
+
* The teach parser mints predicates from this list and the reader below turns
|
|
70
|
+
* them back into English, so both read the one vocabulary. */
|
|
71
|
+
export const TEACH_PARTICIPLE_SRC = "connected|related|associated|linked|based|derived|composed|made|used|known|located|found|involved|concerned";
|
|
72
|
+
|
|
73
|
+
/** The MECHANICAL fallback for a predicate the table has no curated entry
|
|
74
|
+
* for — specifically the minted "mgx:<lemma>" predicates ("mgx:eat",
|
|
75
|
+
* "mgx:drive", …) — the mechanical INVERSE of the naive -s/-es/-ies fold the
|
|
76
|
+
* teach lane's own singularizer uses, same accepted-limitation trade (no real
|
|
77
|
+
* morphology; a handful of doubly-irregular verbs render slightly off but
|
|
78
|
+
* never wrong-MEANING). "has"/"have" never reach this fallback — the teach
|
|
79
|
+
* lane special-cases them onto the CURATED mgx:hasA entry above before a
|
|
80
|
+
* predicate is ever minted. */
|
|
81
|
+
export function thirdPersonSingularSurface(lemma) {
|
|
82
|
+
const w = String(lemma || "");
|
|
83
|
+
// "have" should never reach this naive fallback at all (the teach lane
|
|
84
|
+
// special-cases it onto mgx:hasA before a predicate is ever minted), but if
|
|
85
|
+
// some OTHER path ever reaches here with it as typed — e.g. wink-nlp
|
|
86
|
+
// unavailable so the lemma degrades to the raw verb — the naive "+s" rule
|
|
87
|
+
// would produce the wrong-MEANING "haves" instead of the correct "has".
|
|
88
|
+
if (/^have$/i.test(w)) return "has";
|
|
89
|
+
if (/[a-z]y$/i.test(w) && !/[aeiou]y$/i.test(w)) return `${w.slice(0, -1)}ies`;
|
|
90
|
+
if (/(?:s|x|z|ch|sh|o)$/i.test(w)) return `${w}es`;
|
|
91
|
+
return `${w}s`;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** The INVERSE of thirdPersonSingularSurface — "eats" -> "eat", "flies" ->
|
|
95
|
+
* "fly", "has" -> "have". Do-support wants the bare infinitive after it
|
|
96
|
+
* ("does not EAT", never "does not eats"), and so does every derived
|
|
97
|
+
* forward yes/no reader ("does X cause Y"), so both fold through this one
|
|
98
|
+
* function and can never drift apart on a verb. */
|
|
99
|
+
export function baseVerbSurface(verb) {
|
|
100
|
+
const w = String(verb || "");
|
|
101
|
+
if (/^has$/i.test(w)) return "have";
|
|
102
|
+
if (/[a-z]ies$/i.test(w) && !/[aeiou]ies$/i.test(w)) return `${w.slice(0, -3)}y`;
|
|
103
|
+
if (/(?:ss|zz|x|ch|sh|o)es$/i.test(w)) return w.slice(0, -2);
|
|
104
|
+
// A SINGLE s or z before "es" means the base already ended in "e" and took a
|
|
105
|
+
// plain "s": cause/use/raise/size, not caus/us/rais/siz. Only the doubled
|
|
106
|
+
// sibilants above ("passes", "buzzes") really carry an "-es" ending.
|
|
107
|
+
if (/[sz]es$/i.test(w)) return w.slice(0, -1);
|
|
108
|
+
return w.replace(/s$/i, "");
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** The gerund surface of a 3sg-minted role predicate — "contains" ->
|
|
112
|
+
* "containing", "touches" -> "touching" — the naive INVERSE of the
|
|
113
|
+
* "-ing"-stripping fold the ACE parser already accepts alongside a 3sg
|
|
114
|
+
* surface. Same accepted naive-morphology trade as its two siblings above. */
|
|
115
|
+
export function gerundVerbSurface(verb) {
|
|
116
|
+
const base = baseVerbSurface(verb);
|
|
117
|
+
return /[^aeiou]e$/i.test(base) && base.length > 2 ? `${base.slice(0, -1)}ing` : `${base}ing`;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* How a stored predicate reads in English: a curated table hit, else the
|
|
122
|
+
* mechanical surface form of a minted predicate, else the predicate's local
|
|
123
|
+
* name (the segment after its first colon, or the whole string when there is
|
|
124
|
+
* none). The local-name tail is what keeps a namespace tmct itself mints —
|
|
125
|
+
* `tmct:needs`, stamped by the lexicon — out of a public-facing sentence.
|
|
126
|
+
*
|
|
127
|
+
* Self-contained on purpose: the news page runs this exact function in the
|
|
128
|
+
* browser (phraseRendererSource below stringifies it and its two helpers), so
|
|
129
|
+
* it reaches for nothing outside this module.
|
|
130
|
+
*/
|
|
63
131
|
export function predicatePhrase(predicate) {
|
|
64
132
|
if (FACT_PREDICATE_PHRASES[predicate]) return FACT_PREDICATE_PHRASES[predicate];
|
|
65
|
-
const
|
|
66
|
-
|
|
67
|
-
|
|
133
|
+
const p = String(predicate ?? "");
|
|
134
|
+
// NEGATIVE polarity renders as its own positive phrase, negated — ONE branch
|
|
135
|
+
// for every predicate that can carry a polarity, curated or minted. The
|
|
136
|
+
// negative twins are deliberately absent from FACT_PREDICATE_PHRASES: chat's
|
|
137
|
+
// query-marker families all derive their vocabulary from that table, so an
|
|
138
|
+
// entry there would auto-mint readers for "what cannot X" and "does X cannot
|
|
139
|
+
// Y" that nobody wrote and nothing pins. The prefix swap is the whole rule
|
|
140
|
+
// here because the one polarity pair that ISN'T a prefix swap
|
|
141
|
+
// (mgxneg:subClassOf / rdfs:subClassOf) carries its own curated entry above
|
|
142
|
+
// and returns before this branch.
|
|
143
|
+
// The three surface shapes split as the forward yes/no readers split them,
|
|
144
|
+
// for the same reason: a modal, a copula and a plain verb take different
|
|
145
|
+
// negations, and nothing else does.
|
|
146
|
+
if (p.startsWith("mgxneg:")) {
|
|
147
|
+
const phrase = predicatePhrase(`mgx:${p.slice("mgxneg:".length)}`);
|
|
148
|
+
if (phrase === "can") return "cannot";
|
|
149
|
+
if (phrase === "can be") return "cannot be";
|
|
150
|
+
if (phrase === "is" || phrase.startsWith("is ")) return `is not${phrase.slice(2)}`;
|
|
151
|
+
const [head, ...tail] = phrase.split(" ");
|
|
152
|
+
return ["does not", baseVerbSurface(head), ...tail].join(" ");
|
|
153
|
+
}
|
|
154
|
+
// a comparative renders as its copula surface: mgx:smaller-than ->
|
|
155
|
+
// "is smaller than" (never a 3sg fold — "smallers" isn't a word)
|
|
156
|
+
const comp = /^mgx:([a-z]+(?:-[a-z]+)*)-than$/i.exec(p);
|
|
157
|
+
if (comp) return `is ${comp[1].replace(/-/g, " ")} than`;
|
|
158
|
+
// a participle + preposition renders as its copula surface: mgx:connected-with
|
|
159
|
+
// -> "is connected with" (the participle is already a participle, so no 3sg
|
|
160
|
+
// fold — "connecteds" isn't a word)
|
|
161
|
+
const part = new RegExp(`^mgx:(${TEACH_PARTICIPLE_SRC})-([a-z]+)$`, "i").exec(p);
|
|
162
|
+
if (part) return `is ${part[1].toLowerCase()} ${part[2].toLowerCase()}`;
|
|
163
|
+
// a shared-attribute predicate: mgx:same-goal-as -> "has the same goal as"
|
|
164
|
+
const same = /^mgx:same-([a-z]+)-as$/i.exec(p);
|
|
165
|
+
if (same) return `has the same ${same[1].toLowerCase()} as`;
|
|
166
|
+
// a folded preposition renders back naturally: mgx:rest-on -> "rests on"
|
|
167
|
+
const minted = /^mgx:([a-z]+)(?:-([a-z]+))?$/i.exec(p);
|
|
168
|
+
if (minted) return `${thirdPersonSingularSurface(minted[1])}${minted[2] ? ` ${minted[2]}` : ""}`;
|
|
169
|
+
const colon = p.indexOf(":");
|
|
170
|
+
return colon === -1 ? p : p.slice(colon + 1);
|
|
68
171
|
}
|
|
69
172
|
|
|
70
173
|
/** "a heart has a valve" from one { subject, predicate, object } fact row. */
|
|
71
174
|
export function factSentence(row) {
|
|
72
175
|
return `${row.subject} ${predicatePhrase(row.predicate)} ${row.object}`;
|
|
73
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
|
+
|
|
217
|
+
/** The phrase layer as browser source, for a generated page that renders fact
|
|
218
|
+
* rows in its own inline script. The page supplies FACT_PREDICATE_PHRASES
|
|
219
|
+
* (it embeds the table as JSON) and this supplies everything the reader
|
|
220
|
+
* above stands on, so a new branch here reaches the page without the page
|
|
221
|
+
* being edited. */
|
|
222
|
+
export function phraseRendererSource() {
|
|
223
|
+
return [
|
|
224
|
+
`const TEACH_PARTICIPLE_SRC = ${JSON.stringify(TEACH_PARTICIPLE_SRC)};`,
|
|
225
|
+
`const thirdPersonSingularSurface = ${thirdPersonSingularSurface};`,
|
|
226
|
+
`const baseVerbSurface = ${baseVerbSurface};`,
|
|
227
|
+
`const predicatePhrase = ${predicatePhrase};`,
|
|
228
|
+
`const factSentence = ${factSentence};`,
|
|
229
|
+
].join("\n ");
|
|
230
|
+
}
|
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
import { findIsaChain, buildSubClassSuccessors, SUBCLASS_PREDICATE, TYPE_PREDICATE } from "../syllogise.mjs";
|
|
22
22
|
|
|
23
23
|
/** The negative-polarity CURIE prefix. A separate prefix, never an
|
|
24
|
-
* "mgx:not-<lemma>" mint:
|
|
24
|
+
* "mgx:not-<lemma>" mint: fact-phrase.mjs's predicatePhrase reads "mgx:not-fly" as
|
|
25
25
|
* lemma "not" plus tail "fly" and renders "nots fly", and its preposition fold
|
|
26
26
|
* is guarded on /^mgx:[a-z]+$/, which a hyphenated mint fails — so
|
|
27
27
|
* "a penguin cannot rest on water" would strand "on water" inside the object
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// phrase-exports.mjs — the package's `./phrase` export subpath: how tmct
|
|
2
|
+
// renders a stored fact and its provenance, reachable without pulling in the
|
|
3
|
+
// chat engine the "." entry carries. An embedding host that shows tmct's own
|
|
4
|
+
// answers back to its users renders the same rows the same way tmct does,
|
|
5
|
+
// rather than re-deriving English from raw CURIEs.
|
|
6
|
+
//
|
|
7
|
+
// Everything here is pure and synchronous: no graph, no store, no I/O.
|
|
8
|
+
|
|
9
|
+
// The predicate -> English reader the answer path itself uses, plus the table
|
|
10
|
+
// behind it and the verb-surface folds it stands on.
|
|
11
|
+
export {
|
|
12
|
+
FACT_PREDICATE_PHRASES,
|
|
13
|
+
predicatePhrase,
|
|
14
|
+
factSentence,
|
|
15
|
+
thirdPersonSingularSurface,
|
|
16
|
+
baseVerbSurface,
|
|
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,
|
|
22
|
+
} from "./fact-phrase.mjs";
|
|
23
|
+
|
|
24
|
+
// Provenance: the `reference:<pack>:<Title>@<revid>` tag a reference-grounded
|
|
25
|
+
// fact carries, turned back into the revision-pinned article link tmct cites.
|
|
26
|
+
export {
|
|
27
|
+
referenceTagToUrl,
|
|
28
|
+
articleUrlFor,
|
|
29
|
+
REFERENCE_PACK_NAME,
|
|
30
|
+
REFERENCE_PACK_ORIGIN,
|
|
31
|
+
LIVE_PACK_NAME,
|
|
32
|
+
LIVE_PACK_ORIGIN,
|
|
33
|
+
} from "./reference-pack.mjs";
|
|
@@ -87,6 +87,16 @@ export function referenceProvenanceTag(article) {
|
|
|
87
87
|
return `reference:${REFERENCE_PACK_NAME}:${article.title}@${article.revid}`;
|
|
88
88
|
}
|
|
89
89
|
|
|
90
|
+
/** Wikimedia titles are underscored and percent-encoded in a wiki URL. The
|
|
91
|
+
* build script (scripts/fetch-reference-pack.mjs) stamps every shipped row's
|
|
92
|
+
* `url` with this, and referenceTagToUrl below rebuilds the same link from a
|
|
93
|
+
* stored fact's provenance tag. */
|
|
94
|
+
export const REFERENCE_PACK_ORIGIN = "https://simple.wikipedia.org";
|
|
95
|
+
|
|
96
|
+
export function articleUrlFor(origin, title) {
|
|
97
|
+
return `${origin}/wiki/${encodeURIComponent(String(title).replace(/ /g, "_"))}`;
|
|
98
|
+
}
|
|
99
|
+
|
|
90
100
|
/** The pure half of the clean-miss gate: is this term even a pack-lookup
|
|
91
101
|
* candidate, and under which key? Returns the pack key (the lexicon entry's
|
|
92
102
|
* lemma, normFactTerm-folded) or null when the term is empty, not plain
|
|
@@ -115,6 +125,42 @@ export function liveProvenanceTag(article) {
|
|
|
115
125
|
return `reference:${LIVE_PACK_NAME}:${article.title}@${article.revid}`;
|
|
116
126
|
}
|
|
117
127
|
|
|
128
|
+
export const LIVE_PACK_ORIGIN = "https://en.wikipedia.org";
|
|
129
|
+
const ORIGIN_BY_PACK = new Map([
|
|
130
|
+
[REFERENCE_PACK_NAME, REFERENCE_PACK_ORIGIN],
|
|
131
|
+
[LIVE_PACK_NAME, LIVE_PACK_ORIGIN],
|
|
132
|
+
]);
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* The revision-pinned article a `reference:<pack>:<Title>@<revid>` provenance
|
|
136
|
+
* tag names: `{ pack, title, revid, url }`, or null. Null covers every tag
|
|
137
|
+
* this cannot place — a tag from another source kind, a pack with no known
|
|
138
|
+
* origin, a missing or non-numeric revision — because a consumer showing
|
|
139
|
+
* provenance needs a link it can follow or nothing at all, never one assembled
|
|
140
|
+
* out of a guess about where the article might live.
|
|
141
|
+
*
|
|
142
|
+
* The `?oldid=` query pins the revision the fact was read from, exactly as
|
|
143
|
+
* renderReferenceAnswer cites it in chat.
|
|
144
|
+
*/
|
|
145
|
+
export function referenceTagToUrl(tag) {
|
|
146
|
+
const t = String(tag ?? "").trim();
|
|
147
|
+
if (!t.startsWith("reference:")) return null;
|
|
148
|
+
const rest = t.slice("reference:".length);
|
|
149
|
+
const colon = rest.indexOf(":");
|
|
150
|
+
if (colon < 0) return null;
|
|
151
|
+
const origin = ORIGIN_BY_PACK.get(rest.slice(0, colon));
|
|
152
|
+
if (!origin) return null;
|
|
153
|
+
// The article segment keeps its spaces and may contain "@" itself, so the
|
|
154
|
+
// revision splits off the LAST one and only counts when it is all digits.
|
|
155
|
+
const article = rest.slice(colon + 1);
|
|
156
|
+
const at = article.lastIndexOf("@");
|
|
157
|
+
if (at < 1) return null;
|
|
158
|
+
const revid = article.slice(at + 1);
|
|
159
|
+
if (!/^\d+$/.test(revid)) return null;
|
|
160
|
+
const title = article.slice(0, at);
|
|
161
|
+
return { pack: rest.slice(0, colon), title, revid, url: `${articleUrlFor(origin, title)}?oldid=${revid}` };
|
|
162
|
+
}
|
|
163
|
+
|
|
118
164
|
/** The cited answer for a clean miss the live lookup could ground: the
|
|
119
165
|
* article's summary with its title, the LIVE source named, the licence and
|
|
120
166
|
* the revision-pinned URL always visible. */
|
|
@@ -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
|
-
|
|
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
|
|
434
|
-
//
|
|
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
|
-
:
|
|
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.
|