@polycode-projects/the-mechanical-code-talker 5.0.35 → 5.0.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@polycode-projects/the-mechanical-code-talker",
3
- "version": "5.0.35",
3
+ "version": "5.0.36",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "The Mechanical Code Talker (tmct) — a tolerant, offline, $0 chat surface that guides you toward precision queries about a software repository. ELIZA/PARRY-style but domain-obsessed with code. No model calls; indexes a repo on request (tmct index) or reads any producer's graph.",
@@ -30,15 +30,16 @@ const HACKER_NEWS_MIN_INTERVAL_MS = 250;
30
30
  const HACKER_NEWS_ITEM_CAP = 10;
31
31
 
32
32
  /** The ten browser-verified sources from the probe rounds (section 4.1 and
33
- * 4.2): three contemporary defaults (Wikimedia featured, Hacker News, USGS
34
- * quakes), two contemporary selectables (NYT World, Wikinews); three
33
+ * 4.2): five contemporary news feeds, every one of them polled by default
34
+ * (Wikimedia featured, Hacker News, USGS quakes, NYT World, Wikinews); three
35
35
  * knowledge-base defaults (Simple English Wikipedia, Wikidata, Wiktionary),
36
36
  * two knowledge-base selectables (DBpedia Lookup, English Wikipedia). The
37
37
  * `kind: "kb"` records describe the knowledge-base sources for the
38
38
  * registry/config/health surfaces; their actual lookups run through the
39
39
  * existing research-source seam (getResearchProvider in wikipedia-live.mjs),
40
40
  * not through createNewsFetcher below — a knowledge-base source is a
41
- * targeted term lookup, not a feed to poll. */
41
+ * targeted term lookup, not a feed to poll, so an enabled kb record arms
42
+ * enrichment and never adds a poll target. */
42
43
  export const NEWS_SOURCE_RECORDS = Object.freeze([
43
44
  {
44
45
  id: "wikimedia-featured",
@@ -86,9 +87,7 @@ export const NEWS_SOURCE_RECORDS = Object.freeze([
86
87
  licence: "personal use with attribution",
87
88
  browserVerified: "2026-08-08",
88
89
  minIntervalMs: DEFAULT_MIN_INTERVAL_MS,
89
- // The licence terms (personal, non-commercial, with attribution) sit
90
- // awkwardly on a source that would fetch without the user asking first.
91
- enabledByDefault: false,
90
+ enabledByDefault: true,
92
91
  },
93
92
  {
94
93
  id: "wikinews-published",
@@ -101,8 +100,8 @@ export const NEWS_SOURCE_RECORDS = Object.freeze([
101
100
  browserVerified: "2026-08-08",
102
101
  minIntervalMs: DEFAULT_MIN_INTERVAL_MS,
103
102
  // Wikinews' own lead story announces the Wikimedia Foundation closing
104
- // it; shipped selectable so its health row can tell users when it goes.
105
- enabledByDefault: false,
103
+ // it; its health row is what tells users the day it goes.
104
+ enabledByDefault: true,
106
105
  },
107
106
  {
108
107
  id: "simple-wikipedia",
@@ -166,7 +165,12 @@ export const NEWS_SOURCE_RECORDS = Object.freeze([
166
165
  },
167
166
  ]);
168
167
 
169
- export const DEFAULT_NEWS_SOURCE_IDS = Object.freeze(["wikimedia-featured", "hacker-news", "usgs-quakes"]);
168
+ /** The poll roster a fresh session starts with: news feeds only. */
169
+ export const DEFAULT_NEWS_SOURCE_IDS = Object.freeze([
170
+ "wikimedia-featured", "hacker-news", "usgs-quakes", "nyt-world", "wikinews-published",
171
+ ]);
172
+ /** The lookup roster enrichment walks when a term will not ground. These are
173
+ * reference works, never polled for news. */
170
174
  export const DEFAULT_NEWS_KB_IDS = Object.freeze(["simple-wikipedia", "wikidata", "wiktionary"]);
171
175
 
172
176
  const registry = new Map(NEWS_SOURCE_RECORDS.map((record) => [record.id, record]));
@@ -8,6 +8,8 @@
8
8
  import { sha256Bytes, normFactTerm } from "./hash.mjs";
9
9
  import { FACT_PREDICATE_PHRASES, predicatePhrase, factSentence } from "./fact-phrase.mjs";
10
10
  import { STOP_SET } from "./hub-terms.mjs";
11
+ import { articleFor } from "./digest/words.mjs";
12
+ import { provenanceTagToSource } from "./memory/trust.mjs";
11
13
 
12
14
  export const NEWS_HUB_HOPS = 2; // fixed by design, not a knob
13
15
 
@@ -93,11 +95,6 @@ const UNIVERSAL_QUANTIFIERS = new Set(["every", "all", "each"]);
93
95
  // lookup is something the graph asked for, not something a source reported.
94
96
  const REPORT_PROVENANCE_RE = /(?:^|:)(?:news|news-fixture):/;
95
97
 
96
- // A term the anchoring test (newsworthyHubs, below) must treat as prior
97
- // knowledge — matched at any segment boundary, including after a " | "
98
- // union, so a row folded from two assertions counts if either one does.
99
- const CORPUS_OR_TEACH_SEGMENT_RE = /(?:^|:|\|\s*)(?:corpus|teach):/;
100
-
101
98
  const hasNonEmptyArray = (value) => Array.isArray(value) && value.length > 0;
102
99
 
103
100
  // The provenance HEAD is the first whitespace-delimited token — the same cut
@@ -147,6 +144,46 @@ export function conceptTerms(rows) {
147
144
  return terms;
148
145
  }
149
146
 
147
+ // The SOURCE_PRIOR kinds a term counts as prior knowledge under
148
+ // (src/domain/memory/trust.mjs) — a seed corpus pack, a taught fact, a
149
+ // curated reference article. `referenceLive` (a live research: lookup) is
150
+ // deliberately absent: an enrichment lookup is something a hub candidate
151
+ // earned by already being a candidate, not knowledge the graph held before
152
+ // any report arrived (PLAN_NEWSWORTHINESS.md section 1.1).
153
+ const PRIOR_KNOWLEDGE_SOURCE_KINDS = new Set(["corpus", "corpusWeak", "reference", "provider", "teach"]);
154
+
155
+ /** Every subject and object term (term-whole — a two-word phrase is one
156
+ * entry, never two) touched by a row whose provenance parses to a
157
+ * PRIOR_KNOWLEDGE_SOURCE_KINDS kind. A REPORT row (`news:`/`news-fixture:`,
158
+ * REPORT_PROVENANCE_RE above) is excluded even when its own tag happens to
159
+ * resolve to the `corpus` kind — `news-fixture:` scores there so a demo
160
+ * replay never outranks a live claim (memory/trust.mjs), not because a
161
+ * fixture item is knowledge the graph held before its own report arrived; a
162
+ * row can never be prior knowledge for the very term it is reporting. Pure
163
+ * over `rows`; a caller building the entity gate memoises the result the
164
+ * same way buildTermAdjacency already is. */
165
+ export function priorTerms(rows) {
166
+ const prior = new Set();
167
+ for (const row of rows) {
168
+ if (REPORT_PROVENANCE_RE.test(String(row.provenance || ""))) continue;
169
+ const kind = provenanceTagToSource(row.provenance)?.kind;
170
+ if (!kind || !PRIOR_KNOWLEDGE_SOURCE_KINDS.has(kind)) continue;
171
+ const s = normFactTerm(row.subject);
172
+ const o = normFactTerm(row.object);
173
+ if (s) prior.add(s);
174
+ if (o) prior.add(o);
175
+ }
176
+ return prior;
177
+ }
178
+
179
+ /** True when `term` never appears in `prior` — priorTerms' own absence
180
+ * check, taken term-whole. */
181
+ export function isNovelTerm(term, prior) {
182
+ const t = normFactTerm(term);
183
+ if (!t) return false;
184
+ return prior instanceof Set ? !prior.has(t) : !new Set(prior).has(t);
185
+ }
186
+
150
187
  const BARE_NUMBER_RE = /^-?[£$€]?\d[\d,]*(?:\.\d+)?%?$/;
151
188
  const ISO_DATE_RE = /^\d{4}-\d{2}(-\d{2})?$/;
152
189
  const QUARTER_RE = /^q[1-4]\s+\d{4}$/i;
@@ -174,57 +211,121 @@ export function hasQuantityMarker(term) {
174
211
  return /\d/.test(String(term ?? ""));
175
212
  }
176
213
 
177
- /** scoreHubs's gated twin: from `reported` rows only, counts terms (subject
178
- * and object, STOP_SET removed) as `changed`, then keeps a term only when it
179
- * passes all three hub tests (PLAN_NEWS_FEED.md section 17.3, step two):
180
- * reported (it is why the term is a candidate at all), not a class or a bare
181
- * quantity, and anchored — either the window introduced the term outright,
182
- * or one of its own reported rows joins it to something window-new or
183
- * carrying a digit run. `rows` is the WHOLE fact set (conceptTerms and the
184
- * anchoring test both read prior knowledge from it, not just the window). */
185
- export function newsworthyHubs(rows, reported, { now, windowMs, limit = 6, adjacency = null } = {}) {
186
- const adj = adjacency ?? buildTermAdjacency(rows);
187
- const concepts = conceptTerms(rows);
188
- const nowMs = toMs(now);
189
- const startMs = nowMs - windowMs;
214
+ // The clause-fragment lead words a candidate term's own first word may not
215
+ // be — the lexical half of services/extract-facts.mjs's own
216
+ // readsAsEntityTerm, duplicated here (not imported) because the domain layer
217
+ // never imports from services, a boundary this module's own header states.
218
+ // It is also exactly what that function itself falls back to when no wink
219
+ // engine is wired in, so this is a real, already-shipped code path, not an
220
+ // approximation of one — a caller that DOES wire wink in front of the news
221
+ // gate is free to filter a candidate further before it ever reaches here.
222
+ const ENTITY_TERM_MAX_WORDS = 6;
223
+ const ENTITY_FRAGMENT_LEAD_WORDS = new Set([
224
+ "and", "or", "but", "because", "since", "although", "though", "whereas", "while", "so",
225
+ "that", "which", "who", "whom", "whose", "if", "when", "then", "also", "however",
226
+ "is", "are", "was", "were", "be", "been", "being", "am", "has", "have", "had",
227
+ "do", "does", "did", "can", "could", "will", "would", "should", "may", "might", "must",
228
+ "of", "in", "on", "at", "for", "to", "with", "from", "by", "as", "into", "onto",
229
+ "over", "under", "after", "before", "between", "during", "about", "near", "through",
230
+ "against", "among", "within", "without", "per",
231
+ ]);
232
+
233
+ /** Does `term` read as a thing's name rather than a clause fragment? Bounds
234
+ * the word count and rejects a leading conjunction, auxiliary or
235
+ * preposition (test E's condition 3, PLAN_NEWSWORTHINESS.md section 2). */
236
+ function looksLikeEntityTerm(term) {
237
+ const text = String(term ?? "").trim();
238
+ if (!text) return false;
239
+ const words = text.split(/\s+/);
240
+ if (words.length > ENTITY_TERM_MAX_WORDS) return false;
241
+ const first = words[0].toLowerCase().replace(/^[^a-z0-9]+/, "");
242
+ return Boolean(first) && !ENTITY_FRAGMENT_LEAD_WORDS.has(first);
243
+ }
190
244
 
191
- function isWindowNewTerm(term) {
192
- const idxs = adj.byTerm.get(term);
193
- if (!idxs || !idxs.length) return false;
194
- for (const idx of idxs) {
195
- const row = rows[idx];
196
- const t = rowObservedMs(row);
197
- if (!(Number.isFinite(t) && t >= startMs && t <= nowMs)) return false;
198
- if (CORPUS_OR_TEACH_SEGMENT_RE.test(String(row.provenance || ""))) return false;
199
- }
200
- return true;
245
+ // The Wikidata research provenance tag (researchSourceTag in
246
+ // adapters/corpus/research-source.mjs: `research:wikidata:<term>`) and the
247
+ // folded shape a Wikidata item id takes once normFactTerm lower-cases it —
248
+ // test A's Q-id anchor (PLAN_NEWSWORTHINESS.md section 1.1). No shipped
249
+ // source stores a raw item id as a fact's object today (wikidata-live.mjs
250
+ // resolves every claim to an English label before it reaches the graph), so
251
+ // this reads real data the day a caller stores one directly.
252
+ const WIKIDATA_RESEARCH_PROVENANCE_RE = /(?:^|:)research:wikidata:/;
253
+ const WIKIDATA_QID_TERM_RE = /^q[1-9]\d*$/;
254
+
255
+ function hasWikidataQidAnchor(term, rows) {
256
+ for (const row of rows) {
257
+ if (!WIKIDATA_RESEARCH_PROVENANCE_RE.test(String(row.provenance || ""))) continue;
258
+ const s = normFactTerm(row.subject);
259
+ const o = normFactTerm(row.object);
260
+ if (s === term && WIKIDATA_QID_TERM_RE.test(o)) return true;
261
+ if (o === term && WIKIDATA_QID_TERM_RE.test(s)) return true;
201
262
  }
263
+ return false;
264
+ }
265
+
266
+ /** The newsworthiness gate (PLAN_NEWSWORTHINESS.md section 2): from
267
+ * `reported` rows only, counts terms (subject and object, STOP_SET removed)
268
+ * as `changed`, then keeps a term only when it passes test E (a new
269
+ * entity — absent from `priorTerms(rows)`, term-whole) or test A (a fresh,
270
+ * anchored assertion about an entity the graph already holds). `rows` is
271
+ * the WHOLE fact set (conceptTerms and priorTerms both read prior knowledge
272
+ * from it, not just the reported window). `prior`, when the caller already
273
+ * computed it (buildNewsItems does), is reused rather than recomputed.
274
+ * `readsAsEntityTerm`, when the caller supplies one, replaces
275
+ * looksLikeEntityTerm — the services layer's own readsAsEntityTerm
276
+ * (extract-facts.mjs) adds a wink POS-tag check this domain-local default
277
+ * cannot, since domain never imports services; buildFeed (news.mjs) wires
278
+ * it through because it already imports that module for ingestText. */
279
+ export function newsworthyHubs(rows, reported, {
280
+ now, windowMs, limit = 6, adjacency = null, prior = null, readsAsEntityTerm = looksLikeEntityTerm,
281
+ } = {}) {
282
+ const concepts = conceptTerms(rows);
283
+ const priorSet = prior ?? priorTerms(rows);
202
284
 
203
285
  const counts = new Map();
204
- const anchors = new Map();
286
+ const subjectRowsByTerm = new Map();
205
287
  for (const row of reported) {
206
288
  const s = normFactTerm(row.subject);
207
289
  const o = normFactTerm(row.object);
208
- for (const [term, other] of [[s, o], [o, s]]) {
290
+ for (const term of [s, o]) {
209
291
  if (!term || STOP_SET.has(term)) continue;
210
292
  counts.set(term, (counts.get(term) || 0) + 1);
211
- let others = anchors.get(term);
212
- if (!others) anchors.set(term, (others = new Set()));
213
- if (other) others.add(other);
293
+ }
294
+ if (s && !STOP_SET.has(s)) {
295
+ let subjRows = subjectRowsByTerm.get(s);
296
+ if (!subjRows) subjectRowsByTerm.set(s, (subjRows = []));
297
+ subjRows.push(row);
214
298
  }
215
299
  }
216
300
 
301
+ function passesEntityTest(term) {
302
+ if (concepts.has(term) || isQuantityTerm(term)) return false;
303
+ if (!readsAsEntityTerm(term)) return false;
304
+ return isNovelTerm(term, priorSet);
305
+ }
306
+
307
+ // Section 2's own text lists no entity-shape check for test A (it reads a
308
+ // "known entity" as already established), but a malformed extraction's
309
+ // predicate remainder can BE a reported row's subject too, with nothing
310
+ // else in test A's own three-way anchor to catch it — a recognizer frame
311
+ // split across a bad triple ("bang" subject, "thong shooting" object) is
312
+ // its own novel co-term as far as test A's own anchor reads. The same
313
+ // shape check test E already needs closes that gap for test A as well.
314
+ function passesFreshAssertionTest(term) {
315
+ if (concepts.has(term) || isQuantityTerm(term)) return false;
316
+ if (!readsAsEntityTerm(term)) return false;
317
+ const subjRows = subjectRowsByTerm.get(term);
318
+ if (!subjRows || !subjRows.length) return false;
319
+ if (hasWikidataQidAnchor(term, rows)) return true;
320
+ return subjRows.some((row) => {
321
+ const object = normFactTerm(row.object);
322
+ return hasQuantityMarker(row.object) || (object && isNovelTerm(object, priorSet));
323
+ });
324
+ }
325
+
217
326
  const hubs = [];
218
327
  for (const [term, changed] of counts) {
219
- if (concepts.has(term) || isQuantityTerm(term)) continue;
220
- let anchored = isWindowNewTerm(term);
221
- if (!anchored) {
222
- for (const other of anchors.get(term) ?? []) {
223
- if (hasQuantityMarker(other) || isWindowNewTerm(other)) { anchored = true; break; }
224
- }
225
- }
226
- if (!anchored) continue;
227
- hubs.push({ term, changed });
328
+ if (passesEntityTest(term) || passesFreshAssertionTest(term)) hubs.push({ term, changed });
228
329
  }
229
330
 
230
331
  return hubs
@@ -378,7 +479,10 @@ export function renderNewsParagraph(hub, subgraphRows, { reportedIds = null } =
378
479
  .filter((r) => IDENTITY_PREDICATES.has(r.predicate))
379
480
  .map((r) => r.object)
380
481
  .sort();
381
- if (identityObjects.length) sentences.push(`${hub} is a ${joinWithAnd(identityObjects)}`);
482
+ if (identityObjects.length) {
483
+ const withArticles = identityObjects.map((object) => `${articleFor(object)} ${object}`);
484
+ sentences.push(`${hub} is ${joinWithAnd(withArticles)}`);
485
+ }
382
486
 
383
487
  for (const predicate of Object.keys(FACT_PREDICATE_PHRASES)) {
384
488
  if (IDENTITY_PREDICATES.has(predicate) || sentences.length >= SENTENCE_CAP) continue;
@@ -413,11 +517,14 @@ export function renderNewsParagraph(hub, subgraphRows, { reportedIds = null } =
413
517
  * two-hop sub-graph then splits into its own `reported`/`background` rows,
414
518
  * so a card's paragraph draws from what was reported and its collapsed
415
519
  * `backgroundParagraph` draws from what the graph already knew. */
416
- export function buildNewsItems(rows, { now, windowMs, limit = 6, sourcesByFactId = new Map() } = {}) {
520
+ export function buildNewsItems(rows, { now, windowMs, limit = 6, sourcesByFactId = new Map(), readsAsEntityTerm } = {}) {
417
521
  const reported = reportedRows(rows, { now, windowMs });
418
522
  const reportedIds = new Set(reported.map((r) => r.id));
419
523
  const adjacency = buildTermAdjacency(rows);
420
- const hubs = newsworthyHubs(rows, reported, { now, windowMs, limit, adjacency });
524
+ const prior = priorTerms(rows);
525
+ const hubOptions = { now, windowMs, limit, adjacency, prior };
526
+ if (readsAsEntityTerm) hubOptions.readsAsEntityTerm = readsAsEntityTerm;
527
+ const hubs = newsworthyHubs(rows, reported, hubOptions);
421
528
  const items = hubs.map(({ term, changed }) => {
422
529
  const subgraphRows = subgraphAround(rows, term, { adjacency });
423
530
  const factIds = subgraphRows.map((r) => r.id).sort();
@@ -179,6 +179,131 @@ export function parseAgentEditorText(text) {
179
179
  return { triples, unrecognized };
180
180
  }
181
181
 
182
+ // ---- asking ----------------------------------------------------------------
183
+ //
184
+ // The read side of the same table. `AGENT_LINE_PATTERNS` states each trait as
185
+ // a sentence; the entries below ask for one back, in the two shapes a
186
+ // relation has: FORWARD names the subject and asks for its objects ("what
187
+ // does the fox eat"), INVERSE names the object and asks which subjects state
188
+ // it ("who eats the goat"). Only the four relational predicates take an
189
+ // inverse — "who weighs 8" is not a question the actor card has a sentence
190
+ // for in either direction.
191
+ //
192
+ // `mgx:display-name` and `mgx:is-predator` carry no ask entry: their plain
193
+ // English phrasings ("what is the fox's name", "is the fox a predator") are
194
+ // the relation lane's and the type-check lane's own, and both already answer
195
+ // them from the store.
196
+
197
+ const AGENT_TRAIT_ASK_PATTERNS = [
198
+ { predicate: "mgx:consumes", direction: "forward",
199
+ re: /^(?:what|who)\s+does\s+(?:the\s+|a\s+|an\s+)?(.+?)\s+(?:want\s+to\s+)?eat[?.!\s]*$/i,
200
+ gap: (t) => `what ${t} eats` },
201
+ { predicate: "mgx:consumes", direction: "inverse",
202
+ re: /^(?:what|who)\s+eats\s+(?:the\s+|a\s+|an\s+)?(.+?)[?.!\s]*$/i,
203
+ gap: (t) => `who eats ${t}` },
204
+ { predicate: "mgx:evades", direction: "forward",
205
+ re: /^(?:what|who)\s+does\s+(?:the\s+|a\s+|an\s+)?(.+?)\s+evade[?.!\s]*$/i,
206
+ gap: (t) => `what ${t} evades` },
207
+ { predicate: "mgx:evades", direction: "inverse",
208
+ re: /^(?:what|who)\s+evades\s+(?:the\s+|a\s+|an\s+)?(.+?)[?.!\s]*$/i,
209
+ gap: (t) => `who evades ${t}` },
210
+ { predicate: "mgx:guards", direction: "forward",
211
+ re: /^(?:what|who)\s+does\s+(?:the\s+|a\s+|an\s+)?(.+?)\s+guard[?.!\s]*$/i,
212
+ gap: (t) => `what ${t} guards` },
213
+ { predicate: "mgx:guards", direction: "inverse",
214
+ re: /^(?:what|who)\s+guards\s+(?:the\s+|a\s+|an\s+)?(.+?)[?.!\s]*$/i,
215
+ gap: (t) => `who guards ${t}` },
216
+ { predicate: "mgx:pursues", direction: "forward",
217
+ re: /^(?:what|who)\s+does\s+(?:the\s+|a\s+|an\s+)?(.+?)\s+(?:pursue|chase)[?.!\s]*$/i,
218
+ gap: (t) => `what ${t} pursues` },
219
+ { predicate: "mgx:pursues", direction: "inverse",
220
+ re: /^(?:what|who)\s+(?:pursues|chases)\s+(?:the\s+|a\s+|an\s+)?(.+?)[?.!\s]*$/i,
221
+ gap: (t) => `who pursues ${t}` },
222
+ { predicate: "mgx:hasMass", direction: "forward",
223
+ re: /^(?:how\s+much|what)\s+does\s+(?:the\s+|a\s+|an\s+)?(.+?)\s+weigh[?.!\s]*$/i,
224
+ gap: (t) => `what ${t} weighs` },
225
+ { predicate: "mgx:mass-drain-per-turn", direction: "forward",
226
+ re: /^(?:how\s+much|what)\s+does\s+(?:the\s+|a\s+|an\s+)?(.+?)\s+lose\s+each\s+turn[?.!\s]*$/i,
227
+ gap: (t) => `what ${t} loses each turn` },
228
+ { predicate: "mgx:vision-radius", direction: "forward",
229
+ re: /^how\s+(?:far|many\s+cells)\s+can\s+(?:the\s+|a\s+|an\s+)?(.+?)\s+see[?.!\s]*$/i,
230
+ gap: (t) => `how far ${t} sees` },
231
+ { predicate: "mgx:model", direction: "forward",
232
+ re: /^(?:what|who)\s+does\s+(?:the\s+|a\s+|an\s+)?(.+?)\s+look\s+like[?.!\s]*$/i,
233
+ gap: (t) => `what ${t} looks like` },
234
+ ];
235
+
236
+ /** One question -> `{ predicate, direction, term, gapPhrase }`, or null when
237
+ * nothing in the ask table recognizes it. `gapPhrase` is the entry's own
238
+ * wording for what went unanswered, so a miss says which question missed
239
+ * rather than restating the raw predicate. Pure. */
240
+ export function parseAgentTraitAsk(line) {
241
+ const trimmed = String(line || "").trim();
242
+ if (!trimmed) return null;
243
+ for (const pattern of AGENT_TRAIT_ASK_PATTERNS) {
244
+ const m = trimmed.match(pattern.re);
245
+ if (!m) continue;
246
+ const term = LOW(m[1]);
247
+ if (!term) continue;
248
+ return { predicate: pattern.predicate, direction: pattern.direction, term, gapPhrase: pattern.gap(term) };
249
+ }
250
+ return null;
251
+ }
252
+
253
+ /** Whether `rows` state anything trait-shaped about `term` at all — as the
254
+ * subject of a trait row anywhere on its own class chain, or as the object
255
+ * of one. This is the gate on the whole ask family: a store that holds no
256
+ * agent traits for the term is not this table's to answer, so the question
257
+ * falls back to whatever lane owned it before. Pure. */
258
+ export function namesAgentTrait(rows, term) {
259
+ const chain = new Set(classChainOf(rows, term));
260
+ return (rows || []).some((r) => AGENT_TRAIT_PREDICATES.includes(r.predicate)
261
+ && (chain.has(r.subject) || r.object === term));
262
+ }
263
+
264
+ /** The rows answering a forward ask: `subject`'s own if it declares any,
265
+ * otherwise the nearest class link that does — the same nearest-first walk
266
+ * `traitValuesOf` resolves a value through, kept as ROWS so the answer can
267
+ * cite each one. Empty when no chain link declares the predicate. Pure. */
268
+ function traitRowsOnChain(rows, subject, predicate) {
269
+ for (const node of classChainOf(rows, subject)) {
270
+ const hits = (rows || []).filter((r) => r.subject === node && r.predicate === predicate);
271
+ if (hits.length) return hits.slice().sort(compareTraitHits);
272
+ }
273
+ return [];
274
+ }
275
+
276
+ const compareTraitHits = (a, b) => {
277
+ if (a.subject !== b.subject) return a.subject < b.subject ? -1 : 1;
278
+ return a.object < b.object ? -1 : a.object > b.object ? 1 : 0;
279
+ };
280
+
281
+ const defaultCite = (row) => (row.provenance ? ` (source: ${row.provenance})` : "");
282
+
283
+ /** Answer a parsed ask against `rows`: `{ text, miss, matches }`, or null
284
+ * when the store states no trait about the term at all (the caller keeps
285
+ * the line). A hit names the answer first and then every row it stands on,
286
+ * each cited; a subject with nothing stated under that predicate gets the
287
+ * gap said out loud, never a default filled in for it. An answer resolved
288
+ * off a class rather than the named instance says which class carried it.
289
+ * `cite` renders one row's citation, so a caller can normalize provenance
290
+ * its own way. Pure. */
291
+ export function answerAgentTraitAsk(rows, ask, { cite = defaultCite } = {}) {
292
+ if (!ask || !namesAgentTrait(rows, ask.term)) return null;
293
+ const hits = ask.direction === "forward"
294
+ ? traitRowsOnChain(rows, ask.term, ask.predicate)
295
+ : (rows || []).filter((r) => r.predicate === ask.predicate && r.object === ask.term).sort(compareTraitHits);
296
+ if (!hits.length) return { text: `nothing on record says ${ask.gapPhrase}.`, miss: true, matches: [] };
297
+
298
+ const named = [...new Set(hits.map((r) => (ask.direction === "forward" ? r.object : r.subject)))].sort();
299
+ const answeredBy = hits[0].subject;
300
+ const lead = ask.direction === "forward" && answeredBy !== ask.term
301
+ ? `from ${ask.term}'s ${answeredBy} class: `
302
+ : "";
303
+ const lines = hits.map((r) => `${agentTraitSentence(r.subject, r.predicate, r.object).replace(/\.$/, "")}${cite(r)}`);
304
+ return { text: `${named.join(", ")} — ${lead}${lines.join("; ")}.`, miss: false, matches: hits };
305
+ }
306
+
182
307
  // ---- sync planning ---------------------------------------------------------
183
308
 
184
309
  const tripleKey = (t) => `${t.subject} ${t.predicate} ${t.object}`;