@polycode-projects/the-mechanical-code-talker 6.0.0 → 6.0.2

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.
@@ -30,7 +30,7 @@ import { classDisplayName, DYNAMIC_TAIL_OK_RE } from "../domain/ask.mjs";
30
30
  // about what a predicate says.
31
31
  import {
32
32
  FACT_PREDICATE_PHRASES, TEACH_PARTICIPLE_SRC, predicatePhrase,
33
- thirdPersonSingularSurface, baseVerbSurface, gerundVerbSurface,
33
+ thirdPersonSingularSurface, baseVerbSurface, gerundVerbSurface, findingCaveat,
34
34
  } from "../domain/fact-phrase.mjs";
35
35
  import { emptyRecord as emptyDiscourseRecord, advanceTurn as advanceDiscourseTurn, register as registerReferent, bind as bindDiscourseForm } from "../domain/discourse.mjs";
36
36
  import { uuidv7 } from "../adapters/uuid.mjs";
@@ -38,6 +38,7 @@ import * as defaultSource from "../adapters/source.mjs";
38
38
  import { loadTemplates, render as renderTemplate } from "../adapters/corpus/templates.mjs";
39
39
  import { rankByBiasThenTrust } from "../domain/memory/bias.mjs";
40
40
  import { HAS_A_PREDICATE, loadMemory as loadMemoryStore, normFactPredicate, normFactTerm as normFactTermStatic, readFactRows as readStoredFactRows, readRuleRows as readStoredRuleRows } from "../adapters/memory/core.mjs";
41
+ import { BACKEND_REJECTED_CODE, BACKEND_UNAVAILABLE_CODE } from "../adapters/memory/row-backend.mjs";
41
42
  import {
42
43
  CAPABILITY_REPORT_CAP, NEG_CAPABLE_OF_PREDICATE, NEG_SUBCLASS_PREDICATE, capabilityBaseRate,
43
44
  capabilityExtension, isNegatedPredicate, negatedPredicate,
@@ -80,6 +81,8 @@ import { splitChoiceQuestion, routeChoiceRelation, lemmaFoldVariants, headNounOf
80
81
  import { subClassParents, subClassChildren, descendantSet, ancestryChain, clusterSenses } from "../domain/sense-split.mjs";
81
82
  import { ANSWER_STOP_SET } from "../domain/hub-terms.mjs";
82
83
  import { relatedForTerm } from "../domain/skos-view.mjs";
84
+ import { ENUMERATION_LANES, answerAssertsASet, retrievalMarkerLine } from "../domain/retrieval-marker.mjs";
85
+ import { throughSourceBreaker, sourceSkipNoteLine } from "../domain/source-breaker.mjs";
83
86
  import { adventureTurn, unclaimedAdventureOpening, foldWorldState } from "./adventure.mjs";
84
87
  import { spiderFlyTurn } from "./spider-fly-turn.mjs";
85
88
  import { mudiiiTurn } from "./mudiii-turn.mjs";
@@ -364,6 +367,39 @@ function withCanonicalLine(result) {
364
367
  return { ...result, answer, logLines };
365
368
  }
366
369
 
370
+ /** The corpus-scope line, on the same append-onto-`answer` mechanism as
371
+ * withGoalLine. A turn dispatched with no retrieval context gets nothing —
372
+ * the local shell, the browser page and every existing caller pass none, so
373
+ * their answers are byte-identical to a run without this seam.
374
+ *
375
+ * Applied FIRST in the trailer chain, so the goal and canonical lines stay at
376
+ * the end of the answer where the suites that strip them anchor. The scope
377
+ * line belongs against the answer body anyway: it says what the answer was
378
+ * read from, where the other two describe the turn. */
379
+ function withRetrievalNote(result, retrieval) {
380
+ const line = retrievalMarkerLine(retrieval, { enumerationLane: result?.record?.enumerationLane ?? null });
381
+ if (!line) return result;
382
+ const answer = `${result.answer}\n\n${line}`;
383
+ const logLines = Array.isArray(result.logLines)
384
+ ? result.logLines.map((l) => (l === result.answer ? answer : l))
385
+ : result.logLines;
386
+ return { ...result, answer, logLines };
387
+ }
388
+
389
+ /** The skipped-source line, on the same append-onto-`answer` mechanism as
390
+ * withRetrievalNote, and placed beside it: both say what the answer was read
391
+ * from. A turn that asked no external source, or asked one that answered,
392
+ * gets nothing — which is every turn until a source starts failing. */
393
+ function withSourceSkipNote(result, sourceSkips) {
394
+ const line = sourceSkips?.size ? sourceSkipNoteLine(sourceSkips) : null;
395
+ if (!line) return result;
396
+ const answer = `${result.answer}\n\n${line}`;
397
+ const logLines = Array.isArray(result.logLines)
398
+ ? result.logLines.map((l) => (l === result.answer ? answer : l))
399
+ : result.logLines;
400
+ return { ...result, answer, logLines };
401
+ }
402
+
367
403
  /** Slash-command → (dispatchTool name, arg key). Arg keys are the EXACT ones the
368
404
  * server.mjs dispatchTool switch reads (members/subclasses take `class`;
369
405
  * impact/exports take `module`; architecture takes `package`; search takes
@@ -3402,9 +3438,33 @@ const PLACE_ADVERB_OBJECT_RE = /^(?:anywhere|everywhere|nowhere|somewhere)$/i;
3402
3438
  * tag to a "teach" Source (trust prior in memory/trust.mjs). */
3403
3439
  const teachProvenanceTag = (sessionId, ts) => `teach:chat${sessionId ? `:${sessionId}` : ""}${ts ? `@${ts}` : ""}`;
3404
3440
 
3441
+ /** The store could not be reached or refused service (a 429, a 507, a network
3442
+ * failure). The same write may well land later, so the turn says so and the
3443
+ * session carries on with nothing persisted. Read by code, never by message
3444
+ * text. */
3445
+ const isPersistUnavailable = (error) => error?.code === BACKEND_UNAVAILABLE_CODE;
3446
+ /** The store refused the input itself (an oversized row, a malformed key).
3447
+ * Retrying changes nothing, so this one travels all the way out of the turn
3448
+ * carrying the row and provenance the backend named. */
3449
+ const isPersistRejected = (error) => error?.code === BACKEND_REJECTED_CODE;
3450
+ /** Let a store refusal out of a write helper's own catch. Every other failure
3451
+ * (a malformed slot, a missing grammar, an unparsable sentence) keeps
3452
+ * degrading to null the way it always has. */
3453
+ function rethrowPersistFailure(error) {
3454
+ if (isPersistUnavailable(error) || isPersistRejected(error)) throw error;
3455
+ }
3456
+ /** What a turn says when the store would not take its write. The sentence is
3457
+ * closed and lane-neutral: it never names the fact, so a taught fact, a
3458
+ * taught rule and a retraction all report the same truth. */
3459
+ export const PERSIST_UNAVAILABLE_TEXT = "I understood that, but I couldn't save it. My memory isn't taking writes right now, so nothing changed. We can keep talking, and you can tell me again later.";
3460
+ const PERSIST_UNAVAILABLE_VIA = "persist-unavailable";
3461
+ const persistUnavailableAnswer = () => ({ text: PERSIST_UNAVAILABLE_TEXT, via: PERSIST_UNAVAILABLE_VIA, miss: true });
3462
+
3405
3463
  /** Reify one teach-lane fact + confirm (shared by the property and ownership
3406
3464
  * frames). Lazy + failure-tolerated: a write failure degrades to null (the
3407
- * teach-miss text stands), never a crash. */
3465
+ * teach-miss text stands), never a crash. A store refusal is the exception —
3466
+ * it travels, so the turn reports why nothing was stored instead of blaming
3467
+ * the vocabulary. */
3408
3468
  async function teachFact(memoryDir, sessionId, { subject, predicate, object, quantifier = "", observedAt = "", dateText = "" }) {
3409
3469
  try {
3410
3470
  const { appendFact, normFactTerm } = await import("../adapters/memory/core.mjs");
@@ -3422,7 +3482,8 @@ async function teachFact(memoryDir, sessionId, { subject, predicate, object, qua
3422
3482
  // acknowledgment shows it was registered rather than silently dropped.
3423
3483
  const dateSuffix = observedAt && dateText ? ` (as of ${dateText})` : "";
3424
3484
  return { text: `noted — remembered: ${s} ${phrase} ${o}${dateSuffix}`, via: "assert", miss: false };
3425
- } catch {
3485
+ } catch (error) {
3486
+ rethrowPersistFailure(error);
3426
3487
  return null;
3427
3488
  }
3428
3489
  }
@@ -5972,7 +6033,7 @@ async function teachLane(query, { memoryDir, sessionId = "", lexicon = null, cac
5972
6033
  };
5973
6034
  }
5974
6035
  // nothing stored under that triple — fall through to the ordinary cascade
5975
- } catch { /* store unavailable — fall through */ }
6036
+ } catch (error) { rethrowPersistFailure(error); /* nothing readable under that triple — fall through */ }
5976
6037
  }
5977
6038
  const retractForgetMatch = !retractNotMatch && memoryDir && !QUESTION_LEAD_RE.test(forgetSrc)
5978
6039
  ? forgetSrc.match(RETRACT_FORGET_RE) : null;
@@ -6395,7 +6456,7 @@ async function teachLane(query, { memoryDir, sessionId = "", lexicon = null, cac
6395
6456
  });
6396
6457
  if (stored) return stored;
6397
6458
  }
6398
- } catch { /* store unavailable — the frame declines rather than storing blind */ }
6459
+ } catch (error) { rethrowPersistFailure(error); /* the collection isn't readable — the frame declines rather than storing blind */ }
6399
6460
  }
6400
6461
 
6401
6462
  // RELATIONAL FACT — "<Name> is the <role> of <Name>". Grouped with the
@@ -6492,7 +6553,7 @@ async function teachLane(query, { memoryDir, sessionId = "", lexicon = null, cac
6492
6553
  via: "assert", miss: false,
6493
6554
  };
6494
6555
  }
6495
- } catch { /* malformed slots — fall through to the ordinary honest-miss cascade */ }
6556
+ } catch (error) { rethrowPersistFailure(error); /* malformed slots — fall through to the ordinary honest-miss cascade */ }
6496
6557
  }
6497
6558
 
6498
6559
  // FILTER RULE TEACH — "a <name> is a <base> who is <property>": stores a
@@ -6517,7 +6578,7 @@ async function teachLane(query, { memoryDir, sessionId = "", lexicon = null, cac
6517
6578
  via: "assert", miss: false,
6518
6579
  };
6519
6580
  }
6520
- } catch { /* malformed slots — fall through to the ordinary honest-miss cascade */ }
6581
+ } catch (error) { rethrowPersistFailure(error); /* malformed slots — fall through to the ordinary honest-miss cascade */ }
6521
6582
  }
6522
6583
 
6523
6584
  // RECURSIVE RULE TEACH — "a <name> is a <baseCase>, or a <recStep> of a
@@ -6546,7 +6607,7 @@ async function teachLane(query, { memoryDir, sessionId = "", lexicon = null, cac
6546
6607
  via: "assert", miss: false,
6547
6608
  };
6548
6609
  }
6549
- } catch { /* malformed slots — fall through to the ordinary honest-miss cascade */ }
6610
+ } catch (error) { rethrowPersistFailure(error); /* malformed slots — fall through to the ordinary honest-miss cascade */ }
6550
6611
  }
6551
6612
 
6552
6613
  // ACTION-RULE TEACH — the five action frames plus the render binding (see
@@ -6582,7 +6643,7 @@ async function teachLane(query, { memoryDir, sessionId = "", lexicon = null, cac
6582
6643
  via: "assert", miss: false,
6583
6644
  };
6584
6645
  }
6585
- } catch { /* malformed slots — fall through to the ordinary honest-miss cascade */ }
6646
+ } catch (error) { rethrowPersistFailure(error); /* malformed slots — fall through to the ordinary honest-miss cascade */ }
6586
6647
  }
6587
6648
 
6588
6649
  const actionSigPassive = ownSrc.match(ACTION_SIGNATURE_PASSIVE_RE);
@@ -6607,7 +6668,7 @@ async function teachLane(query, { memoryDir, sessionId = "", lexicon = null, cac
6607
6668
  via: "assert", miss: false,
6608
6669
  };
6609
6670
  }
6610
- } catch { /* malformed slots — fall through to the ordinary honest-miss cascade */ }
6671
+ } catch (error) { rethrowPersistFailure(error); /* malformed slots — fall through to the ordinary honest-miss cascade */ }
6611
6672
  }
6612
6673
  }
6613
6674
 
@@ -6643,7 +6704,7 @@ async function teachLane(query, { memoryDir, sessionId = "", lexicon = null, cac
6643
6704
  via: "assert", miss: false,
6644
6705
  };
6645
6706
  }
6646
- } catch { /* malformed slots — fall through to the ordinary honest-miss cascade */ }
6707
+ } catch (error) { rethrowPersistFailure(error); /* malformed slots — fall through to the ordinary honest-miss cascade */ }
6647
6708
  }
6648
6709
 
6649
6710
  const precondComp = ownSrc.match(ACTION_PRECOND_COMPARATIVE_RE);
@@ -6681,7 +6742,7 @@ async function teachLane(query, { memoryDir, sessionId = "", lexicon = null, cac
6681
6742
  via: "assert", miss: false,
6682
6743
  };
6683
6744
  }
6684
- } catch { /* malformed slots — fall through to the ordinary honest-miss cascade */ }
6745
+ } catch (error) { rethrowPersistFailure(error); /* malformed slots — fall through to the ordinary honest-miss cascade */ }
6685
6746
  }
6686
6747
 
6687
6748
  const actionConstraint = ownSrc.match(ACTION_CONSTRAINT_TEACH_RE);
@@ -6706,7 +6767,7 @@ async function teachLane(query, { memoryDir, sessionId = "", lexicon = null, cac
6706
6767
  via: "assert", miss: false,
6707
6768
  };
6708
6769
  }
6709
- } catch { /* malformed slots — fall through to the ordinary honest-miss cascade */ }
6770
+ } catch (error) { rethrowPersistFailure(error); /* malformed slots — fall through to the ordinary honest-miss cascade */ }
6710
6771
  }
6711
6772
 
6712
6773
  const actionEffect = ownSrc.match(ACTION_EFFECT_TEACH_RE);
@@ -6762,7 +6823,7 @@ async function teachLane(query, { memoryDir, sessionId = "", lexicon = null, cac
6762
6823
  via: "assert", miss: false,
6763
6824
  };
6764
6825
  }
6765
- } catch { /* malformed slots — fall through to the ordinary honest-miss cascade */ }
6826
+ } catch (error) { rethrowPersistFailure(error); /* malformed slots — fall through to the ordinary honest-miss cascade */ }
6766
6827
  }
6767
6828
 
6768
6829
  const rendersAs = ownSrc.match(RENDERS_AS_TEACH_RE);
@@ -8085,6 +8146,36 @@ function citationProvenance(provenance) {
8085
8146
  return provenance.replace(/#node:[0-9a-f]+/g, "");
8086
8147
  }
8087
8148
 
8149
+ /** What every rendered fact line ends with: the extractor's caveat, when the
8150
+ * row carries a finding worth declaring, then the source citation. The order
8151
+ * is fixed — a reader sees how the sentence was read, then who said it — and
8152
+ * both halves are optional, so a clean untraced row ends with nothing at all.
8153
+ *
8154
+ * A row whose extractor recorded a finding stays answerable (no lane declines
8155
+ * a stored fact); the caveat is how the answer says which reading it leans
8156
+ * on, the same reader-visible signal renderFactLine's "possibly:" hedge gives
8157
+ * a weak-corpus row. */
8158
+ function factLineTail(f) {
8159
+ const caveat = findingCaveat(f);
8160
+ const cite = f.provenance ? ` (source: ${citationProvenance(f.provenance)})` : "";
8161
+ return `${caveat ? ` ${caveat}` : ""}${cite}`;
8162
+ }
8163
+
8164
+ /** Every extraction finding the rows behind ONE composed sentence carry. A
8165
+ * union or an enumeration reads several stored rows out as a single line, so
8166
+ * the line declares what any of them was read from. */
8167
+ function composedExtraction(rows) {
8168
+ return rows.filter(Boolean).flatMap((r) => (Array.isArray(r.extraction) ? r.extraction : []));
8169
+ }
8170
+
8171
+ /** One fact as an uncited-framing citation step: the phrase, its caveat and
8172
+ * its source. Chains, both-sides refusals and "via:" receipts all read a
8173
+ * premise this way — the same convention renderFactLine uses, without the
8174
+ * "you told me"/"i learned" first-person framing a standalone line carries. */
8175
+ function citedFactPhrase(f) {
8176
+ return `${factPhrase(f)}${factLineTail(f)}`;
8177
+ }
8178
+
8088
8179
  /** One rendered fact line. An OPERATOR-asserted fact keeps the true first-person
8089
8180
  * provenance ("you told me: …"). A CORPUS fact is presented as clean DATA with its
8090
8181
  * source cited, not "i learned: …" — that phrase over-claims and anthropomorphises
@@ -8096,28 +8187,28 @@ function citationProvenance(provenance) {
8096
8187
  * that it's lower-confidence, so a distinct, honest hedge ("possibly: …")
8097
8188
  * applies here instead. Provenance stays VERBATIM in every case. */
8098
8189
  function renderFactLine(f) {
8099
- const cite = f.provenance ? ` (source: ${citationProvenance(f.provenance)})` : "";
8190
+ const tail = factLineTail(f);
8100
8191
  // A rdfs:subPropertyOf row relates two PREDICATES, not two things — factPhrase
8101
8192
  // would compose the raw CURIE ("contains rdfs:subPropertyOf touches"), so this
8102
8193
  // shape gets its own dedicated line ahead of the provenance-keyed framing below,
8103
8194
  // the same way renderUnionLine/renderEnumerationLine read as a definition
8104
8195
  // rather than a first-person claim regardless of who taught it.
8105
8196
  if (f.predicate === SUB_PROPERTY_OF_PREDICATE) {
8106
- return `${gerundVerbSurface(f.subject)} implies ${gerundVerbSurface(f.object)}${cite}`;
8197
+ return `${gerundVerbSurface(f.subject)} implies ${gerundVerbSurface(f.object)}${tail}`;
8107
8198
  }
8108
8199
  // ace:chat = the ACE-parsed operator assert; teach:chat = the teach lane's
8109
8200
  // natural frames — both are things the operator SAID, so both read first-person.
8110
- if (f.provenance.includes("ace:chat") || f.provenance.includes("teach:chat")) return `you told me: ${factPhrase(f)}${cite}`;
8201
+ if (f.provenance.includes("ace:chat") || f.provenance.includes("teach:chat")) return `you told me: ${factPhrase(f)}${tail}`;
8111
8202
  // WEAK corpus facts (lower trust, e.g. RelatedTo) — real, cited, but hedged as
8112
8203
  // uncertain rather than either flatly stated or falsely claimed as "learned".
8113
- if (f.provenance.includes("corpus-weak:")) return `possibly: ${factPhrase(f)}${cite}`;
8204
+ if (f.provenance.includes("corpus-weak:")) return `possibly: ${factPhrase(f)}${tail}`;
8114
8205
  // SOLID corpus facts are background DATA — present the relation plainly, cited
8115
8206
  // to its source, never "i learned: …" (a first-person claim over corpus data).
8116
- if (f.provenance.includes("corpus:")) return `${factPhrase(f)}${cite}`;
8207
+ if (f.provenance.includes("corpus:")) return `${factPhrase(f)}${tail}`;
8117
8208
  // Reference-pack facts are the same class of cited data — the "i learned:"
8118
8209
  // frame read as a definition-less non-answer on the re-ask.
8119
- if (f.provenance.includes("reference:")) return `${factPhrase(f)}${cite}`;
8120
- return `i learned: ${factPhrase(f)}${cite}`;
8210
+ if (f.provenance.includes("reference:")) return `${factPhrase(f)}${tail}`;
8211
+ return `i learned: ${factPhrase(f)}${tail}`;
8121
8212
  }
8122
8213
 
8123
8214
  /** A union node's stored triples read back as ONE sentence rather than a
@@ -8129,9 +8220,11 @@ function renderFactLine(f) {
8129
8220
  * Pure — takes the fact rows, returns one line. */
8130
8221
  function renderUnionLine(node, members) {
8131
8222
  const sorted = [...members].sort((a, b) => a.object.localeCompare(b.object));
8132
- const cite = node.provenance ? ` (source: ${citationProvenance(node.provenance)})` : "";
8223
+ // One sentence states every arm, so its caveat covers every row it was
8224
+ // composed from, not just the one the citation came off.
8225
+ const tail = factLineTail({ ...node, extraction: composedExtraction([node, ...sorted]) });
8133
8226
  const arms = sorted.map((m) => `${indefiniteArticleFor(m.object)} ${m.object}`).join(" or ");
8134
- return `every ${node.subject} is ${arms}${cite}`;
8227
+ return `every ${node.subject} is ${arms}${tail}`;
8135
8228
  }
8136
8229
 
8137
8230
  /** An enumerated class's stored `owl:oneOf` triples read back as ONE sentence:
@@ -8149,9 +8242,9 @@ function renderEnumerationLine(cls, members) {
8149
8242
  ? `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`
8150
8243
  : names.join("");
8151
8244
  const citeSource = sorted.find((m) => m.provenance)?.provenance;
8152
- const cite = citeSource ? ` (source: ${citationProvenance(citeSource)})` : "";
8245
+ const tail = factLineTail({ provenance: citeSource || "", extraction: composedExtraction(sorted) });
8153
8246
  const plural = thirdPersonSingularSurface(String(cls || "").replace(/-/g, " "));
8154
- return `the ${plural} are exactly ${list}${cite}`;
8247
+ return `the ${plural} are exactly ${list}${tail}`;
8155
8248
  }
8156
8249
 
8157
8250
  /** A universal restriction's stored triples read back as ONE sentence rather
@@ -8165,18 +8258,16 @@ function renderEnumerationLine(cls, members) {
8165
8258
  function renderUniversalRestrictionLine(node, rows) {
8166
8259
  const onProperty = rows.find((r) => r.predicate === "owl:onProperty");
8167
8260
  const allValuesFrom = rows.find((r) => r.predicate === "owl:allValuesFrom");
8168
- const cite = node.provenance ? ` (source: ${citationProvenance(node.provenance)})` : "";
8261
+ const tail = factLineTail({ ...node, extraction: composedExtraction([node, onProperty, allValuesFrom]) });
8169
8262
  const filler = thirdPersonSingularSurface(String(allValuesFrom?.object || "").replace(/-/g, " "));
8170
- return `every ${node.subject} ${onProperty?.object || ""} only ${filler}${cite}`;
8263
+ return `every ${node.subject} ${onProperty?.object || ""} only ${filler}${tail}`;
8171
8264
  }
8172
8265
  export { renderUnionLine, renderEnumerationLine, renderUniversalRestrictionLine };
8173
8266
 
8174
- const SENSE_CITE_RE = / \(source: [^)]*\)$/;
8175
-
8176
8267
  /** Append an is-a object's superclass chain to its rendered fact line, before
8177
- * the citation: "rover is a kind of dog" becomes "rover is a kind of dog →
8178
- * canine → mammal → animal". Only the subject-side is-a lines of the queried
8179
- * term get a chain; every other line renders unchanged.
8268
+ * the caveat and the citation: "rover is a kind of dog" becomes "rover is a
8269
+ * kind of dog → canine → mammal → animal". Only the subject-side is-a lines
8270
+ * of the queried term get a chain; every other line renders unchanged.
8180
8271
  *
8181
8272
  * `toward` steers the chain toward a specific ancestor (the class a "list …"
8182
8273
  * question actually asked about) when the is-a object has more than one
@@ -8187,8 +8278,9 @@ function renderFactLineWithChain(f, parents, subjectVariants, { toward = null }
8187
8278
  const chain = ancestryChain(f.object, parents, { cap: 6, stopAt: ANSWER_STOP_SET, toward });
8188
8279
  if (chain.length <= 1) return base;
8189
8280
  const suffix = ` → ${chain.slice(1).join(" → ")}`;
8190
- const cite = base.match(SENSE_CITE_RE);
8191
- return cite ? base.slice(0, cite.index) + suffix + cite[0] : base + suffix;
8281
+ const tail = factLineTail(f);
8282
+ if (!tail || !base.endsWith(tail)) return base + suffix;
8283
+ return base.slice(0, base.length - tail.length) + suffix + tail;
8192
8284
  }
8193
8285
 
8194
8286
  /** Render a subject-scan fact list with each is-a object's superclass chain
@@ -8315,9 +8407,8 @@ function isaPolarityReply(hit, negHit) {
8315
8407
  * inconsistency as a derivation — so neither side wins, same discipline as
8316
8408
  * isaPolarityReply's both-sides verdict. */
8317
8409
  function isaInconsistencyRefusal(posFact, disjointFact) {
8318
- const cite = (f) => `${factPhrase(f)}${f.provenance ? ` (source: ${citationProvenance(f.provenance)})` : ""}`;
8319
8410
  return {
8320
- text: `you've told me both ${cite(posFact)} and ${cite(disjointFact)} — together those contradict, and I won't derive an answer from an inconsistency. `
8411
+ text: `you've told me both ${citedFactPhrase(posFact)} and ${citedFactPhrase(disjointFact)} — together those contradict, and I won't derive an answer from an inconsistency. `
8321
8412
  + `To settle it, say "forget that ${posFact.subject} is ${indefiniteArticleFor(posFact.object)} ${posFact.object}".`,
8322
8413
  replace: true,
8323
8414
  };
@@ -8327,21 +8418,22 @@ function isaInconsistencyRefusal(posFact, disjointFact) {
8327
8418
  * an ordered list of
8328
8419
  * premise Fact rows as one continuous argument — "cache is a kind of store;
8329
8420
  * store is a kind of component; so redis.mjs is a component" — each premise
8330
- * cited via the SAME factPhrase + "(source: …)" convention renderFactLine
8331
- * uses, just without its "you told me"/"i learned" framing (a chain reads as
8332
- * one derivation, not a list of standalone recollections). The conclusion
8333
- * clause is spelled directly from the first premise's subject and the last
8334
- * premise's object — sound for any chain length, though today's only caller
8335
- * (the live cax-sco/scm-sco chase below) ever passes exactly two. */
8421
+ * cited through citedFactPhrase, the SAME caveat + "(source: …)" convention
8422
+ * renderFactLine uses, just without its "you told me"/"i learned" framing (a
8423
+ * chain reads as one derivation, not a list of standalone recollections). The
8424
+ * conclusion clause is spelled directly from the first premise's subject and
8425
+ * the last premise's object — sound for any chain length, though today's only
8426
+ * caller (the live cax-sco/scm-sco chase below) ever passes exactly two. */
8336
8427
  function renderIsaChain(premises) {
8337
- const step = (f) => `${factPhrase(f)}${f.provenance ? ` (source: ${citationProvenance(f.provenance)})` : ""}`;
8338
8428
  const first = premises[0];
8339
8429
  const last = premises[premises.length - 1];
8340
- return `${premises.map(step).join("; ")}; so ${first.subject} is a ${last.object}`;
8430
+ return `${premises.map((f) => citedFactPhrase(f)).join("; ")}; so ${first.subject} is a ${last.object}`;
8341
8431
  }
8342
8432
 
8343
8433
  /** Read every reified Fact out of the memory graph as plain {subject, predicate,
8344
- * object, provenance} rows. Lazy + failure-tolerated: no memory → []. */
8434
+ * object, provenance} rows, each carrying `extraction` when its own record
8435
+ * recorded a finding, so a line rendered off this reader declares the same
8436
+ * caveat a readFactRows row would. Lazy + failure-tolerated: no memory → []. */
8345
8437
  async function memoryFacts(memoryDir) {
8346
8438
  try {
8347
8439
  const { loadMemory } = await import("../adapters/memory/core.mjs");
@@ -8350,7 +8442,11 @@ async function memoryFacts(memoryDir) {
8350
8442
  for (const ind of m.individuals || []) {
8351
8443
  if (ind?.class !== "Fact") continue;
8352
8444
  const get = (k) => (ind.attributes || []).find((a) => a.key === k)?.value || "";
8353
- out.push({ subject: get("subject"), predicate: get("predicate"), object: get("object"), provenance: get("provenance") });
8445
+ const extraction = get("extraction").split(" ").filter(Boolean);
8446
+ out.push({
8447
+ subject: get("subject"), predicate: get("predicate"), object: get("object"), provenance: get("provenance"),
8448
+ ...(extraction.length ? { extraction } : {}),
8449
+ });
8354
8450
  }
8355
8451
  return out;
8356
8452
  } catch {
@@ -9001,7 +9097,7 @@ function renderIsaCite(chain, facts) {
9001
9097
  (f) => f.predicate === step.predicate && f.subject === step.subject && f.object === step.object,
9002
9098
  ));
9003
9099
  if (!steps.length || !steps.every(Boolean)) return null;
9004
- return steps.map((g) => `${factPhrase(g)}${g.provenance ? ` (source: ${citationProvenance(g.provenance)})` : ""}`).join("; ");
9100
+ return steps.map((g) => citedFactPhrase(g)).join("; ");
9005
9101
  }
9006
9102
 
9007
9103
  /** THE capability answer — every reader that asks "can X do Y" renders through
@@ -9253,7 +9349,23 @@ function uniqueFacts(rows) {
9253
9349
  * it as its own "Goal (inferred)" line; every other consumer reads named
9254
9350
  * fields and is unaffected. */
9255
9351
  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);
9352
+ return withEnumerationLane(
9353
+ withDeducedGoal(await factAnswerReaders(memoryDir, query, envelope, miss, biasByBundle, cache, focusLabel), envelope, query),
9354
+ ENUMERATION_LANES.FACT_SET,
9355
+ );
9356
+ }
9357
+
9358
+ /** Stamp the enumeration lane on a fact reader's return when its answer reports
9359
+ * a set's extent, so the corpus-scope trailer can find it.
9360
+ *
9361
+ * Both cascades below render their hits the same way — a capped list of fact
9362
+ * lines plus a held remainder — across twenty-odd return sites. Deciding here,
9363
+ * from the rendered answer, rather than tagging each site keeps one rule in
9364
+ * one place, and covers a reader added to either cascade later. */
9365
+ function withEnumerationLane(res, lane) {
9366
+ if (!res || res.miss || typeof res.text !== "string") return res;
9367
+ if (!answerAssertsASet(res.text, res)) return res;
9368
+ return { ...res, enumerationLane: lane };
9257
9369
  }
9258
9370
 
9259
9371
  /** Attach the additive `goal` field to a fact reader's return: the same
@@ -9664,7 +9776,7 @@ async function factAnswerReaders(memoryDir, query, envelope, miss, biasByBundle
9664
9776
  if (declined) return declined;
9665
9777
  const steps = order.slice(0, -1).map((n, i) => pairs.find((f) => f.subject === n && f.object === order[i + 1]));
9666
9778
  if (steps.every(Boolean)) {
9667
- const cite = steps.map((g) => `${factPhrase(g)}${g.provenance ? ` (source: ${citationProvenance(g.provenance)})` : ""}`).join("; ");
9779
+ const cite = steps.map((g) => citedFactPhrase(g)).join("; ");
9668
9780
  return { text: `${order[0]} — ${cite}; so ${order[0]} is the ${supWord} ${kindSingular}`, replace: true };
9669
9781
  }
9670
9782
  }
@@ -10389,7 +10501,7 @@ async function factAnswerReaders(memoryDir, query, envelope, miss, biasByBundle
10389
10501
  if (!chain || chain.length < 2) return renderFactLine(f);
10390
10502
  const steps = chain.map(rowForStep);
10391
10503
  if (!steps.every(Boolean)) return renderFactLine(f);
10392
- const cite = steps.map((g) => `${factPhrase(g)}${g.provenance ? ` (source: ${citationProvenance(g.provenance)})` : ""}`).join("; ");
10504
+ const cite = steps.map((g) => citedFactPhrase(g)).join("; ");
10393
10505
  return `${renderFactLine(f)} — via: ${cite}`;
10394
10506
  });
10395
10507
  const shown = lines.slice(0, FACT_ANSWER_CAP);
@@ -11017,7 +11129,10 @@ function inheritsChain(graph, startId) {
11017
11129
  * plus factAnswer's same additive `goal` field when one is deducible
11018
11130
  * (withDeducedGoal). */
11019
11131
  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);
11132
+ return withEnumerationLane(
11133
+ withDeducedGoal(await factReadBackReaders(memoryDir, query, envelope, miss, graph, focusLabel, biasByBundle, cache), envelope, query),
11134
+ ENUMERATION_LANES.FACT_READBACK,
11135
+ );
11021
11136
  }
11022
11137
 
11023
11138
  async function factReadBackReaders(memoryDir, query, envelope, miss, graph = null, focusLabel = null, biasByBundle = {}, cache = null) {
@@ -11466,7 +11581,7 @@ async function factReadBackReaders(memoryDir, query, envelope, miss, graph = nul
11466
11581
  const key = af.id || `${af.subject}|${af.predicate}|${af.object}`;
11467
11582
  if (seenAlias.has(key)) continue;
11468
11583
  seenAlias.add(key);
11469
- parts.push(`${factPhrase(af)}${af.provenance ? ` (source: ${citationProvenance(af.provenance)})` : ""}`);
11584
+ parts.push(citedFactPhrase(af));
11470
11585
  }
11471
11586
  }
11472
11587
  return `${node.entity} — ${parts.join("; ")}`;
@@ -11649,7 +11764,7 @@ async function factReadBackReaders(memoryDir, query, envelope, miss, graph = nul
11649
11764
  const kindEcho = stripTrailingDiscourseTag(isaAsk[2]).trim();
11650
11765
  const chain = [posFact, ...(objFact ? [objFact] : [])].map(renderFactLine).join("; ");
11651
11766
  return {
11652
- text: `no — ${chain}; and ${factPhrase(disjointFact)}${disjointFact.provenance ? ` (source: ${citationProvenance(disjointFact.provenance)})` : ""} `
11767
+ text: `no — ${chain}; and ${citedFactPhrase(disjointFact)} `
11653
11768
  + `— so ${isaSubject} can never be ${indefiniteArticleFor(kindEcho)} ${kindEcho}.`,
11654
11769
  replace: true,
11655
11770
  };
@@ -13149,19 +13264,67 @@ async function cleanMissLiveKey(term, { graph, memoryDir, lexicon, cache }) {
13149
13264
  return key;
13150
13265
  }
13151
13266
 
13267
+ /** The name a live source goes by in a breaker and in the skipped-source note.
13268
+ * A registered stub with no name of its own answers to this one, so a test
13269
+ * provider is guarded exactly as the shipped one is. */
13270
+ const LIVE_SOURCE_FALLBACK_NAME = "wikipedia";
13271
+
13272
+ /** Runs one live-source lookup behind that source's circuit breaker, so a
13273
+ * source that keeps timing out is skipped for the rest of the session
13274
+ * instead of being asked again every turn. A skipped source adds its name to
13275
+ * `sourceSkips` and answers null, which is the same shape a miss already
13276
+ * takes — the turn proceeds byte-identically, and the answer says the source
13277
+ * was not asked. */
13278
+ async function throughLiveSourceBreaker(provider, sourceSkips, work) {
13279
+ const source = String(provider?.name || LIVE_SOURCE_FALLBACK_NAME);
13280
+ const systemicFailuresOf = typeof provider?.stats === "function"
13281
+ ? () => provider.stats().systemicFailures ?? 0
13282
+ : null;
13283
+ return throughSourceBreaker(source, work, { skipped: sourceSkips, label: provider?.label, systemicFailuresOf });
13284
+ }
13285
+
13152
13286
  /** The live Wikipedia lookup for an already-gated key: the article, or null
13153
- * (toggle-off provider, network failure, throttle, drift-guard rejection —
13154
- * all byte-identical to a live-off run). `onLiveLookup` is a notify-only
13155
- * hook (the web page's "searching wikipedia…" statusline); its own failure
13156
- * is swallowed too. */
13157
- async function liveReferenceAnswerForKey(key, onLiveLookup) {
13158
- try { if (typeof onLiveLookup === "function") onLiveLookup(key); } catch { /* notify-only */ }
13287
+ * (toggle-off provider, network failure, throttle, drift-guard rejection,
13288
+ * a breaker-skipped source — all byte-identical to a live-off run).
13289
+ * `onLiveLookup` is a notify-only hook (the web page's "searching
13290
+ * wikipedia…" statusline); its own failure is swallowed too. */
13291
+ async function liveReferenceAnswerForKey(key, onLiveLookup, sourceSkips = null) {
13292
+ const provider = getLiveReferenceProvider();
13159
13293
  let article = null;
13160
- try { article = await getLiveReferenceProvider().lookup(key); } catch { article = null; }
13294
+ try {
13295
+ article = await throughLiveSourceBreaker(provider, sourceSkips, async () => {
13296
+ try { if (typeof onLiveLookup === "function") onLiveLookup(key); } catch { /* notify-only */ }
13297
+ // The fetch budget covers this lookup: the search and the read it needs,
13298
+ // and nothing like a retry loop past them.
13299
+ try { provider.beginTurn?.(); } catch { /* an older provider has no budget */ }
13300
+ try { return await provider.lookup(key); } catch { return null; }
13301
+ });
13302
+ } catch { article = null; }
13161
13303
  if (!article) return null;
13162
13304
  return { key, article, text: renderLiveReferenceAnswer(key, article) };
13163
13305
  }
13164
13306
 
13307
+ /** The research lane's provider with its source's breaker in front of every
13308
+ * fetching method. A skipped source answers null to all three, which is the
13309
+ * lane's own "the source had nothing" path, so a run pauses honestly instead
13310
+ * of walking a queue against a dead source. The contract fields the lane
13311
+ * reads (name, origin, provenanceTag) pass straight through. */
13312
+ function guardedResearchProvider(provider, sourceSkips) {
13313
+ if (!provider) return provider;
13314
+ try { provider.beginTurn?.(); } catch { /* an older provider has no budget */ }
13315
+ const guard = (work) => throughLiveSourceBreaker(provider, sourceSkips, work);
13316
+ return {
13317
+ ...provider,
13318
+ lookup: (term) => guard(() => provider.lookup(term)),
13319
+ ...(typeof provider.pageByTitle === "function"
13320
+ ? { pageByTitle: (title) => guard(() => provider.pageByTitle(title)) }
13321
+ : {}),
13322
+ ...(typeof provider.linkedTitles === "function"
13323
+ ? { linkedTitles: (title, options) => guard(() => provider.linkedTitles(title, options)) }
13324
+ : {}),
13325
+ };
13326
+ }
13327
+
13165
13328
  /** The child-pack half of learn-on-miss, for an already-gated key: look the
13166
13329
  * key up in the shipped child triples pack and append every fact under child
13167
13330
  * provenance, so the SAME question can be re-asked from the store. Null on a
@@ -14958,7 +15121,7 @@ const ARCH_OVERVIEW_PHRASES = [
14958
15121
  new RegExp(`^${ARCH_OVERVIEW_LEAD}(?:(?:an?|the)\\s+)?(?:overview|map|diagram)\\s+${ARCH_OVERVIEW_OF_REPO}(?:\\s+here)?\\??$`, "i"),
14959
15122
  ];
14960
15123
 
14961
- async function runAsk(query, { config, source, graph, focus, last, templates, memoryDir, sessionId = "", lexicon = null, env, trace, vocabHint: sessionVocabHint = null, tel = null, biasByBundle = {}, cache = null, vocabAntecedent = null, planHolder = null, discourseHolder = null, gameConfig = DEFAULT_GAME_CONFIG, liveReference = false, onLiveLookup = null, uiContext = "cli", synthesisBudget = AUTO_SYNTHESIS_BUDGET, codeDomainActive = false }) {
15124
+ async function runAsk(query, { config, source, graph, focus, last, templates, memoryDir, sessionId = "", lexicon = null, env, trace, vocabHint: sessionVocabHint = null, tel = null, biasByBundle = {}, cache = null, vocabAntecedent = null, planHolder = null, discourseHolder = null, gameConfig = DEFAULT_GAME_CONFIG, liveReference = false, onLiveLookup = null, sourceSkips = null, uiContext = "cli", synthesisBudget = AUTO_SYNTHESIS_BUDGET, codeDomainActive = false }) {
14962
15125
  // The session-wide hint names a term this session can PROVE resolves; when
14963
15126
  // the question itself named a subject the lexicon knows, the hint names that
14964
15127
  // instead, so a miss on "how many eyes does a human have" points at "human"
@@ -15171,7 +15334,7 @@ async function runAsk(query, { config, source, graph, focus, last, templates, me
15171
15334
  }
15172
15335
  let liveKey = null;
15173
15336
  try { liveKey = cleanMissLiveTerm(wikiTerm, lexicon ?? undefined); } catch { liveKey = null; }
15174
- const live = liveKey ? await liveReferenceAnswerForKey(liveKey, onLiveLookup) : null;
15337
+ const live = liveKey ? await liveReferenceAnswerForKey(liveKey, onLiveLookup, sourceSkips) : null;
15175
15338
  if (live) {
15176
15339
  await ingestReferenceArticle(memoryDir, live.key, live.article, cache, liveProvenanceTag, lexicon, synthesisBudget);
15177
15340
  note(trace, `lane: WIKIPEDIA ASK — answered from a live en.wikipedia.org lookup, cited (article "${live.article.title}", revid ${live.article.revid})`);
@@ -15470,6 +15633,9 @@ async function runAsk(query, { config, source, graph, focus, last, templates, me
15470
15633
  let via = "composed";
15471
15634
  let recordMiss = miss;
15472
15635
  let factPending = null; // a truncated fact listing's held remainder (for "more" paging)
15636
+ // Set by the lanes here whose answer reports a set's extent, and read by the
15637
+ // corpus-scope trailer. Null on every point answer and every miss.
15638
+ let enumerationLane = null;
15473
15639
  // Set when the memory-facts lane (W4, below) answered from a corpus-weak-only
15474
15640
  // hit set (factAnswer's KNOW_ABOUT_RE reader, `weakOnly`) — the hedged
15475
15641
  // "possibly" answer still stands as `answer`, but `via` is deliberately left
@@ -15524,6 +15690,7 @@ async function runAsk(query, { config, source, graph, focus, last, templates, me
15524
15690
  // A cold "what else" carries miss:true — it resolved no subject, so the
15525
15691
  // turn is a miss in better words, exactly like the isa ladder's closers.
15526
15692
  answer = whatElse.text; via = "fact:what-else"; recordMiss = whatElse.miss ?? false; handled = true;
15693
+ if (!recordMiss) enumerationLane = ENUMERATION_LANES.WHAT_ELSE;
15527
15694
  if (whatElse.pending) factPending = whatElse.pending;
15528
15695
  deduced = "surface additional remembered facts beyond the primary definition";
15529
15696
  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\"");
@@ -15843,7 +16010,7 @@ async function runAsk(query, { config, source, graph, focus, last, templates, me
15843
16010
  // exactly as a live-off run would.
15844
16011
  if (!bareMetaHit && liveReference && refTerm) {
15845
16012
  const liveKey = await cleanMissLiveKey(refTerm, { graph, memoryDir, lexicon, cache });
15846
- const live = liveKey ? await liveReferenceAnswerForKey(liveKey, onLiveLookup) : null;
16013
+ const live = liveKey ? await liveReferenceAnswerForKey(liveKey, onLiveLookup, sourceSkips) : null;
15847
16014
  if (live) bareMetaHit = { text: live.text, replace: true, live };
15848
16015
  }
15849
16016
  }
@@ -16058,6 +16225,7 @@ async function runAsk(query, { config, source, graph, focus, last, templates, me
16058
16225
  if (!fact.miss && !fact.weakOnly) {
16059
16226
  via = "fact";
16060
16227
  recordMiss = false;
16228
+ if (fact.enumerationLane) enumerationLane = fact.enumerationLane;
16061
16229
  } else if (fact.weakOnly) {
16062
16230
  factLaneWeakOnly = true;
16063
16231
  }
@@ -16192,11 +16360,23 @@ async function runAsk(query, { config, source, graph, focus, last, templates, me
16192
16360
  // (4) #2 TEACH lane — a teach-shaped would-miss nothing above answered: route to
16193
16361
  // memory, or say what CAN be remembered (LOUD), never the wall / a silent drop.
16194
16362
  if (miss && recordMiss && via === "composed") {
16195
- const taught = await teachLane(query, { memoryDir, sessionId, lexicon, cache, planHolder, graph, gameConfig });
16363
+ // A store that refuses the write is reported as itself. Left to fall
16364
+ // through, every frame in the lane declines in turn and the answer blames
16365
+ // the vocabulary for something the vocabulary had nothing to do with.
16366
+ let taught = null;
16367
+ try {
16368
+ taught = await teachLane(query, { memoryDir, sessionId, lexicon, cache, planHolder, graph, gameConfig });
16369
+ } catch (error) {
16370
+ if (!isPersistUnavailable(error)) throw error;
16371
+ taught = persistUnavailableAnswer();
16372
+ }
16196
16373
  if (taught) {
16197
16374
  answer = taught.text; via = taught.via; recordMiss = taught.miss;
16198
16375
  if (!taught.miss) dialogueLaneOverride = "teach";
16199
- note(trace, `lane: (4) TEACH — TEACH_RE/OWNS_TEACH_RE/BARE_DECLARATIVE_RE matched, ${taught.miss ? "but the payload could not be stored" : "reified into .tmct/memory"}`);
16376
+ const teachOutcome = taught.via === PERSIST_UNAVAILABLE_VIA ? "but the store would not take the write"
16377
+ : taught.miss ? "but the payload could not be stored"
16378
+ : "reified into .tmct/memory";
16379
+ note(trace, `lane: (4) TEACH — TEACH_RE/OWNS_TEACH_RE/BARE_DECLARATIVE_RE matched, ${teachOutcome}`);
16200
16380
  // `deduced` was computed straight off envelope.parsed alone, but the
16201
16381
  // structural grammar has no business parsing a teach-shaped sentence at
16202
16382
  // all, so it would otherwise be confidently WRONG or silently absent.
@@ -16397,6 +16577,7 @@ async function runAsk(query, { config, source, graph, focus, last, templates, me
16397
16577
  answer = fact.replace ? fact.text : `${answer}\n${fact.text}`;
16398
16578
  via = "fact";
16399
16579
  recordMiss = false;
16580
+ if (fact.enumerationLane) enumerationLane = fact.enumerationLane;
16400
16581
  if (fact.pending) factPending = fact.pending;
16401
16582
  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
16583
  note(trace, `source: child pack ${CHILD_PACK_NAME} — ${learned.count} fact(s) appended as ${childProvenanceTag(key)}, answer served from .tmct/memory Facts`);
@@ -16420,7 +16601,7 @@ async function runAsk(query, { config, source, graph, focus, last, templates, me
16420
16601
  // miss byte-identical to a live-off run.
16421
16602
  if (miss && recordMiss && via === "composed" && liveReference && refTerm) {
16422
16603
  const liveKey = await cleanMissLiveKey(refTerm, { graph, memoryDir, lexicon, cache });
16423
- const live = liveKey ? await liveReferenceAnswerForKey(liveKey, onLiveLookup) : null;
16604
+ const live = liveKey ? await liveReferenceAnswerForKey(liveKey, onLiveLookup, sourceSkips) : null;
16424
16605
  if (live) {
16425
16606
  answer = live.text;
16426
16607
  via = "reference";
@@ -16635,7 +16816,7 @@ async function runAsk(query, { config, source, graph, focus, last, templates, me
16635
16816
  || (liveReference === "always" ? envelope?.parsed?.object : null);
16636
16817
  let liveKey = null;
16637
16818
  try { liveKey = supplementTerm ? cleanMissLiveTerm(supplementTerm, lexicon ?? undefined) : null; } catch { liveKey = null; }
16638
- const live = liveKey ? await liveReferenceAnswerForKey(liveKey, onLiveLookup) : null;
16819
+ const live = liveKey ? await liveReferenceAnswerForKey(liveKey, onLiveLookup, sourceSkips) : null;
16639
16820
  if (live) {
16640
16821
  answer = `${answer}\nWikipedia adds: ${live.text}`;
16641
16822
  await ingestReferenceArticle(memoryDir, live.key, live.article, cache, liveProvenanceTag, lexicon, synthesisBudget);
@@ -16646,6 +16827,15 @@ async function runAsk(query, { config, source, graph, focus, last, templates, me
16646
16827
  // turn "asked about" (the SchemaClass meta-node is documentation, not a code entity),
16647
16828
  // so record + expand them, not the schema match.
16648
16829
  const finalAnsweredIds = conceptInstances ? conceptInstances.map((i) => i.id) : answeredIds;
16830
+ // `lane`: the dialogue-act lane — a lane's own override, else the
16831
+ // question-shape lookup — resolved to an ISO act by runTurn's withLast.
16832
+ const lane = dialogueLaneOverride ?? askDialogueLane(envelope?.parsed, query, recordMiss);
16833
+ // A set question answered out of the fact store reports a set's extent even
16834
+ // when the set turned out to hold one member, so the question's own shape
16835
+ // decides here and the rendered-answer rule only widens it.
16836
+ if (!enumerationLane && !recordMiss && via === "fact" && lane === "ask-set") {
16837
+ enumerationLane = ENUMERATION_LANES.FACT_SET;
16838
+ }
16649
16839
  const record = {
16650
16840
  type: "turn", ts, query, via, resolvedIds, answeredIds: finalAnsweredIds, miss: recordMiss,
16651
16841
  // English gloss + machine-parsable notation — off ask.mjs's own
@@ -16655,6 +16845,9 @@ async function runAsk(query, { config, source, graph, focus, last, templates, me
16655
16845
  // Premise-derived trust for a LIVE-CHASE-ONLY entailment answer; omitted
16656
16846
  // entirely when this turn didn't answer via one of those.
16657
16847
  ...(entailedTrust !== null ? { entailedTrust } : {}),
16848
+ // Set only when this answer reports a set's extent — the corpus-scope
16849
+ // trailer's own gate. Absent on a point answer and on every miss.
16850
+ ...(enumerationLane && !recordMiss ? { enumerationLane } : {}),
16658
16851
  // The automatic /prove fallback's own budget wall — the same marker
16659
16852
  // /prove's own explicit budget wall stamps, so chatbench/infbench can
16660
16853
  // count a budget miss apart from a parse miss.
@@ -16688,21 +16881,21 @@ async function runAsk(query, { config, source, graph, focus, last, templates, me
16688
16881
  // `goal`: the SAME deduced string the debug trace's own "goal:" line
16689
16882
  // carries. Only runAsk ever sets this field, so the always-on goal line is
16690
16883
  // 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
16884
  return { answer, logLines, record, focus: newFocus, detail, effectiveQuery, goal: deduced, lane, ...(planResult ? { plan: planResult } : {}) };
16695
16885
  }
16696
16886
 
16697
16887
  /** A non-ask, non-dispatch chat turn (count answer, /stats) — the same
16698
16888
  * { 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 } = {}) {
16889
+ function plainTurn(query, answer, { command, via = "composed", miss = false, focus = null, canonical = null, goal = null, enumerationLane = null } = {}) {
16700
16890
  const ts = new Date().toISOString();
16701
16891
  return {
16702
16892
  answer,
16703
16893
  logLines: [ts, `> ${query}`, answer, ""],
16704
16894
  record: {
16705
16895
  type: "turn", ts, query, ...(command ? { command } : {}), via, resolvedIds: [], answeredIds: [], miss,
16896
+ // Set only by the lanes whose answers report a set's extent. Absent
16897
+ // everywhere else, so a point answer never grows a corpus-scope line.
16898
+ ...(enumerationLane ? { enumerationLane } : {}),
16706
16899
  // See runAsk's own `record.canonical`; `null` is the honest default
16707
16900
  // here (a bare command confirmation, an orientation card, a count).
16708
16901
  canonical,
@@ -17607,7 +17800,8 @@ async function assertTurn(line, { memoryDir, sessionId, focus, lexicon = null, c
17607
17800
  .join(", "),
17608
17801
  };
17609
17802
  return plainTurn(line, answer, { command: "assert", via: "assert", focus, canonical, goal: "teach/remember a new fact" });
17610
- } catch {
17803
+ } catch (error) {
17804
+ rethrowPersistFailure(error);
17611
17805
  return null; // grammar unavailable / write failed — fall through to the engine
17612
17806
  }
17613
17807
  }
@@ -18331,14 +18525,26 @@ async function answerWithoutFillerPrefix(input, options, missed) {
18331
18525
  export async function runTurn(input, options = {}) {
18332
18526
  const memoryDir = options?.memoryDir ?? null;
18333
18527
  const before = await factRowSnapshot(memoryDir);
18334
- let result = await dispatchTurn(input, options);
18335
- const rescued = await answerWithoutFillerPrefix(input, options, result);
18336
- if (rescued) result = rescued;
18528
+ let result;
18529
+ try {
18530
+ result = await dispatchTurn(input, options);
18531
+ const rescued = await answerWithoutFillerPrefix(input, options, result);
18532
+ if (rescued) result = rescued;
18533
+ } catch (error) {
18534
+ // Every write lane the dispatcher reaches — a rule teach, a retraction, a
18535
+ // game's board snapshot — reports a refused store the same way the teach
18536
+ // lane does. A rejected input is a different thing and travels on,
18537
+ // carrying the row and provenance the backend named.
18538
+ if (!isPersistUnavailable(error)) throw error;
18539
+ result = plainTurn(String(input ?? "").trim(), PERSIST_UNAVAILABLE_TEXT, {
18540
+ via: PERSIST_UNAVAILABLE_VIA, miss: true, focus: options?.focus ?? null,
18541
+ });
18542
+ }
18337
18543
  if (!result || typeof result !== "object") return result;
18338
18544
  return { ...result, factsTouched: await factsTouchedSince(memoryDir, before) };
18339
18545
  }
18340
18546
 
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 } = {}) {
18547
+ 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
18548
  // Every game's tuning knobs (spider-fly's mass economy, guess-the-number's
18343
18549
  // bounds, the shared plan lane's search-depth cap) — a caller's own
18344
18550
  // gameConfig (chat-session.mjs resolves one per session from tmct.toml)
@@ -18431,7 +18637,11 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
18431
18637
  // an answer's typed content is in hand (runAsk, off the ask envelope's
18432
18638
  // `discourse` referents); the caller re-threads whatever comes back.
18433
18639
  const discourseHolder = { record: discourse ?? emptyDiscourseRecord() };
18434
- const ctx = { config, source, graph, focus, last, memoryDir, sessionId, templates, env, lexicon, trace, narrate, liveReference, researchSource, onLiveLookup, vocabHint: resolvedVocabHint, tel, biasByBundle, cache: factRowsCache, vocabAntecedent, planHolder, discourseHolder, gameConfig: resolvedGameConfig, uiContext, synthesisBudget, codeDomainActive: domainActive, laneVocab: laneVocabValue, domainPacks: domainPacksValue, newsState, newsConfig, newsProviders };
18640
+ // Every external source this turn asked for and did not get, because its
18641
+ // circuit breaker had already given up on it. A name lands here only when
18642
+ // the skip changed what served the answer, and the trailer says so.
18643
+ const sourceSkips = new Set();
18644
+ const ctx = { config, source, graph, focus, last, memoryDir, sessionId, templates, env, lexicon, trace, narrate, liveReference, researchSource, onLiveLookup, sourceSkips, vocabHint: resolvedVocabHint, tel, biasByBundle, cache: factRowsCache, vocabAntecedent, planHolder, discourseHolder, gameConfig: resolvedGameConfig, uiContext, synthesisBudget, codeDomainActive: domainActive, laneVocab: laneVocabValue, domainPacks: domainPacksValue, newsState, newsConfig, newsProviders };
18435
18645
  // A DISPATCHED turn (count / slash-command / ask) becomes the new "last
18436
18646
  // answer" that why/say-more re-renders; a conversational turn does not.
18437
18647
  // Every dispatched turn's result passes through finish() here — the LAST
@@ -18484,7 +18694,7 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
18484
18694
  // Goal/canonical lines append onto the PRE-narration `finished` result
18485
18695
  // `nextLast` was captured from, so a narrated turn still gets both short
18486
18696
  // lines up top plus the full trace block after.
18487
- return { ...withNarration(withCanonicalLine(withGoalLine(finished)), trace, fallbackGoal), last: nextLast, discourse: discourseHolder.record };
18697
+ return { ...withNarration(withCanonicalLine(withGoalLine(withSourceSkipNote(withRetrievalNote(finished, retrieval), sourceSkips))), trace, fallbackGoal), last: nextLast, discourse: discourseHolder.record };
18488
18698
  };
18489
18699
 
18490
18700
  // Slash-optional system commands: a bare leading command word ("stats",
@@ -18665,7 +18875,10 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
18665
18875
  holder: researchHolder,
18666
18876
  memoryDir,
18667
18877
  lexicon,
18668
- provider: getResearchProvider({ minIntervalMs: resolvedResearchConfig.minIntervalMs, source: effectiveResearchSource }),
18878
+ provider: guardedResearchProvider(
18879
+ getResearchProvider({ minIntervalMs: resolvedResearchConfig.minIntervalMs, source: effectiveResearchSource }),
18880
+ sourceSkips,
18881
+ ),
18669
18882
  config: { ...resolvedResearchConfig, source: effectiveResearchSource },
18670
18883
  planActive: Boolean(planHolder.state && !planHolder.state.done),
18671
18884
  pagerActive: Boolean(Array.isArray(last?.detail?.pending?.items) && last.detail.pending.items.length),
@@ -18975,17 +19188,26 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
18975
19188
  // Gated on memoryDir: only a session shell provides a write target, so a bare
18976
19189
  // runTurn (tests, library callers) stays pure and falls through to the engine.
18977
19190
  if (memoryDir) {
18978
- const asserted = await assertTurn(workingLine, ctx);
19191
+ let asserted = null;
19192
+ let taxonomy = null;
19193
+ try {
19194
+ asserted = await assertTurn(workingLine, ctx);
19195
+ // Bare declarative taxonomy (hyphenated-instance membership, article-led
19196
+ // kind-of) — see bareTaxonomyTeach. Checked here because the ask engine
19197
+ // would otherwise parse these statements as inherits QUESTIONS.
19198
+ if (!asserted) taxonomy = await bareTaxonomyTeach(workingLine, ctx);
19199
+ } catch (error) {
19200
+ if (!isPersistUnavailable(error)) throw error;
19201
+ note(trace, "lane: declarative teach — the sentence parsed, but the store would not take the write");
19202
+ const refusedTurn = plainTurn(workingLine, PERSIST_UNAVAILABLE_TEXT, { via: PERSIST_UNAVAILABLE_VIA, miss: true, focus });
19203
+ return withLast(refusedTurn, "teach/remember a new fact");
19204
+ }
18979
19205
  if (asserted) {
18980
19206
  note(trace, "goal: teach/remember a new fact (declarative ACE sentence)");
18981
19207
  note(trace, "lane: assertTurn — grammar/ace.mjs parseAce matched a full triple with no residue");
18982
19208
  asserted.lane = "teach";
18983
19209
  return withLast(asserted, "teach/remember a new fact");
18984
19210
  }
18985
- // Bare declarative taxonomy (hyphenated-instance membership, article-led
18986
- // kind-of) — see bareTaxonomyTeach. Checked here because the ask engine
18987
- // would otherwise parse these statements as inherits QUESTIONS.
18988
- const taxonomy = await bareTaxonomyTeach(workingLine, ctx);
18989
19211
  if (taxonomy) {
18990
19212
  note(trace, "goal: teach/remember a new fact (bare declarative taxonomy)");
18991
19213
  note(trace, "lane: bareTaxonomyTeach — hyphenated-instance or article-led kind-of declarative, stored before the ask engine could parse it as a question");
@@ -19005,7 +19227,7 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
19005
19227
  note(trace, `goal: ${goal}`);
19006
19228
  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
19229
  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 });
19230
+ const skosTurn = plainTurn(workingLine, skos.text, { via: skos.miss ? "miss" : "fact", miss: skos.miss, focus, enumerationLane: skos.miss ? null : ENUMERATION_LANES.SKOS_NEIGHBOURHOOD });
19009
19231
  if (!skos.miss) skosTurn.goal = goal;
19010
19232
  skosTurn.lane = skos.miss ? "honest-miss" : "ask-set";
19011
19233
  return withLast(skosTurn, goal);
@@ -19021,7 +19243,7 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
19021
19243
  if (memCount != null) {
19022
19244
  note(trace, "goal: get a count of a memory-store kind (facts/utterances)");
19023
19245
  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");
19246
+ return withLast(plainTurn(workingLine, memCount, { via: "count", focus, enumerationLane: ENUMERATION_LANES.MEMORY_COUNT }), "get a count of a memory-store kind");
19025
19247
  }
19026
19248
  }
19027
19249
  // "list facts"/"list utterances"/"how many sessions are there" — enumerate the
@@ -19034,7 +19256,7 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
19034
19256
  const goal = "list or count a memory-store kind (facts/utterances/sessions/sources/rules)";
19035
19257
  note(trace, `goal: ${goal}`);
19036
19258
  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 });
19259
+ const turn = plainTurn(workingLine, memClass.text, { via: memClass.miss ? "miss" : "fact", miss: !!memClass.miss, focus, enumerationLane: memClass.miss ? null : ENUMERATION_LANES.MEMORY_CLASS });
19038
19260
  // A bare numeric count ("1 source.") stays silent here — only a real list
19039
19261
  // enumeration gets the trailer. answerMemoryClassQuery serves both shapes
19040
19262
  // through one lane. answerTaughtClassCount below is the one count lane that
@@ -19055,7 +19277,7 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
19055
19277
  const goal = "list the words I know that contain a given letter";
19056
19278
  note(trace, `goal: ${goal}`);
19057
19279
  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 });
19280
+ const turn = plainTurn(workingLine, lettered.text, { via: lettered.miss ? "miss" : "fact", miss: !!lettered.miss, focus, enumerationLane: lettered.miss ? null : ENUMERATION_LANES.LETTER_WORDS });
19059
19281
  if (!lettered.miss) turn.goal = goal;
19060
19282
  turn.lane = lettered.miss ? "honest-miss" : "ask-set";
19061
19283
  if (lettered.pending) turn.detail = { traversal: null, matches: [], pending: lettered.pending };
@@ -19072,7 +19294,7 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
19072
19294
  const goal = "list a declared collection's taught contents";
19073
19295
  note(trace, `goal: ${goal}`);
19074
19296
  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 });
19297
+ const turn = plainTurn(workingLine, collectionContents.text, { via: collectionContents.miss ? "miss" : "fact", miss: !!collectionContents.miss, focus, enumerationLane: collectionContents.miss ? null : ENUMERATION_LANES.COLLECTION_CONTENTS });
19076
19298
  if (!collectionContents.miss) turn.goal = goal;
19077
19299
  if (collectionContents.pending) turn.detail = { traversal: null, matches: [], pending: collectionContents.pending };
19078
19300
  return withLast(turn, goal);
@@ -19086,7 +19308,7 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
19086
19308
  if (taughtCount != null) {
19087
19309
  note(trace, 'goal: count the taught members of a class ("how many animals are there")');
19088
19310
  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");
19311
+ return withLast(plainTurn(workingLine, taughtCount, { via: "count", focus, enumerationLane: ENUMERATION_LANES.TAUGHT_CLASS_COUNT }), "count a taught class's members");
19090
19312
  }
19091
19313
  }
19092
19314
  // "list all animals"/"list the animals" — enumerate a taught class's members
@@ -19098,7 +19320,7 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
19098
19320
  const goal = "list the taught members of a class";
19099
19321
  note(trace, `goal: ${goal}`);
19100
19322
  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 });
19323
+ const turn = plainTurn(workingLine, memberList.text, { via: memberList.miss ? "miss" : "fact", miss: !!memberList.miss, focus, enumerationLane: memberList.miss ? null : ENUMERATION_LANES.MEMBERSHIP_LIST });
19102
19324
  if (!memberList.miss) turn.goal = goal;
19103
19325
  if (memberList.pending) turn.detail = { traversal: null, matches: [], pending: memberList.pending };
19104
19326
  return withLast(turn, goal);
@@ -19113,7 +19335,7 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
19113
19335
  const goal = "give an example of a taught class's member";
19114
19336
  note(trace, `goal: ${goal}`);
19115
19337
  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 });
19338
+ const turn = plainTurn(workingLine, memberExample.text, { via: memberExample.miss ? "miss" : "fact", miss: !!memberExample.miss, focus, enumerationLane: memberExample.miss ? null : ENUMERATION_LANES.MEMBERSHIP_EXAMPLE });
19117
19339
  if (!memberExample.miss) turn.goal = goal;
19118
19340
  return withLast(turn, goal);
19119
19341
  }