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

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.33",
3
+ "version": "5.0.35",
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.",
@@ -654,3 +654,94 @@ export function routeChoiceRelation(stem) {
654
654
  }
655
655
  return null;
656
656
  }
657
+
658
+ // ---- stem topic candidates (S1) ----
659
+ //
660
+ // extractStemSourceTerm above reads ONE term off a fixed template shape, and
661
+ // when the shape a stem actually has does not match the shape a template
662
+ // expects, the capture lands in the wrong slot with nothing to catch it
663
+ // (design survey section 2.2). stemTopicCandidates instead reads every phrase
664
+ // in the stem that COULD name its topic, so the caller (chat.mjs's
665
+ // chooseChoiceTopic) can pick among them by how much the graph itself knows
666
+ // about each one, rather than by surface shape alone.
667
+
668
+ /** Words that never name a question's topic: articles, pronouns, auxiliaries,
669
+ * modals, wh-words, and the light verbs a stem uses to frame a question
670
+ * ("find", "put", "get") rather than to name its subject. A closed set, in
671
+ * the house style of every other table in this module. */
672
+ export const STEM_TOPIC_STOPWORDS = new Set([
673
+ ...PRONOUN_TERMS,
674
+ ...PHRASE_BOUNDARY_WORDS,
675
+ "a", "an", "the", "some", "any", "few", "many", "several", "more", "most",
676
+ "my", "your", "his", "its", "our", "their",
677
+ "what", "which", "where", "when", "why", "how",
678
+ "find", "found", "put", "get", "keep", "store", "place", "buy", "locate",
679
+ "hide", "wear", "carry", "use", "take", "open", "cross", "need", "want",
680
+ ]);
681
+
682
+ function stemTopicWords(text) {
683
+ return String(text ?? "").toLowerCase().split(/[^a-z'-]+/).filter(Boolean);
684
+ }
685
+
686
+ /** Every word any option's text carries — an option term is an answer
687
+ * candidate, never the topic, so it is dropped from the stem's own
688
+ * candidate list before the graph is ever asked about it. */
689
+ function optionWordSet(options) {
690
+ const words = new Set();
691
+ for (const option of options ?? []) {
692
+ for (const w of stemTopicWords(option?.text)) words.add(w);
693
+ }
694
+ return words;
695
+ }
696
+
697
+ const isUsableTopicWord = (word, optionWords) =>
698
+ word.length > 2 && !STEM_TOPIC_STOPWORDS.has(word) && !optionWords.has(word);
699
+
700
+ /**
701
+ * Every phrase in `stem` that could name what the question is about, in stem
702
+ * order, longest first at each position. Drops STEM_TOPIC_STOPWORDS members,
703
+ * words of two letters or fewer, and every word that also appears in an
704
+ * option — an option term is an answer candidate, never the topic.
705
+ *
706
+ * @param {string} stem
707
+ * @param {Array<{label: string, text: string}>} options
708
+ * @returns {Array<{ text: string, position: number, words: 1 | 2 }>}
709
+ */
710
+ export function stemTopicCandidates(stem, options) {
711
+ const optionWords = optionWordSet(options);
712
+ const words = stemTopicWords(stem);
713
+ const candidates = [];
714
+ const seen = new Set();
715
+ words.forEach((word, i) => {
716
+ if (!isUsableTopicWord(word, optionWords)) return;
717
+ const next = words[i + 1];
718
+ if (next && isUsableTopicWord(next, optionWords)) {
719
+ const text = `${word} ${next}`;
720
+ if (!seen.has(text)) { seen.add(text); candidates.push({ text, position: i, words: 2 }); }
721
+ }
722
+ if (!seen.has(word)) { seen.add(word); candidates.push({ text: word, position: i, words: 1 }); }
723
+ });
724
+ return candidates;
725
+ }
726
+
727
+ /** The stem's other content terms once `topic` is taken out: the constraints
728
+ * the question states beyond naming its subject. Same filtering as
729
+ * stemTopicCandidates, minus the topic's own words. Phase S2 reads this.
730
+ *
731
+ * @param {string} stem
732
+ * @param {string} topic
733
+ * @param {Array<{label: string, text: string}>} options
734
+ * @returns {string[]}
735
+ */
736
+ export function stemConstraintTerms(stem, topic, options) {
737
+ const optionWords = optionWordSet(options);
738
+ const topicWords = new Set(stemTopicWords(topic));
739
+ const terms = [];
740
+ const seen = new Set();
741
+ for (const word of stemTopicWords(stem)) {
742
+ if (!isUsableTopicWord(word, optionWords) || topicWords.has(word) || seen.has(word)) continue;
743
+ seen.add(word);
744
+ terms.push(word);
745
+ }
746
+ return terms;
747
+ }
@@ -50,16 +50,200 @@ function rowObservedMs(row) {
50
50
  return toMs(row.createdAt || "");
51
51
  }
52
52
 
53
+ /** Does this provenance carry a news/research tag anywhere in it? True for a
54
+ * bare `news:…` and for both ingest wrappers (`extracted:news:…`,
55
+ * `optimistic-extract:news:…`), which is what the live poll path writes. The
56
+ * window filter below and any surface counting "facts from news" read the
57
+ * same rule from here, so a tile can never drift from the feed. */
58
+ export function isNewsProvenance(provenance) {
59
+ return NEWS_WINDOW_PROVENANCE_RE.test(String(provenance || ""));
60
+ }
61
+
53
62
  export function newsWindowRows(rows, { now, windowMs }) {
54
63
  const nowMs = toMs(now);
55
64
  const startMs = nowMs - windowMs;
56
65
  return rows.filter((row) => {
57
- if (!NEWS_WINDOW_PROVENANCE_RE.test(String(row.provenance || ""))) return false;
66
+ if (!isNewsProvenance(row.provenance)) return false;
58
67
  const t = rowObservedMs(row);
59
68
  return Number.isFinite(t) && t >= startMs && t <= nowMs;
60
69
  });
61
70
  }
62
71
 
72
+ // ---------------------------------------------------------------------------
73
+ // The newsworthiness gate (PLAN_NEWS_FEED.md section 17). A card reports what
74
+ // a contemporary source said inside the window; everything the graph looked
75
+ // up, inferred or already held is background. classifyNewsRow bands a single
76
+ // row; reportedRows and newsworthyHubs narrow buildNewsItems downstream of
77
+ // newsWindowRows/scoreHubs, which keep their own behaviour unchanged.
78
+ // ---------------------------------------------------------------------------
79
+
80
+ // Identity predicates and their negative twins — what a thing IS, never what
81
+ // happened to it, so a row under any of these bands background whoever wrote
82
+ // it. Distinct from renderNewsParagraph's own narrower IDENTITY_PREDICATES
83
+ // (below), which only needs the two positive forms for its identity sentence.
84
+ const GATE_IDENTITY_PREDICATES = new Set(["rdf:type", "rdfs:subClassOf", "mgxneg:subClassOf", "owl:disjointWith"]);
85
+
86
+ // Every determiner a universal quantifier is ever stored under — today only
87
+ // "every" is written (chat.mjs's own teach lane), "all"/"each" kept here so a
88
+ // future writer of either still bands background rather than heading a card.
89
+ const UNIVERSAL_QUANTIFIERS = new Set(["every", "all", "each"]);
90
+
91
+ // A REPORT is `news:` or `news-fixture:` only — `research:` counts for the
92
+ // window (isNewsProvenance, above) but never for the gate: an enrichment
93
+ // lookup is something the graph asked for, not something a source reported.
94
+ const REPORT_PROVENANCE_RE = /(?:^|:)(?:news|news-fixture):/;
95
+
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
+ const hasNonEmptyArray = (value) => Array.isArray(value) && value.length > 0;
102
+
103
+ // The provenance HEAD is the first whitespace-delimited token — the same cut
104
+ // point trust.mjs's own provenanceTagToSource uses, so "entailed:" is read
105
+ // off the row's OWN assertion even when a union has appended a second tag
106
+ // after it.
107
+ const provenanceHead = (provenance) => String(provenance || "").trim().split(/\s+/)[0] || "";
108
+
109
+ /** "derived" | "background" | "reported" for one row, pure over the row plus
110
+ * `now` (PLAN_NEWS_FEED.md section 17.3, step one). Rules apply in order,
111
+ * first hit wins: a syllogised row is derived; an identity, universal or
112
+ * non-news-provenance row is background; a news/news-fixture row with no
113
+ * readable or in-window stamp is background; everything else is reported. */
114
+ export function classifyNewsRow(row, { now, windowMs }) {
115
+ if (provenanceHead(row.provenance).startsWith("entailed:")
116
+ || hasNonEmptyArray(row.environments) || hasNonEmptyArray(row.justification)) {
117
+ return "derived";
118
+ }
119
+ if (GATE_IDENTITY_PREDICATES.has(row.predicate)) return "background";
120
+ if (UNIVERSAL_QUANTIFIERS.has(String(row.quantifier || "").toLowerCase())) return "background";
121
+ if (!REPORT_PROVENANCE_RE.test(String(row.provenance || ""))) return "background";
122
+ const t = rowObservedMs(row);
123
+ const nowMs = toMs(now);
124
+ if (!Number.isFinite(t) || t < nowMs - windowMs || t > nowMs) return "background";
125
+ return "reported";
126
+ }
127
+
128
+ /** The "reported" subset of `rows` — counting occurrences over this set,
129
+ * rather than the wider news window, is what makes a hub's `changedCount`
130
+ * count reports rather than lookups (newsworthyHubs, below). */
131
+ export function reportedRows(rows, { now, windowMs }) {
132
+ return rows.filter((row) => classifyNewsRow(row, { now, windowMs }) === "reported");
133
+ }
134
+
135
+ /** The class objects of every identity row anywhere in `rows` — what the
136
+ * graph's own `rdf:type`/`rdfs:subClassOf` (and negative twins) rows name as
137
+ * a CLASS, regardless of who reported the identity fact. A hub test, not a
138
+ * row band: a term absent from this set is not a class by the graph's own
139
+ * account. */
140
+ export function conceptTerms(rows) {
141
+ const terms = new Set();
142
+ for (const row of rows) {
143
+ if (!GATE_IDENTITY_PREDICATES.has(row.predicate)) continue;
144
+ const t = normFactTerm(row.object);
145
+ if (t) terms.add(t);
146
+ }
147
+ return terms;
148
+ }
149
+
150
+ const BARE_NUMBER_RE = /^-?[£$€]?\d[\d,]*(?:\.\d+)?%?$/;
151
+ const ISO_DATE_RE = /^\d{4}-\d{2}(-\d{2})?$/;
152
+ const QUARTER_RE = /^q[1-4]\s+\d{4}$/i;
153
+ const LEADING_DIGIT_PHRASE_RE = /^\d[\d,.]*\s+\S/;
154
+ const TRAILING_NUMBER_PHRASE_RE = /\s\d[\d,.]*$/;
155
+
156
+ /** True when the WHOLE term is a number, a date or a quantity phrase ("q3
157
+ * 2026", "7,409 square kilometres", "1,683,115") — never a term a hub may
158
+ * head: a date is when a card happened, and an amount is what it says. */
159
+ export function isQuantityTerm(term) {
160
+ const t = String(term ?? "").trim().toLowerCase();
161
+ if (!t) return false;
162
+ if (BARE_NUMBER_RE.test(t)) return true;
163
+ if (ISO_DATE_RE.test(t)) return true;
164
+ if (QUARTER_RE.test(t)) return true;
165
+ if (LEADING_DIGIT_PHRASE_RE.test(t)) return true;
166
+ if (TRAILING_NUMBER_PHRASE_RE.test(t)) return true;
167
+ return false;
168
+ }
169
+
170
+ /** True when `term` contains a digit run anywhere — the anchor a specific
171
+ * measurement gives a seeded hub, weaker than isQuantityTerm's "the whole
172
+ * term IS a number" test. */
173
+ export function hasQuantityMarker(term) {
174
+ return /\d/.test(String(term ?? ""));
175
+ }
176
+
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;
190
+
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;
201
+ }
202
+
203
+ const counts = new Map();
204
+ const anchors = new Map();
205
+ for (const row of reported) {
206
+ const s = normFactTerm(row.subject);
207
+ const o = normFactTerm(row.object);
208
+ for (const [term, other] of [[s, o], [o, s]]) {
209
+ if (!term || STOP_SET.has(term)) continue;
210
+ 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);
214
+ }
215
+ }
216
+
217
+ const hubs = [];
218
+ 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 });
228
+ }
229
+
230
+ return hubs
231
+ .sort((a, b) => b.changed - a.changed || (a.term < b.term ? -1 : a.term > b.term ? 1 : 0))
232
+ .slice(0, limit);
233
+ }
234
+
235
+ /** A card's two-hop sub-graph, divided by the row-band gate: `reported` rows
236
+ * (what heads the card) and everything else (the collapsed background
237
+ * line). `reportedIds` is the reported-row id set the caller already
238
+ * computed over the whole fact set (reportedRows' output, by id). */
239
+ export function splitCardRows(subgraphRows, reportedIds) {
240
+ const ids = reportedIds instanceof Set ? reportedIds : new Set(reportedIds || []);
241
+ const reported = [];
242
+ const background = [];
243
+ for (const row of subgraphRows) (ids.has(row.id) ? reported : background).push(row);
244
+ return { reported, background };
245
+ }
246
+
63
247
  /** Counts window facts per term (subject and object, normalized, STOP_SET
64
248
  * removed) -> [{ term, changed }] sorted changed desc then term asc, capped
65
249
  * at `limit`. */
@@ -169,12 +353,23 @@ const SENTENCE_CAP = 5;
169
353
  * 8.3): identity first, then the hub's own relations grouped by predicate in
170
354
  * FACT_PREDICATE_PHRASES table order, then one closing sentence naming up to
171
355
  * three second-hop facts. Every sentence shown is a grounded fact, never a
172
- * paraphrase of prose the grammar could not read. */
173
- export function renderNewsParagraph(hub, subgraphRows) {
356
+ * paraphrase of prose the grammar could not read.
357
+ *
358
+ * `reportedIds` (PLAN_NEWS_FEED.md section 17.4), when given, restricts the
359
+ * relation sentences and the closing "Around it" sentence to rows in that
360
+ * set — the identity sentence keeps drawing from every row it's handed,
361
+ * since "what is this thing" is the first question a reader has regardless
362
+ * of who reported it. Defaults to null, meaning every row renders, so every
363
+ * existing caller and pin is unaffected. */
364
+ export function renderNewsParagraph(hub, subgraphRows, { reportedIds = null } = {}) {
174
365
  const hubTerm = normFactTerm(hub);
366
+ const isReported = reportedIds === null
367
+ ? () => true
368
+ : (id) => (reportedIds instanceof Set ? reportedIds.has(id) : reportedIds.includes(id));
175
369
  const hubRows = subgraphRows.filter((r) => normFactTerm(r.subject) === hubTerm);
370
+ const reportedHubRows = hubRows.filter((r) => isReported(r.id));
176
371
  const secondHopRows = subgraphRows.filter(
177
- (r) => normFactTerm(r.subject) !== hubTerm && normFactTerm(r.object) !== hubTerm,
372
+ (r) => normFactTerm(r.subject) !== hubTerm && normFactTerm(r.object) !== hubTerm && isReported(r.id),
178
373
  );
179
374
 
180
375
  const sentences = [];
@@ -187,7 +382,7 @@ export function renderNewsParagraph(hub, subgraphRows) {
187
382
 
188
383
  for (const predicate of Object.keys(FACT_PREDICATE_PHRASES)) {
189
384
  if (IDENTITY_PREDICATES.has(predicate) || sentences.length >= SENTENCE_CAP) continue;
190
- const objects = hubRows
385
+ const objects = reportedHubRows
191
386
  .filter((r) => r.predicate === predicate)
192
387
  .map((r) => r.object)
193
388
  .sort();
@@ -209,25 +404,35 @@ export function renderNewsParagraph(hub, subgraphRows) {
209
404
  return capped.length ? `${capped.join(". ")}.` : "";
210
405
  }
211
406
 
212
- /** scoreHubs -> one item per hub (PLAN_NEWS_FEED.md section 6.6), paragraph
213
- * included, sorted builtAt desc then id asc. `sourcesByFactId` maps fact ids
214
- * to snapshot source links ({ title, url, name }). */
407
+ /** newsworthyHubs -> one item per hub (PLAN_NEWS_FEED.md section 6.6),
408
+ * paragraph included, sorted builtAt desc then id asc. `sourcesByFactId`
409
+ * maps fact ids to snapshot source links ({ title, url, name }). The gate
410
+ * (PLAN_NEWS_FEED.md section 17): `reportedRows` replaces `newsWindowRows`
411
+ * and `newsworthyHubs` replaces `scoreHubs` as this function's own inputs —
412
+ * both keep their prior behaviour for every other caller. Each item's
413
+ * two-hop sub-graph then splits into its own `reported`/`background` rows,
414
+ * so a card's paragraph draws from what was reported and its collapsed
415
+ * `backgroundParagraph` draws from what the graph already knew. */
215
416
  export function buildNewsItems(rows, { now, windowMs, limit = 6, sourcesByFactId = new Map() } = {}) {
216
- const windowRows = newsWindowRows(rows, { now, windowMs });
217
- const hubs = scoreHubs(rows, windowRows, { limit });
417
+ const reported = reportedRows(rows, { now, windowMs });
418
+ const reportedIds = new Set(reported.map((r) => r.id));
218
419
  const adjacency = buildTermAdjacency(rows);
420
+ const hubs = newsworthyHubs(rows, reported, { now, windowMs, limit, adjacency });
219
421
  const items = hubs.map(({ term, changed }) => {
220
422
  const subgraphRows = subgraphAround(rows, term, { adjacency });
221
423
  const factIds = subgraphRows.map((r) => r.id).sort();
424
+ const { background } = splitCardRows(subgraphRows, reportedIds);
222
425
  return {
223
426
  id: `news-feed:${sha256HexPrefix(`${term}\0${factIds.join(",")}`, 8)}`,
224
427
  hub: term,
225
428
  factIds,
226
429
  changedCount: changed,
227
430
  builtAt: now,
228
- paragraph: renderNewsParagraph(term, subgraphRows),
431
+ paragraph: renderNewsParagraph(term, subgraphRows, { reportedIds }),
229
432
  tier: tierOf(subgraphRows),
230
433
  sources: collectSources(subgraphRows, sourcesByFactId),
434
+ background: background.map((r) => r.id).sort(),
435
+ backgroundParagraph: renderNewsParagraph(term, background),
231
436
  };
232
437
  });
233
438
  return items.sort((a, b) => (toMs(b.builtAt) - toMs(a.builtAt)) || byId(a, b));