@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/services/chat.mjs
CHANGED
|
@@ -80,6 +80,7 @@ import { splitChoiceQuestion, routeChoiceRelation, lemmaFoldVariants, headNounOf
|
|
|
80
80
|
import { subClassParents, subClassChildren, descendantSet, ancestryChain, clusterSenses } from "../domain/sense-split.mjs";
|
|
81
81
|
import { ANSWER_STOP_SET } from "../domain/hub-terms.mjs";
|
|
82
82
|
import { relatedForTerm } from "../domain/skos-view.mjs";
|
|
83
|
+
import { ENUMERATION_LANES, answerAssertsASet, retrievalMarkerLine } from "../domain/retrieval-marker.mjs";
|
|
83
84
|
import { adventureTurn, unclaimedAdventureOpening, foldWorldState } from "./adventure.mjs";
|
|
84
85
|
import { spiderFlyTurn } from "./spider-fly-turn.mjs";
|
|
85
86
|
import { mudiiiTurn } from "./mudiii-turn.mjs";
|
|
@@ -364,6 +365,25 @@ function withCanonicalLine(result) {
|
|
|
364
365
|
return { ...result, answer, logLines };
|
|
365
366
|
}
|
|
366
367
|
|
|
368
|
+
/** The corpus-scope line, on the same append-onto-`answer` mechanism as
|
|
369
|
+
* withGoalLine. A turn dispatched with no retrieval context gets nothing —
|
|
370
|
+
* the local shell, the browser page and every existing caller pass none, so
|
|
371
|
+
* their answers are byte-identical to a run without this seam.
|
|
372
|
+
*
|
|
373
|
+
* Applied FIRST in the trailer chain, so the goal and canonical lines stay at
|
|
374
|
+
* the end of the answer where the suites that strip them anchor. The scope
|
|
375
|
+
* line belongs against the answer body anyway: it says what the answer was
|
|
376
|
+
* read from, where the other two describe the turn. */
|
|
377
|
+
function withRetrievalNote(result, retrieval) {
|
|
378
|
+
const line = retrievalMarkerLine(retrieval, { enumerationLane: result?.record?.enumerationLane ?? null });
|
|
379
|
+
if (!line) return result;
|
|
380
|
+
const answer = `${result.answer}\n\n${line}`;
|
|
381
|
+
const logLines = Array.isArray(result.logLines)
|
|
382
|
+
? result.logLines.map((l) => (l === result.answer ? answer : l))
|
|
383
|
+
: result.logLines;
|
|
384
|
+
return { ...result, answer, logLines };
|
|
385
|
+
}
|
|
386
|
+
|
|
367
387
|
/** Slash-command → (dispatchTool name, arg key). Arg keys are the EXACT ones the
|
|
368
388
|
* server.mjs dispatchTool switch reads (members/subclasses take `class`;
|
|
369
389
|
* impact/exports take `module`; architecture takes `package`; search takes
|
|
@@ -9253,7 +9273,23 @@ function uniqueFacts(rows) {
|
|
|
9253
9273
|
* it as its own "Goal (inferred)" line; every other consumer reads named
|
|
9254
9274
|
* fields and is unaffected. */
|
|
9255
9275
|
export async function factAnswer(memoryDir, query, envelope, miss, biasByBundle = {}, cache = null, focusLabel = null) {
|
|
9256
|
-
return
|
|
9276
|
+
return withEnumerationLane(
|
|
9277
|
+
withDeducedGoal(await factAnswerReaders(memoryDir, query, envelope, miss, biasByBundle, cache, focusLabel), envelope, query),
|
|
9278
|
+
ENUMERATION_LANES.FACT_SET,
|
|
9279
|
+
);
|
|
9280
|
+
}
|
|
9281
|
+
|
|
9282
|
+
/** Stamp the enumeration lane on a fact reader's return when its answer reports
|
|
9283
|
+
* a set's extent, so the corpus-scope trailer can find it.
|
|
9284
|
+
*
|
|
9285
|
+
* Both cascades below render their hits the same way — a capped list of fact
|
|
9286
|
+
* lines plus a held remainder — across twenty-odd return sites. Deciding here,
|
|
9287
|
+
* from the rendered answer, rather than tagging each site keeps one rule in
|
|
9288
|
+
* one place, and covers a reader added to either cascade later. */
|
|
9289
|
+
function withEnumerationLane(res, lane) {
|
|
9290
|
+
if (!res || res.miss || typeof res.text !== "string") return res;
|
|
9291
|
+
if (!answerAssertsASet(res.text, res)) return res;
|
|
9292
|
+
return { ...res, enumerationLane: lane };
|
|
9257
9293
|
}
|
|
9258
9294
|
|
|
9259
9295
|
/** Attach the additive `goal` field to a fact reader's return: the same
|
|
@@ -11017,7 +11053,10 @@ function inheritsChain(graph, startId) {
|
|
|
11017
11053
|
* plus factAnswer's same additive `goal` field when one is deducible
|
|
11018
11054
|
* (withDeducedGoal). */
|
|
11019
11055
|
export async function factReadBack(memoryDir, query, envelope, miss, graph = null, focusLabel = null, biasByBundle = {}, cache = null) {
|
|
11020
|
-
return
|
|
11056
|
+
return withEnumerationLane(
|
|
11057
|
+
withDeducedGoal(await factReadBackReaders(memoryDir, query, envelope, miss, graph, focusLabel, biasByBundle, cache), envelope, query),
|
|
11058
|
+
ENUMERATION_LANES.FACT_READBACK,
|
|
11059
|
+
);
|
|
11021
11060
|
}
|
|
11022
11061
|
|
|
11023
11062
|
async function factReadBackReaders(memoryDir, query, envelope, miss, graph = null, focusLabel = null, biasByBundle = {}, cache = null) {
|
|
@@ -15470,6 +15509,9 @@ async function runAsk(query, { config, source, graph, focus, last, templates, me
|
|
|
15470
15509
|
let via = "composed";
|
|
15471
15510
|
let recordMiss = miss;
|
|
15472
15511
|
let factPending = null; // a truncated fact listing's held remainder (for "more" paging)
|
|
15512
|
+
// Set by the lanes here whose answer reports a set's extent, and read by the
|
|
15513
|
+
// corpus-scope trailer. Null on every point answer and every miss.
|
|
15514
|
+
let enumerationLane = null;
|
|
15473
15515
|
// Set when the memory-facts lane (W4, below) answered from a corpus-weak-only
|
|
15474
15516
|
// hit set (factAnswer's KNOW_ABOUT_RE reader, `weakOnly`) — the hedged
|
|
15475
15517
|
// "possibly" answer still stands as `answer`, but `via` is deliberately left
|
|
@@ -15524,6 +15566,7 @@ async function runAsk(query, { config, source, graph, focus, last, templates, me
|
|
|
15524
15566
|
// A cold "what else" carries miss:true — it resolved no subject, so the
|
|
15525
15567
|
// turn is a miss in better words, exactly like the isa ladder's closers.
|
|
15526
15568
|
answer = whatElse.text; via = "fact:what-else"; recordMiss = whatElse.miss ?? false; handled = true;
|
|
15569
|
+
if (!recordMiss) enumerationLane = ENUMERATION_LANES.WHAT_ELSE;
|
|
15527
15570
|
if (whatElse.pending) factPending = whatElse.pending;
|
|
15528
15571
|
deduced = "surface additional remembered facts beyond the primary definition";
|
|
15529
15572
|
note(trace, "lane: (0) WHAT ELSE — \"what else is/about X\" recognized off the raw query, before the relaxation cascade could quietly drop \"else\" and reduce it to a plain \"what is X\"");
|
|
@@ -16058,6 +16101,7 @@ async function runAsk(query, { config, source, graph, focus, last, templates, me
|
|
|
16058
16101
|
if (!fact.miss && !fact.weakOnly) {
|
|
16059
16102
|
via = "fact";
|
|
16060
16103
|
recordMiss = false;
|
|
16104
|
+
if (fact.enumerationLane) enumerationLane = fact.enumerationLane;
|
|
16061
16105
|
} else if (fact.weakOnly) {
|
|
16062
16106
|
factLaneWeakOnly = true;
|
|
16063
16107
|
}
|
|
@@ -16397,6 +16441,7 @@ async function runAsk(query, { config, source, graph, focus, last, templates, me
|
|
|
16397
16441
|
answer = fact.replace ? fact.text : `${answer}\n${fact.text}`;
|
|
16398
16442
|
via = "fact";
|
|
16399
16443
|
recordMiss = false;
|
|
16444
|
+
if (fact.enumerationLane) enumerationLane = fact.enumerationLane;
|
|
16400
16445
|
if (fact.pending) factPending = fact.pending;
|
|
16401
16446
|
note(trace, "lane: (4h) CHILD PACK — a clean miss on a lexicon term pulled the term's triples from the shipped child pack into memory, and the question was re-answered from the store");
|
|
16402
16447
|
note(trace, `source: child pack ${CHILD_PACK_NAME} — ${learned.count} fact(s) appended as ${childProvenanceTag(key)}, answer served from .tmct/memory Facts`);
|
|
@@ -16646,6 +16691,15 @@ async function runAsk(query, { config, source, graph, focus, last, templates, me
|
|
|
16646
16691
|
// turn "asked about" (the SchemaClass meta-node is documentation, not a code entity),
|
|
16647
16692
|
// so record + expand them, not the schema match.
|
|
16648
16693
|
const finalAnsweredIds = conceptInstances ? conceptInstances.map((i) => i.id) : answeredIds;
|
|
16694
|
+
// `lane`: the dialogue-act lane — a lane's own override, else the
|
|
16695
|
+
// question-shape lookup — resolved to an ISO act by runTurn's withLast.
|
|
16696
|
+
const lane = dialogueLaneOverride ?? askDialogueLane(envelope?.parsed, query, recordMiss);
|
|
16697
|
+
// A set question answered out of the fact store reports a set's extent even
|
|
16698
|
+
// when the set turned out to hold one member, so the question's own shape
|
|
16699
|
+
// decides here and the rendered-answer rule only widens it.
|
|
16700
|
+
if (!enumerationLane && !recordMiss && via === "fact" && lane === "ask-set") {
|
|
16701
|
+
enumerationLane = ENUMERATION_LANES.FACT_SET;
|
|
16702
|
+
}
|
|
16649
16703
|
const record = {
|
|
16650
16704
|
type: "turn", ts, query, via, resolvedIds, answeredIds: finalAnsweredIds, miss: recordMiss,
|
|
16651
16705
|
// English gloss + machine-parsable notation — off ask.mjs's own
|
|
@@ -16655,6 +16709,9 @@ async function runAsk(query, { config, source, graph, focus, last, templates, me
|
|
|
16655
16709
|
// Premise-derived trust for a LIVE-CHASE-ONLY entailment answer; omitted
|
|
16656
16710
|
// entirely when this turn didn't answer via one of those.
|
|
16657
16711
|
...(entailedTrust !== null ? { entailedTrust } : {}),
|
|
16712
|
+
// Set only when this answer reports a set's extent — the corpus-scope
|
|
16713
|
+
// trailer's own gate. Absent on a point answer and on every miss.
|
|
16714
|
+
...(enumerationLane && !recordMiss ? { enumerationLane } : {}),
|
|
16658
16715
|
// The automatic /prove fallback's own budget wall — the same marker
|
|
16659
16716
|
// /prove's own explicit budget wall stamps, so chatbench/infbench can
|
|
16660
16717
|
// count a budget miss apart from a parse miss.
|
|
@@ -16688,21 +16745,21 @@ async function runAsk(query, { config, source, graph, focus, last, templates, me
|
|
|
16688
16745
|
// `goal`: the SAME deduced string the debug trace's own "goal:" line
|
|
16689
16746
|
// carries. Only runAsk ever sets this field, so the always-on goal line is
|
|
16690
16747
|
// scoped to real ask-engine turns by construction.
|
|
16691
|
-
// `lane`: the dialogue-act lane — a lane's own override, else the
|
|
16692
|
-
// question-shape lookup — resolved to an ISO act by runTurn's withLast.
|
|
16693
|
-
const lane = dialogueLaneOverride ?? askDialogueLane(envelope?.parsed, query, recordMiss);
|
|
16694
16748
|
return { answer, logLines, record, focus: newFocus, detail, effectiveQuery, goal: deduced, lane, ...(planResult ? { plan: planResult } : {}) };
|
|
16695
16749
|
}
|
|
16696
16750
|
|
|
16697
16751
|
/** A non-ask, non-dispatch chat turn (count answer, /stats) — the same
|
|
16698
16752
|
* { answer, logLines, record, focus } shape, recorded like any other turn. */
|
|
16699
|
-
function plainTurn(query, answer, { command, via = "composed", miss = false, focus = null, canonical = null, goal = null } = {}) {
|
|
16753
|
+
function plainTurn(query, answer, { command, via = "composed", miss = false, focus = null, canonical = null, goal = null, enumerationLane = null } = {}) {
|
|
16700
16754
|
const ts = new Date().toISOString();
|
|
16701
16755
|
return {
|
|
16702
16756
|
answer,
|
|
16703
16757
|
logLines: [ts, `> ${query}`, answer, ""],
|
|
16704
16758
|
record: {
|
|
16705
16759
|
type: "turn", ts, query, ...(command ? { command } : {}), via, resolvedIds: [], answeredIds: [], miss,
|
|
16760
|
+
// Set only by the lanes whose answers report a set's extent. Absent
|
|
16761
|
+
// everywhere else, so a point answer never grows a corpus-scope line.
|
|
16762
|
+
...(enumerationLane ? { enumerationLane } : {}),
|
|
16706
16763
|
// See runAsk's own `record.canonical`; `null` is the honest default
|
|
16707
16764
|
// here (a bare command confirmation, an orientation card, a count).
|
|
16708
16765
|
canonical,
|
|
@@ -18338,7 +18395,7 @@ export async function runTurn(input, options = {}) {
|
|
|
18338
18395
|
return { ...result, factsTouched: await factsTouchedSince(memoryDir, before) };
|
|
18339
18396
|
}
|
|
18340
18397
|
|
|
18341
|
-
async function dispatchTurn(input, { config, source = defaultSource, graph = null, focus = null, last = null, memoryDir = null, sessionId = "", env = process.env, lexicon = null, narrate = false, liveReference = false, researchSource = null, onLiveLookup = null, vocabHint = null, tel = null, biasByBundle = {}, factRowsCache: injectedFactRowsCache = null, planState = null, gameConfig = null, uiContext = "cli", synthesisBudget = AUTO_SYNTHESIS_BUDGET, researchState = null, researchConfig = null, newsState = null, newsConfig = null, newsProviders = null, discourse = null, _noSplit = false, actingSubject = "player", codeDomainActive = null, laneVocab = null, domainPacks = null } = {}) {
|
|
18398
|
+
async function dispatchTurn(input, { config, source = defaultSource, graph = null, focus = null, last = null, memoryDir = null, sessionId = "", env = process.env, lexicon = null, narrate = false, liveReference = false, researchSource = null, onLiveLookup = null, vocabHint = null, tel = null, biasByBundle = {}, factRowsCache: injectedFactRowsCache = null, planState = null, gameConfig = null, uiContext = "cli", synthesisBudget = AUTO_SYNTHESIS_BUDGET, researchState = null, researchConfig = null, newsState = null, newsConfig = null, newsProviders = null, discourse = null, _noSplit = false, actingSubject = "player", codeDomainActive = null, laneVocab = null, domainPacks = null, retrieval = null } = {}) {
|
|
18342
18399
|
// Every game's tuning knobs (spider-fly's mass economy, guess-the-number's
|
|
18343
18400
|
// bounds, the shared plan lane's search-depth cap) — a caller's own
|
|
18344
18401
|
// gameConfig (chat-session.mjs resolves one per session from tmct.toml)
|
|
@@ -18484,7 +18541,7 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
|
|
|
18484
18541
|
// Goal/canonical lines append onto the PRE-narration `finished` result
|
|
18485
18542
|
// `nextLast` was captured from, so a narrated turn still gets both short
|
|
18486
18543
|
// lines up top plus the full trace block after.
|
|
18487
|
-
return { ...withNarration(withCanonicalLine(withGoalLine(finished)), trace, fallbackGoal), last: nextLast, discourse: discourseHolder.record };
|
|
18544
|
+
return { ...withNarration(withCanonicalLine(withGoalLine(withRetrievalNote(finished, retrieval))), trace, fallbackGoal), last: nextLast, discourse: discourseHolder.record };
|
|
18488
18545
|
};
|
|
18489
18546
|
|
|
18490
18547
|
// Slash-optional system commands: a bare leading command word ("stats",
|
|
@@ -19005,7 +19062,7 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
|
|
|
19005
19062
|
note(trace, `goal: ${goal}`);
|
|
19006
19063
|
note(trace, `lane: SKOS VIEW — a synonym/related question ${skos.miss ? "matched but the store holds no such facts (honest miss)" : "answered from the store's relation facts"}`);
|
|
19007
19064
|
if (!skos.miss) note(trace, "source: .tmct/memory Facts (mgx:synonym/mgx:relatedTo/mgx:similarTo, read as skos:altLabel/skos:related)");
|
|
19008
|
-
const skosTurn = plainTurn(workingLine, skos.text, { via: skos.miss ? "miss" : "fact", miss: skos.miss, focus });
|
|
19065
|
+
const skosTurn = plainTurn(workingLine, skos.text, { via: skos.miss ? "miss" : "fact", miss: skos.miss, focus, enumerationLane: skos.miss ? null : ENUMERATION_LANES.SKOS_NEIGHBOURHOOD });
|
|
19009
19066
|
if (!skos.miss) skosTurn.goal = goal;
|
|
19010
19067
|
skosTurn.lane = skos.miss ? "honest-miss" : "ask-set";
|
|
19011
19068
|
return withLast(skosTurn, goal);
|
|
@@ -19021,7 +19078,7 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
|
|
|
19021
19078
|
if (memCount != null) {
|
|
19022
19079
|
note(trace, "goal: get a count of a memory-store kind (facts/utterances)");
|
|
19023
19080
|
note(trace, "lane: answerMemoryCount — matched a MEMORY_COUNT_NOUNS entry, answered off the .tmct/memory graph header");
|
|
19024
|
-
return withLast(plainTurn(workingLine, memCount, { via: "count", focus }), "get a count of a memory-store kind");
|
|
19081
|
+
return withLast(plainTurn(workingLine, memCount, { via: "count", focus, enumerationLane: ENUMERATION_LANES.MEMORY_COUNT }), "get a count of a memory-store kind");
|
|
19025
19082
|
}
|
|
19026
19083
|
}
|
|
19027
19084
|
// "list facts"/"list utterances"/"how many sessions are there" — enumerate the
|
|
@@ -19034,7 +19091,7 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
|
|
|
19034
19091
|
const goal = "list or count a memory-store kind (facts/utterances/sessions/sources/rules)";
|
|
19035
19092
|
note(trace, `goal: ${goal}`);
|
|
19036
19093
|
note(trace, "lane: answerMemoryClassQuery — matched a memory-store class noun, answered off the .tmct/memory store's own individuals");
|
|
19037
|
-
const turn = plainTurn(workingLine, memClass.text, { via: memClass.miss ? "miss" : "fact", miss: !!memClass.miss, focus });
|
|
19094
|
+
const turn = plainTurn(workingLine, memClass.text, { via: memClass.miss ? "miss" : "fact", miss: !!memClass.miss, focus, enumerationLane: memClass.miss ? null : ENUMERATION_LANES.MEMORY_CLASS });
|
|
19038
19095
|
// A bare numeric count ("1 source.") stays silent here — only a real list
|
|
19039
19096
|
// enumeration gets the trailer. answerMemoryClassQuery serves both shapes
|
|
19040
19097
|
// through one lane. answerTaughtClassCount below is the one count lane that
|
|
@@ -19055,7 +19112,7 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
|
|
|
19055
19112
|
const goal = "list the words I know that contain a given letter";
|
|
19056
19113
|
note(trace, `goal: ${goal}`);
|
|
19057
19114
|
note(trace, "lane: answerWordsWithLetter — matched a closed words-containing-a-letter phrasing over the store's own subject/object terms");
|
|
19058
|
-
const turn = plainTurn(workingLine, lettered.text, { via: lettered.miss ? "miss" : "fact", miss: !!lettered.miss, focus });
|
|
19115
|
+
const turn = plainTurn(workingLine, lettered.text, { via: lettered.miss ? "miss" : "fact", miss: !!lettered.miss, focus, enumerationLane: lettered.miss ? null : ENUMERATION_LANES.LETTER_WORDS });
|
|
19059
19116
|
if (!lettered.miss) turn.goal = goal;
|
|
19060
19117
|
turn.lane = lettered.miss ? "honest-miss" : "ask-set";
|
|
19061
19118
|
if (lettered.pending) turn.detail = { traversal: null, matches: [], pending: lettered.pending };
|
|
@@ -19072,7 +19129,7 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
|
|
|
19072
19129
|
const goal = "list a declared collection's taught contents";
|
|
19073
19130
|
note(trace, `goal: ${goal}`);
|
|
19074
19131
|
note(trace, "lane: answerCollectionContents — matched a container-restricted or bare containment list over mgx:memberOf/mgx:partOf rows");
|
|
19075
|
-
const turn = plainTurn(workingLine, collectionContents.text, { via: collectionContents.miss ? "miss" : "fact", miss: !!collectionContents.miss, focus });
|
|
19132
|
+
const turn = plainTurn(workingLine, collectionContents.text, { via: collectionContents.miss ? "miss" : "fact", miss: !!collectionContents.miss, focus, enumerationLane: collectionContents.miss ? null : ENUMERATION_LANES.COLLECTION_CONTENTS });
|
|
19076
19133
|
if (!collectionContents.miss) turn.goal = goal;
|
|
19077
19134
|
if (collectionContents.pending) turn.detail = { traversal: null, matches: [], pending: collectionContents.pending };
|
|
19078
19135
|
return withLast(turn, goal);
|
|
@@ -19086,7 +19143,7 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
|
|
|
19086
19143
|
if (taughtCount != null) {
|
|
19087
19144
|
note(trace, 'goal: count the taught members of a class ("how many animals are there")');
|
|
19088
19145
|
note(trace, "lane: answerTaughtClassCount — matched a plain-noun count over taught isa-facts whose OBJECT is that class");
|
|
19089
|
-
return withLast(plainTurn(workingLine, taughtCount, { via: "count", focus }), "count a taught class's members");
|
|
19146
|
+
return withLast(plainTurn(workingLine, taughtCount, { via: "count", focus, enumerationLane: ENUMERATION_LANES.TAUGHT_CLASS_COUNT }), "count a taught class's members");
|
|
19090
19147
|
}
|
|
19091
19148
|
}
|
|
19092
19149
|
// "list all animals"/"list the animals" — enumerate a taught class's members
|
|
@@ -19098,7 +19155,7 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
|
|
|
19098
19155
|
const goal = "list the taught members of a class";
|
|
19099
19156
|
note(trace, `goal: ${goal}`);
|
|
19100
19157
|
note(trace, "lane: answerMembershipList — matched a bare 'list <noun>' over taught isa-facts whose OBJECT is that class");
|
|
19101
|
-
const turn = plainTurn(workingLine, memberList.text, { via: memberList.miss ? "miss" : "fact", miss: !!memberList.miss, focus });
|
|
19158
|
+
const turn = plainTurn(workingLine, memberList.text, { via: memberList.miss ? "miss" : "fact", miss: !!memberList.miss, focus, enumerationLane: memberList.miss ? null : ENUMERATION_LANES.MEMBERSHIP_LIST });
|
|
19102
19159
|
if (!memberList.miss) turn.goal = goal;
|
|
19103
19160
|
if (memberList.pending) turn.detail = { traversal: null, matches: [], pending: memberList.pending };
|
|
19104
19161
|
return withLast(turn, goal);
|
|
@@ -19113,7 +19170,7 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
|
|
|
19113
19170
|
const goal = "give an example of a taught class's member";
|
|
19114
19171
|
note(trace, `goal: ${goal}`);
|
|
19115
19172
|
note(trace, "lane: answerMembershipExample — matched 'example of a <noun>'/'name a <noun>' over taught isa-facts whose OBJECT is that class");
|
|
19116
|
-
const turn = plainTurn(workingLine, memberExample.text, { via: memberExample.miss ? "miss" : "fact", miss: !!memberExample.miss, focus });
|
|
19173
|
+
const turn = plainTurn(workingLine, memberExample.text, { via: memberExample.miss ? "miss" : "fact", miss: !!memberExample.miss, focus, enumerationLane: memberExample.miss ? null : ENUMERATION_LANES.MEMBERSHIP_EXAMPLE });
|
|
19117
19174
|
if (!memberExample.miss) turn.goal = goal;
|
|
19118
19175
|
return withLast(turn, goal);
|
|
19119
19176
|
}
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
// corpus-loader.mjs — load, clear and read the shared, read-only corpus
|
|
2
|
+
// bands (corpus-bands.mjs) over an injected DynamoDB-shaped document client:
|
|
3
|
+
// the AWS SDK's `DynamoDBDocument` convenience wrapper (`.put`/`.get`/
|
|
4
|
+
// `.delete`/`.query`, no Command objects), the same client shape
|
|
5
|
+
// `termQueryOverDocumentClient` (subgraph-retrieval.mjs) already reads. This
|
|
6
|
+
// module holds no credentials and imports no AWS package itself — the
|
|
7
|
+
// consumer constructs the client (a profile locally, OIDC in CI) and injects
|
|
8
|
+
// it, matching the shipped DynamoDB row backend's own discipline (§3.10).
|
|
9
|
+
//
|
|
10
|
+
// `queryBandTerm` lives here rather than in corpus-bands.mjs because it
|
|
11
|
+
// wraps subgraph-retrieval.mjs's `termQueryOverDocumentClient` — the one
|
|
12
|
+
// term-Query implementation this whole surface shares — and that module is
|
|
13
|
+
// services-layer; corpus-bands.mjs is adapters-layer and may not import
|
|
14
|
+
// upward into it (test/estate/import-layers.test.mjs).
|
|
15
|
+
//
|
|
16
|
+
// Load streams the source jsonl (wire-row-shaped facts, one per line),
|
|
17
|
+
// writes each with bounded concurrency, and writes the manifest row last —
|
|
18
|
+
// a run that dies mid-load leaves individually valid rows and a stale
|
|
19
|
+
// manifest, and re-running completes it, because every write is a content-
|
|
20
|
+
// addressed overwrite. Load is also a no-op when the source digest matches
|
|
21
|
+
// the manifest already on the band, which is what makes a CI job that runs
|
|
22
|
+
// this against every band on every deploy cheap.
|
|
23
|
+
//
|
|
24
|
+
// Clear queries the whole band partition and physically deletes every item
|
|
25
|
+
// it finds, manifest last. Physical, not the row service's soft delete: the
|
|
26
|
+
// loader holds AWS credentials on the operator's side of the trust line, not
|
|
27
|
+
// a public API caller's.
|
|
28
|
+
|
|
29
|
+
import { createReadStream } from "node:fs";
|
|
30
|
+
import { createInterface } from "node:readline";
|
|
31
|
+
import { createHash } from "node:crypto";
|
|
32
|
+
import {
|
|
33
|
+
bandPartitionKey, bandSortKeyForRow, buildBandManifest, bandLicenseInfo, MANIFEST_SORT_KEY,
|
|
34
|
+
} from "../adapters/memory/corpus-bands.mjs";
|
|
35
|
+
import { BackendRejected, BackendUnavailable, assertValidRow } from "../adapters/memory/row-backend.mjs";
|
|
36
|
+
import { termQueryOverDocumentClient } from "./subgraph-retrieval.mjs";
|
|
37
|
+
|
|
38
|
+
const DEFAULT_WRITE_CONCURRENCY = 25;
|
|
39
|
+
|
|
40
|
+
/** Runs `fn` over `items` with at most `limit` calls in flight, mirroring the
|
|
41
|
+
* DynamoDB row backend's own bounded-concurrency write loop. */
|
|
42
|
+
async function mapWithConcurrency(items, limit, fn) {
|
|
43
|
+
if (!items.length) return;
|
|
44
|
+
const workerCount = Math.max(1, Math.min(limit, items.length));
|
|
45
|
+
let cursor = 0;
|
|
46
|
+
async function worker() {
|
|
47
|
+
for (;;) {
|
|
48
|
+
const index = cursor++;
|
|
49
|
+
if (index >= items.length) return;
|
|
50
|
+
await fn(items[index], index);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
await Promise.all(Array.from({ length: workerCount }, worker));
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Every store call funnels through here so a network failure or a
|
|
57
|
+
* 429/5xx-shaped rejection surfaces as `BackendUnavailable`, never a raw
|
|
58
|
+
* client error a caller would have to string-match. */
|
|
59
|
+
async function call(fn, label) {
|
|
60
|
+
try {
|
|
61
|
+
return await fn();
|
|
62
|
+
} catch (error) {
|
|
63
|
+
if (error instanceof BackendRejected || error instanceof BackendUnavailable) throw error;
|
|
64
|
+
throw new BackendUnavailable(`corpus loader's ${label} call failed: ${error.message}`, { cause: error });
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** sha256 of a file's bytes, streamed — the source digest the loader's
|
|
69
|
+
* no-op check compares against the manifest already on the band. */
|
|
70
|
+
export async function digestFile(path) {
|
|
71
|
+
const hash = createHash("sha256");
|
|
72
|
+
await new Promise((resolve, reject) => {
|
|
73
|
+
const stream = createReadStream(path);
|
|
74
|
+
stream.on("data", (chunk) => hash.update(chunk));
|
|
75
|
+
stream.on("end", resolve);
|
|
76
|
+
stream.on("error", reject);
|
|
77
|
+
});
|
|
78
|
+
return hash.digest("hex");
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Stream a wire-row jsonl (one `{rowKey, rowClass, term, json}` per line),
|
|
82
|
+
* validating each row on the way in — a malformed source row is a
|
|
83
|
+
* `BackendRejected`, naming the line, before anything reaches the store. */
|
|
84
|
+
async function* readWireRows(path) {
|
|
85
|
+
const rl = createInterface({ input: createReadStream(path, "utf8"), crlfDelay: Infinity });
|
|
86
|
+
let lineNumber = 0;
|
|
87
|
+
for await (const raw of rl) {
|
|
88
|
+
lineNumber += 1;
|
|
89
|
+
const line = raw.trim();
|
|
90
|
+
if (!line) continue;
|
|
91
|
+
let row;
|
|
92
|
+
try {
|
|
93
|
+
row = JSON.parse(line);
|
|
94
|
+
} catch (error) {
|
|
95
|
+
throw new BackendRejected(`${path}:${lineNumber}: not valid JSON: ${error.message}`);
|
|
96
|
+
}
|
|
97
|
+
assertValidRow(row);
|
|
98
|
+
yield row;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** The manifest row for `band`, or null when the band has never been loaded. */
|
|
103
|
+
export async function bandStatus({ client, tableName, band }) {
|
|
104
|
+
const result = await call(
|
|
105
|
+
() => client.get({ TableName: tableName, Key: { pk: bandPartitionKey(band), sk: MANIFEST_SORT_KEY } }),
|
|
106
|
+
"get",
|
|
107
|
+
);
|
|
108
|
+
return result?.Item ? { ...result.Item } : null;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Every item (fact rows and the manifest, if present) under a band's
|
|
112
|
+
* partition, paginated. Shared by `clearBand` and any caller that wants a
|
|
113
|
+
* full inventory rather than one term's rows. */
|
|
114
|
+
async function queryWholePartition({ client, tableName, band }) {
|
|
115
|
+
const items = [];
|
|
116
|
+
let exclusiveStartKey;
|
|
117
|
+
do {
|
|
118
|
+
const response = await call(() => client.query({
|
|
119
|
+
TableName: tableName,
|
|
120
|
+
KeyConditionExpression: "pk = :pk",
|
|
121
|
+
ExpressionAttributeValues: { ":pk": bandPartitionKey(band) },
|
|
122
|
+
...(exclusiveStartKey ? { ExclusiveStartKey: exclusiveStartKey } : {}),
|
|
123
|
+
}), "query");
|
|
124
|
+
items.push(...(response?.Items || []));
|
|
125
|
+
exclusiveStartKey = response?.LastEvaluatedKey || null;
|
|
126
|
+
} while (exclusiveStartKey);
|
|
127
|
+
return items;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Load `band` from a jsonl source of wire rows. Resolves to
|
|
131
|
+
* `{status: "unchanged" | "loaded" | "dry-run", band, rowCount, sourceDigest}`.
|
|
132
|
+
* `dryRun` computes the digest and reports what would happen without
|
|
133
|
+
* writing anything. */
|
|
134
|
+
export async function loadBand({
|
|
135
|
+
client, tableName, band, source, dryRun = false,
|
|
136
|
+
writeConcurrency = DEFAULT_WRITE_CONCURRENCY, now = () => new Date().toISOString(),
|
|
137
|
+
}) {
|
|
138
|
+
if (!client) throw new TypeError("loadBand needs a client");
|
|
139
|
+
if (!tableName) throw new TypeError("loadBand needs a tableName");
|
|
140
|
+
if (!band) throw new TypeError("loadBand needs a band");
|
|
141
|
+
if (!source) throw new TypeError("loadBand needs a source path");
|
|
142
|
+
|
|
143
|
+
const sourceDigest = await digestFile(source);
|
|
144
|
+
const existing = await bandStatus({ client, tableName, band });
|
|
145
|
+
if (existing?.sourceDigest === sourceDigest) {
|
|
146
|
+
return { status: "unchanged", band, rowCount: existing.rowCount, sourceDigest };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const pk = bandPartitionKey(band);
|
|
150
|
+
let rowCount = 0;
|
|
151
|
+
const { license, notice } = bandLicenseInfo(band);
|
|
152
|
+
|
|
153
|
+
if (!dryRun) {
|
|
154
|
+
const rows = [];
|
|
155
|
+
for await (const row of readWireRows(source)) rows.push(row);
|
|
156
|
+
rowCount = rows.length;
|
|
157
|
+
await mapWithConcurrency(rows, writeConcurrency, async (row) => {
|
|
158
|
+
const item = {
|
|
159
|
+
pk, sk: bandSortKeyForRow(row.rowClass, row.term, row.rowKey),
|
|
160
|
+
rowKey: row.rowKey, rowClass: row.rowClass, term: row.term, json: row.json,
|
|
161
|
+
};
|
|
162
|
+
await call(() => client.put({ TableName: tableName, Item: item }), "put");
|
|
163
|
+
});
|
|
164
|
+
const manifest = buildBandManifest({
|
|
165
|
+
band, rowCount, loadedAt: now(), sourceDigest, license, notice,
|
|
166
|
+
});
|
|
167
|
+
await call(() => client.put({
|
|
168
|
+
TableName: tableName,
|
|
169
|
+
Item: { pk, sk: MANIFEST_SORT_KEY, ...manifest },
|
|
170
|
+
}), "put");
|
|
171
|
+
return { status: "loaded", band, rowCount, sourceDigest };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
for await (const _row of readWireRows(source)) rowCount += 1;
|
|
175
|
+
return { status: "dry-run", band, rowCount, sourceDigest };
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Physically delete every item under `band`'s partition, manifest last.
|
|
179
|
+
* Idempotent: an empty partition (already cleared, or never loaded) is a
|
|
180
|
+
* no-op. Resolves to `{band, deleted}`. */
|
|
181
|
+
export async function clearBand({ client, tableName, band, writeConcurrency = DEFAULT_WRITE_CONCURRENCY }) {
|
|
182
|
+
if (!client) throw new TypeError("clearBand needs a client");
|
|
183
|
+
if (!tableName) throw new TypeError("clearBand needs a tableName");
|
|
184
|
+
if (!band) throw new TypeError("clearBand needs a band");
|
|
185
|
+
|
|
186
|
+
const items = await queryWholePartition({ client, tableName, band });
|
|
187
|
+
const facts = items.filter((item) => item.sk !== MANIFEST_SORT_KEY);
|
|
188
|
+
const manifestItem = items.find((item) => item.sk === MANIFEST_SORT_KEY);
|
|
189
|
+
|
|
190
|
+
await mapWithConcurrency(facts, writeConcurrency, async (item) => {
|
|
191
|
+
await call(() => client.delete({ TableName: tableName, Key: { pk: item.pk, sk: item.sk } }), "delete");
|
|
192
|
+
});
|
|
193
|
+
if (manifestItem) {
|
|
194
|
+
await call(() => client.delete({ TableName: tableName, Key: { pk: manifestItem.pk, sk: manifestItem.sk } }), "delete");
|
|
195
|
+
}
|
|
196
|
+
return { band, deleted: items.length };
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const DEFAULT_BAND_QUERY_PAGE_SIZE = 200;
|
|
200
|
+
|
|
201
|
+
/** One term's rows from one band, fully paginated, wrapping
|
|
202
|
+
* subgraph-retrieval.mjs's `termQueryOverDocumentClient` — the one term
|
|
203
|
+
* Query this whole surface shares. `client` is the same convenience
|
|
204
|
+
* document client (`.query({...})` resolving to `{Items,
|
|
205
|
+
* LastEvaluatedKey}`) `loadBand`/`clearBand` already take. Returns plain
|
|
206
|
+
* wire rows (`{rowKey, rowClass, term, json}`), with the storage-only
|
|
207
|
+
* `pk`/`sk` stripped — the loader's own read-back checks and the read-only
|
|
208
|
+
* corpus route both call this rather than issuing their own Query. */
|
|
209
|
+
export async function queryBandTerm(client, tableName, band, term, { pageSize = DEFAULT_BAND_QUERY_PAGE_SIZE } = {}) {
|
|
210
|
+
const queryTerm = termQueryOverDocumentClient({ client, tableName, pageSize });
|
|
211
|
+
const rows = [];
|
|
212
|
+
let exclusiveStartKey;
|
|
213
|
+
for (;;) {
|
|
214
|
+
const response = await queryTerm({ band, term, exclusiveStartKey });
|
|
215
|
+
for (const item of response.rows) {
|
|
216
|
+
rows.push({ rowKey: item.rowKey, rowClass: item.rowClass, term: item.term, json: item.json });
|
|
217
|
+
}
|
|
218
|
+
exclusiveStartKey = response.lastEvaluatedKey;
|
|
219
|
+
if (!exclusiveStartKey) break;
|
|
220
|
+
}
|
|
221
|
+
return rows;
|
|
222
|
+
}
|