@polycode-projects/the-mechanical-code-talker 5.0.34 → 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 +1 -1
- package/src/adapters/corpus/news-sources.mjs +13 -9
- package/src/domain/choice-question.mjs +91 -0
- package/src/domain/news-feed.mjs +315 -12
- package/src/services/agent-editor.mjs +125 -0
- package/src/services/chat.mjs +496 -24
- package/src/services/mudiii-scene.mjs +370 -8
- package/src/services/mudiii-turn.mjs +180 -2
- package/src/services/mudiii-viz.mjs +75 -13
- package/src/services/news-viz.mjs +114 -35
- package/src/services/news.mjs +112 -101
- package/src/surfaces/web/memory-ask-browser.bundle.js +137 -137
- package/src/surfaces/web/news-browser-entry.mjs +132 -37
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@polycode-projects/the-mechanical-code-talker",
|
|
3
|
-
"version": "5.0.
|
|
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):
|
|
34
|
-
*
|
|
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
|
-
|
|
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;
|
|
105
|
-
enabledByDefault:
|
|
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
|
-
|
|
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]));
|
|
@@ -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
|
+
}
|
package/src/domain/news-feed.mjs
CHANGED
|
@@ -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
|
|
|
@@ -69,6 +71,280 @@ export function newsWindowRows(rows, { now, windowMs }) {
|
|
|
69
71
|
});
|
|
70
72
|
}
|
|
71
73
|
|
|
74
|
+
// ---------------------------------------------------------------------------
|
|
75
|
+
// The newsworthiness gate (PLAN_NEWS_FEED.md section 17). A card reports what
|
|
76
|
+
// a contemporary source said inside the window; everything the graph looked
|
|
77
|
+
// up, inferred or already held is background. classifyNewsRow bands a single
|
|
78
|
+
// row; reportedRows and newsworthyHubs narrow buildNewsItems downstream of
|
|
79
|
+
// newsWindowRows/scoreHubs, which keep their own behaviour unchanged.
|
|
80
|
+
// ---------------------------------------------------------------------------
|
|
81
|
+
|
|
82
|
+
// Identity predicates and their negative twins — what a thing IS, never what
|
|
83
|
+
// happened to it, so a row under any of these bands background whoever wrote
|
|
84
|
+
// it. Distinct from renderNewsParagraph's own narrower IDENTITY_PREDICATES
|
|
85
|
+
// (below), which only needs the two positive forms for its identity sentence.
|
|
86
|
+
const GATE_IDENTITY_PREDICATES = new Set(["rdf:type", "rdfs:subClassOf", "mgxneg:subClassOf", "owl:disjointWith"]);
|
|
87
|
+
|
|
88
|
+
// Every determiner a universal quantifier is ever stored under — today only
|
|
89
|
+
// "every" is written (chat.mjs's own teach lane), "all"/"each" kept here so a
|
|
90
|
+
// future writer of either still bands background rather than heading a card.
|
|
91
|
+
const UNIVERSAL_QUANTIFIERS = new Set(["every", "all", "each"]);
|
|
92
|
+
|
|
93
|
+
// A REPORT is `news:` or `news-fixture:` only — `research:` counts for the
|
|
94
|
+
// window (isNewsProvenance, above) but never for the gate: an enrichment
|
|
95
|
+
// lookup is something the graph asked for, not something a source reported.
|
|
96
|
+
const REPORT_PROVENANCE_RE = /(?:^|:)(?:news|news-fixture):/;
|
|
97
|
+
|
|
98
|
+
const hasNonEmptyArray = (value) => Array.isArray(value) && value.length > 0;
|
|
99
|
+
|
|
100
|
+
// The provenance HEAD is the first whitespace-delimited token — the same cut
|
|
101
|
+
// point trust.mjs's own provenanceTagToSource uses, so "entailed:" is read
|
|
102
|
+
// off the row's OWN assertion even when a union has appended a second tag
|
|
103
|
+
// after it.
|
|
104
|
+
const provenanceHead = (provenance) => String(provenance || "").trim().split(/\s+/)[0] || "";
|
|
105
|
+
|
|
106
|
+
/** "derived" | "background" | "reported" for one row, pure over the row plus
|
|
107
|
+
* `now` (PLAN_NEWS_FEED.md section 17.3, step one). Rules apply in order,
|
|
108
|
+
* first hit wins: a syllogised row is derived; an identity, universal or
|
|
109
|
+
* non-news-provenance row is background; a news/news-fixture row with no
|
|
110
|
+
* readable or in-window stamp is background; everything else is reported. */
|
|
111
|
+
export function classifyNewsRow(row, { now, windowMs }) {
|
|
112
|
+
if (provenanceHead(row.provenance).startsWith("entailed:")
|
|
113
|
+
|| hasNonEmptyArray(row.environments) || hasNonEmptyArray(row.justification)) {
|
|
114
|
+
return "derived";
|
|
115
|
+
}
|
|
116
|
+
if (GATE_IDENTITY_PREDICATES.has(row.predicate)) return "background";
|
|
117
|
+
if (UNIVERSAL_QUANTIFIERS.has(String(row.quantifier || "").toLowerCase())) return "background";
|
|
118
|
+
if (!REPORT_PROVENANCE_RE.test(String(row.provenance || ""))) return "background";
|
|
119
|
+
const t = rowObservedMs(row);
|
|
120
|
+
const nowMs = toMs(now);
|
|
121
|
+
if (!Number.isFinite(t) || t < nowMs - windowMs || t > nowMs) return "background";
|
|
122
|
+
return "reported";
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** The "reported" subset of `rows` — counting occurrences over this set,
|
|
126
|
+
* rather than the wider news window, is what makes a hub's `changedCount`
|
|
127
|
+
* count reports rather than lookups (newsworthyHubs, below). */
|
|
128
|
+
export function reportedRows(rows, { now, windowMs }) {
|
|
129
|
+
return rows.filter((row) => classifyNewsRow(row, { now, windowMs }) === "reported");
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** The class objects of every identity row anywhere in `rows` — what the
|
|
133
|
+
* graph's own `rdf:type`/`rdfs:subClassOf` (and negative twins) rows name as
|
|
134
|
+
* a CLASS, regardless of who reported the identity fact. A hub test, not a
|
|
135
|
+
* row band: a term absent from this set is not a class by the graph's own
|
|
136
|
+
* account. */
|
|
137
|
+
export function conceptTerms(rows) {
|
|
138
|
+
const terms = new Set();
|
|
139
|
+
for (const row of rows) {
|
|
140
|
+
if (!GATE_IDENTITY_PREDICATES.has(row.predicate)) continue;
|
|
141
|
+
const t = normFactTerm(row.object);
|
|
142
|
+
if (t) terms.add(t);
|
|
143
|
+
}
|
|
144
|
+
return terms;
|
|
145
|
+
}
|
|
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
|
+
|
|
187
|
+
const BARE_NUMBER_RE = /^-?[£$€]?\d[\d,]*(?:\.\d+)?%?$/;
|
|
188
|
+
const ISO_DATE_RE = /^\d{4}-\d{2}(-\d{2})?$/;
|
|
189
|
+
const QUARTER_RE = /^q[1-4]\s+\d{4}$/i;
|
|
190
|
+
const LEADING_DIGIT_PHRASE_RE = /^\d[\d,.]*\s+\S/;
|
|
191
|
+
const TRAILING_NUMBER_PHRASE_RE = /\s\d[\d,.]*$/;
|
|
192
|
+
|
|
193
|
+
/** True when the WHOLE term is a number, a date or a quantity phrase ("q3
|
|
194
|
+
* 2026", "7,409 square kilometres", "1,683,115") — never a term a hub may
|
|
195
|
+
* head: a date is when a card happened, and an amount is what it says. */
|
|
196
|
+
export function isQuantityTerm(term) {
|
|
197
|
+
const t = String(term ?? "").trim().toLowerCase();
|
|
198
|
+
if (!t) return false;
|
|
199
|
+
if (BARE_NUMBER_RE.test(t)) return true;
|
|
200
|
+
if (ISO_DATE_RE.test(t)) return true;
|
|
201
|
+
if (QUARTER_RE.test(t)) return true;
|
|
202
|
+
if (LEADING_DIGIT_PHRASE_RE.test(t)) return true;
|
|
203
|
+
if (TRAILING_NUMBER_PHRASE_RE.test(t)) return true;
|
|
204
|
+
return false;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** True when `term` contains a digit run anywhere — the anchor a specific
|
|
208
|
+
* measurement gives a seeded hub, weaker than isQuantityTerm's "the whole
|
|
209
|
+
* term IS a number" test. */
|
|
210
|
+
export function hasQuantityMarker(term) {
|
|
211
|
+
return /\d/.test(String(term ?? ""));
|
|
212
|
+
}
|
|
213
|
+
|
|
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
|
+
}
|
|
244
|
+
|
|
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;
|
|
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);
|
|
284
|
+
|
|
285
|
+
const counts = new Map();
|
|
286
|
+
const subjectRowsByTerm = new Map();
|
|
287
|
+
for (const row of reported) {
|
|
288
|
+
const s = normFactTerm(row.subject);
|
|
289
|
+
const o = normFactTerm(row.object);
|
|
290
|
+
for (const term of [s, o]) {
|
|
291
|
+
if (!term || STOP_SET.has(term)) continue;
|
|
292
|
+
counts.set(term, (counts.get(term) || 0) + 1);
|
|
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);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
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
|
+
|
|
326
|
+
const hubs = [];
|
|
327
|
+
for (const [term, changed] of counts) {
|
|
328
|
+
if (passesEntityTest(term) || passesFreshAssertionTest(term)) hubs.push({ term, changed });
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
return hubs
|
|
332
|
+
.sort((a, b) => b.changed - a.changed || (a.term < b.term ? -1 : a.term > b.term ? 1 : 0))
|
|
333
|
+
.slice(0, limit);
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/** A card's two-hop sub-graph, divided by the row-band gate: `reported` rows
|
|
337
|
+
* (what heads the card) and everything else (the collapsed background
|
|
338
|
+
* line). `reportedIds` is the reported-row id set the caller already
|
|
339
|
+
* computed over the whole fact set (reportedRows' output, by id). */
|
|
340
|
+
export function splitCardRows(subgraphRows, reportedIds) {
|
|
341
|
+
const ids = reportedIds instanceof Set ? reportedIds : new Set(reportedIds || []);
|
|
342
|
+
const reported = [];
|
|
343
|
+
const background = [];
|
|
344
|
+
for (const row of subgraphRows) (ids.has(row.id) ? reported : background).push(row);
|
|
345
|
+
return { reported, background };
|
|
346
|
+
}
|
|
347
|
+
|
|
72
348
|
/** Counts window facts per term (subject and object, normalized, STOP_SET
|
|
73
349
|
* removed) -> [{ term, changed }] sorted changed desc then term asc, capped
|
|
74
350
|
* at `limit`. */
|
|
@@ -178,12 +454,23 @@ const SENTENCE_CAP = 5;
|
|
|
178
454
|
* 8.3): identity first, then the hub's own relations grouped by predicate in
|
|
179
455
|
* FACT_PREDICATE_PHRASES table order, then one closing sentence naming up to
|
|
180
456
|
* three second-hop facts. Every sentence shown is a grounded fact, never a
|
|
181
|
-
* paraphrase of prose the grammar could not read.
|
|
182
|
-
|
|
457
|
+
* paraphrase of prose the grammar could not read.
|
|
458
|
+
*
|
|
459
|
+
* `reportedIds` (PLAN_NEWS_FEED.md section 17.4), when given, restricts the
|
|
460
|
+
* relation sentences and the closing "Around it" sentence to rows in that
|
|
461
|
+
* set — the identity sentence keeps drawing from every row it's handed,
|
|
462
|
+
* since "what is this thing" is the first question a reader has regardless
|
|
463
|
+
* of who reported it. Defaults to null, meaning every row renders, so every
|
|
464
|
+
* existing caller and pin is unaffected. */
|
|
465
|
+
export function renderNewsParagraph(hub, subgraphRows, { reportedIds = null } = {}) {
|
|
183
466
|
const hubTerm = normFactTerm(hub);
|
|
467
|
+
const isReported = reportedIds === null
|
|
468
|
+
? () => true
|
|
469
|
+
: (id) => (reportedIds instanceof Set ? reportedIds.has(id) : reportedIds.includes(id));
|
|
184
470
|
const hubRows = subgraphRows.filter((r) => normFactTerm(r.subject) === hubTerm);
|
|
471
|
+
const reportedHubRows = hubRows.filter((r) => isReported(r.id));
|
|
185
472
|
const secondHopRows = subgraphRows.filter(
|
|
186
|
-
(r) => normFactTerm(r.subject) !== hubTerm && normFactTerm(r.object) !== hubTerm,
|
|
473
|
+
(r) => normFactTerm(r.subject) !== hubTerm && normFactTerm(r.object) !== hubTerm && isReported(r.id),
|
|
187
474
|
);
|
|
188
475
|
|
|
189
476
|
const sentences = [];
|
|
@@ -192,11 +479,14 @@ export function renderNewsParagraph(hub, subgraphRows) {
|
|
|
192
479
|
.filter((r) => IDENTITY_PREDICATES.has(r.predicate))
|
|
193
480
|
.map((r) => r.object)
|
|
194
481
|
.sort();
|
|
195
|
-
if (identityObjects.length)
|
|
482
|
+
if (identityObjects.length) {
|
|
483
|
+
const withArticles = identityObjects.map((object) => `${articleFor(object)} ${object}`);
|
|
484
|
+
sentences.push(`${hub} is ${joinWithAnd(withArticles)}`);
|
|
485
|
+
}
|
|
196
486
|
|
|
197
487
|
for (const predicate of Object.keys(FACT_PREDICATE_PHRASES)) {
|
|
198
488
|
if (IDENTITY_PREDICATES.has(predicate) || sentences.length >= SENTENCE_CAP) continue;
|
|
199
|
-
const objects =
|
|
489
|
+
const objects = reportedHubRows
|
|
200
490
|
.filter((r) => r.predicate === predicate)
|
|
201
491
|
.map((r) => r.object)
|
|
202
492
|
.sort();
|
|
@@ -218,25 +508,38 @@ export function renderNewsParagraph(hub, subgraphRows) {
|
|
|
218
508
|
return capped.length ? `${capped.join(". ")}.` : "";
|
|
219
509
|
}
|
|
220
510
|
|
|
221
|
-
/**
|
|
222
|
-
* included, sorted builtAt desc then id asc. `sourcesByFactId`
|
|
223
|
-
* to snapshot source links ({ title, url, name }).
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
511
|
+
/** newsworthyHubs -> one item per hub (PLAN_NEWS_FEED.md section 6.6),
|
|
512
|
+
* paragraph included, sorted builtAt desc then id asc. `sourcesByFactId`
|
|
513
|
+
* maps fact ids to snapshot source links ({ title, url, name }). The gate
|
|
514
|
+
* (PLAN_NEWS_FEED.md section 17): `reportedRows` replaces `newsWindowRows`
|
|
515
|
+
* and `newsworthyHubs` replaces `scoreHubs` as this function's own inputs —
|
|
516
|
+
* both keep their prior behaviour for every other caller. Each item's
|
|
517
|
+
* two-hop sub-graph then splits into its own `reported`/`background` rows,
|
|
518
|
+
* so a card's paragraph draws from what was reported and its collapsed
|
|
519
|
+
* `backgroundParagraph` draws from what the graph already knew. */
|
|
520
|
+
export function buildNewsItems(rows, { now, windowMs, limit = 6, sourcesByFactId = new Map(), readsAsEntityTerm } = {}) {
|
|
521
|
+
const reported = reportedRows(rows, { now, windowMs });
|
|
522
|
+
const reportedIds = new Set(reported.map((r) => r.id));
|
|
227
523
|
const adjacency = buildTermAdjacency(rows);
|
|
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);
|
|
228
528
|
const items = hubs.map(({ term, changed }) => {
|
|
229
529
|
const subgraphRows = subgraphAround(rows, term, { adjacency });
|
|
230
530
|
const factIds = subgraphRows.map((r) => r.id).sort();
|
|
531
|
+
const { background } = splitCardRows(subgraphRows, reportedIds);
|
|
231
532
|
return {
|
|
232
533
|
id: `news-feed:${sha256HexPrefix(`${term}\0${factIds.join(",")}`, 8)}`,
|
|
233
534
|
hub: term,
|
|
234
535
|
factIds,
|
|
235
536
|
changedCount: changed,
|
|
236
537
|
builtAt: now,
|
|
237
|
-
paragraph: renderNewsParagraph(term, subgraphRows),
|
|
538
|
+
paragraph: renderNewsParagraph(term, subgraphRows, { reportedIds }),
|
|
238
539
|
tier: tierOf(subgraphRows),
|
|
239
540
|
sources: collectSources(subgraphRows, sourcesByFactId),
|
|
541
|
+
background: background.map((r) => r.id).sort(),
|
|
542
|
+
backgroundParagraph: renderNewsParagraph(term, background),
|
|
240
543
|
};
|
|
241
544
|
});
|
|
242
545
|
return items.sort((a, b) => (toMs(b.builtAt) - toMs(a.builtAt)) || byId(a, b));
|