@polycode-projects/the-mechanical-code-talker 6.0.0 → 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.
@@ -0,0 +1,120 @@
1
+ // retrieval-marker.mjs — the trailing line an answer carries when a corpus
2
+ // retrieval stood behind it, or when one was supposed to and did not.
3
+ //
4
+ // A bounded retrieval reads a slice of the corpus, never the whole of it. A
5
+ // point answer is unaffected: it either grounds on what came back or misses.
6
+ // An answer that reports the extent of a set is different. Reporting the
7
+ // slice's contents as the store's would be a completeness claim nothing
8
+ // checked, so those answers say what they counted over.
9
+ //
10
+ // Three states, three fixed lines. The wording is written once here and pinned
11
+ // byte for byte, because it lands in prose a reader judges the whole product
12
+ // by.
13
+
14
+ import { SUPPLEMENTED_MODE, SEED_SESSION_MODE } from "./retrieval-modes.mjs";
15
+
16
+ export { SUPPLEMENTED_MODE, SEED_SESSION_MODE };
17
+
18
+ /** Retrieval ran and nothing stopped it early. */
19
+ export const CORPUS_SCOPE_LINE = "Corpus scope: the rows this query pulled from the corpus.";
20
+
21
+ /** Retrieval ran and a budget stopped it, or a read failed. Over a dense
22
+ * corpus this is the ordinary case rather than the exception — the
23
+ * subClassOf closure branches, so a grounded turn spends its query budget
24
+ * and comes back with a prefix. The line reads as a routine statement of
25
+ * scope for that reason. */
26
+ export const CORPUS_SCOPE_BOUNDED_LINE = "Corpus scope: the rows this query pulled from the corpus. The corpus may hold more.";
27
+
28
+ /** No corpus read happened while bands were configured — the breaker is open,
29
+ * so the turn answered from the bundled seed and the session alone. Under
30
+ * that floor this line is the reader's only signal that a thin answer came
31
+ * from the degraded mode, so it rides every answer, not only the ones that
32
+ * count a set. */
33
+ export const CORPUS_SUPPLEMENT_ABSENT_LINE = "Corpus scope: none. Answered without the corpus supplement.";
34
+
35
+ /** The enumeration-class lanes: the answers that report a set's extent, and so
36
+ * have to say what they counted over.
37
+ *
38
+ * Every entry is referenced from the composer that mints it, and the lane
39
+ * inventory test holds that both ways — a registered lane no composer sets is
40
+ * dead, and a composer naming a lane that is not registered is a lane nobody
41
+ * classified. */
42
+ export const ENUMERATION_LANES = Object.freeze({
43
+ /** "how many facts do you know" — a tally of a memory-store kind. */
44
+ MEMORY_COUNT: "memory-count",
45
+ /** "list facts" / "how many sessions are there" — the stored individuals. */
46
+ MEMORY_CLASS: "memory-class",
47
+ /** "which words have a p in them" — the store's own vocabulary, filtered. */
48
+ LETTER_WORDS: "letter-words",
49
+ /** "list the letters in the alphabet" — a declared collection's contents. */
50
+ COLLECTION_CONTENTS: "collection-contents",
51
+ /** "how many animals are there" — a taught class's members, tallied. */
52
+ TAUGHT_CLASS_COUNT: "taught-class-count",
53
+ /** "list the animals" — a taught class's members, named. */
54
+ MEMBERSHIP_LIST: "membership-list",
55
+ /** "name an animal" — one member, and a count of the rest. */
56
+ MEMBERSHIP_EXAMPLE: "membership-example",
57
+ /** "another word for dog" — the remembered synonym neighbourhood. */
58
+ SKOS_NEIGHBOURHOOD: "skos-neighbourhood",
59
+ /** "what else about a dog" — everything past the primary definition. */
60
+ WHAT_ELSE: "what-else",
61
+ /** "which animals can fly" and its siblings, read out of the fact store. */
62
+ FACT_SET: "fact-set",
63
+ /** "what did you learn about dogs" — the read-back cascade's listings. */
64
+ FACT_READBACK: "fact-readback",
65
+ });
66
+
67
+ const REGISTERED_LANES = Object.freeze(Object.values(ENUMERATION_LANES));
68
+
69
+ /** Is this a lane name the registry knows? */
70
+ export function isEnumerationLane(lane) {
71
+ return typeof lane === "string" && REGISTERED_LANES.includes(lane);
72
+ }
73
+
74
+ /** Does this answer report the extent of a set?
75
+ *
76
+ * A truncated listing does by definition — it is holding a remainder. So does
77
+ * any answer that renders more than one fact line: two lines are a set, and a
78
+ * reader takes them as everything there was. One line is a point answer and
79
+ * changes nothing.
80
+ *
81
+ * The fact-store lanes derive their marker through this rather than tagging
82
+ * each of their twenty-odd return sites, which means a reader added to those
83
+ * cascades later is covered the moment it renders a set. */
84
+ export function answerAssertsASet(text, { pending = null } = {}) {
85
+ if (pending) return true;
86
+ return String(text ?? "").split("\n").filter((line) => line.trim() !== "").length > 1;
87
+ }
88
+
89
+ /** The retrieval context in the shape the marker reads, or null when the
90
+ * caller passed none. Accepts `retrieveSubgraph`'s own metrics object
91
+ * unchanged, and the smaller `{mode, bounded, bands}` literal a handler may
92
+ * build by hand. Anything without a recognised mode reads as no context, so a
93
+ * malformed input can never mint a marker. */
94
+ export function retrievalContextOf(input) {
95
+ if (!input || typeof input !== "object") return null;
96
+ const mode = input.mode;
97
+ if (mode !== SUPPLEMENTED_MODE && mode !== SEED_SESSION_MODE) return null;
98
+ return {
99
+ mode,
100
+ bounded: Boolean(input.bounded),
101
+ bands: Array.isArray(input.bands) ? input.bands : [],
102
+ };
103
+ }
104
+
105
+ /** The trailing line this turn's answer carries, or null for no line.
106
+ *
107
+ * No context at all means no line, which is what every caller that never
108
+ * retrieves gets: the local shell, the browser page, every existing test.
109
+ *
110
+ * A seed-session turn with no bands configured is not a degraded mode, it is
111
+ * a deployment without a corpus, so it says nothing either. */
112
+ export function retrievalMarkerLine(retrieval, { enumerationLane = null } = {}) {
113
+ const context = retrievalContextOf(retrieval);
114
+ if (!context) return null;
115
+ if (context.mode === SEED_SESSION_MODE) {
116
+ return context.bands.length ? CORPUS_SUPPLEMENT_ABSENT_LINE : null;
117
+ }
118
+ if (!isEnumerationLane(enumerationLane)) return null;
119
+ return context.bounded ? CORPUS_SCOPE_BOUNDED_LINE : CORPUS_SCOPE_LINE;
120
+ }
@@ -0,0 +1,13 @@
1
+ // retrieval-modes.mjs — the two honest modes a turn's retrieval payload can
2
+ // carry. Every layer that needs to say "the corpus supplement ran" or "it
3
+ // did not" reads these two strings rather than minting its own, so a
4
+ // retrieval-layer skip and a breaker-forced skip land in an answer looking
5
+ // identical.
6
+
7
+ /** Retrieval ran and the answer stands on the corpus supplement as well as
8
+ * the seed and the session. */
9
+ export const SUPPLEMENTED_MODE = "supplemented";
10
+
11
+ /** No corpus read happened — no bands are configured, or the breaker is
12
+ * open. The answer stands on the bundled seed and the session alone. */
13
+ export const SEED_SESSION_MODE = "seed-session";
@@ -117,6 +117,8 @@ const promptFor = (focus) => (focus ? `tmct(${shortLabel(focus.label)})> ` : PRO
117
117
  * logFile, sidecarFile, bannerLines, empty, focus, lastAnswer, turns, promptFor(),
118
118
  * turn(line), close() }. `turn(line)` runs one dispatched turn through runTurn and the
119
119
  * full sink sequencing, returning { answer, end, prompt }; `close()` is idempotent.
120
+ * `turn(line, {retrieval})` passes this turn's own corpus-retrieval context,
121
+ * overriding the session-level `retrieval` option for that turn.
120
122
  */
121
123
  export async function createSession({
122
124
  repoPath,
@@ -168,6 +170,15 @@ export async function createSession({
168
170
  // lifetime (four mud.html characters means four sessions, not one session
169
171
  // switching identity turn to turn).
170
172
  actingSubject,
173
+ // What the corpus retrieval behind this session's turns did, in
174
+ // retrieve-subgraph's own metrics shape ({mode, bounded, bands}). It decides
175
+ // the corpus-scope line an answer carries: what the query pulled in, whether
176
+ // a budget cut it short, or that the supplement was absent altogether. A
177
+ // caller that retrieves per turn passes its own context to `turn(line,
178
+ // {retrieval})` instead, which wins over this one. Omitted (the default)
179
+ // means no corpus behind this session, and every answer is byte-identical to
180
+ // a run without the seam.
181
+ retrieval = null,
171
182
  // The session-log filesystem seam: mkdir/createWriteStream, injectable so a
172
183
  // test can exercise the unwritable-log guard by rejecting at the seam
173
184
  // itself rather than by making a real directory unwritable — chmod-based
@@ -553,10 +564,10 @@ export async function createSession({
553
564
  * (empty when the turn wrote nothing). A throwing runTurn must never abort
554
565
  * the session: a piped/non-interactive driver has no other chance to see
555
566
  * this turn's answer. */
556
- async turn(line) {
567
+ async turn(line, { retrieval: turnRetrieval = null } = {}) {
557
568
  let result;
558
569
  try {
559
- result = await runTurn(line, { config, source, graph, focus, last, memoryDir, sessionId, env, lexicon, narrate: narrateOn, liveReference: liveReferenceOn, researchSource: researchSourceOn, vocabHint, tel, biasByBundle, planState, gameConfig, recognitionConfig, researchState, researchConfig, newsState, newsConfig, newsProviders, discourse: discourseRecord, actingSubject, codeDomainActive: domainActive, laneVocab, domainPacks });
570
+ result = await runTurn(line, { config, source, graph, focus, last, memoryDir, sessionId, env, lexicon, narrate: narrateOn, liveReference: liveReferenceOn, researchSource: researchSourceOn, vocabHint, tel, biasByBundle, planState, gameConfig, recognitionConfig, researchState, researchConfig, newsState, newsConfig, newsProviders, discourse: discourseRecord, actingSubject, codeDomainActive: domainActive, laneVocab, domainPacks, retrieval: turnRetrieval ?? retrieval });
560
571
  } catch (e) {
561
572
  const ts = new Date().toISOString();
562
573
  const message = e instanceof Error ? e.message : String(e);
@@ -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 withDeducedGoal(await factAnswerReaders(memoryDir, query, envelope, miss, biasByBundle, cache, focusLabel), envelope, query);
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 withDeducedGoal(await factReadBackReaders(memoryDir, query, envelope, miss, graph, focusLabel, biasByBundle, cache), envelope, query);
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
+ }