@polycode-projects/the-mechanical-code-talker 5.0.24 → 5.0.26

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.
Files changed (34) hide show
  1. package/README.md +74 -11
  2. package/bin/tmct.mjs +81 -0
  3. package/corpus/sprites/src/sprite-facts.jsonl +48 -0
  4. package/package.json +5 -1
  5. package/src/adapters/corpus/courtesy.mjs +91 -28
  6. package/src/adapters/corpus/dbpedia-lookup-live.mjs +116 -0
  7. package/src/adapters/corpus/news-sources.mjs +436 -0
  8. package/src/adapters/corpus/research-source.mjs +16 -3
  9. package/src/adapters/corpus/wiktionary-live.mjs +158 -0
  10. package/src/adapters/news-store.mjs +87 -0
  11. package/src/adapters/toml-config.mjs +18 -0
  12. package/src/domain/choice-question.mjs +275 -0
  13. package/src/domain/cli-verbs.mjs +20 -0
  14. package/src/domain/dialogue-acts.mjs +1 -0
  15. package/src/domain/el-classify.mjs +569 -0
  16. package/src/domain/fact-phrase.mjs +70 -0
  17. package/src/domain/feed-normalize.mjs +224 -0
  18. package/src/domain/grammar/ace.mjs +223 -7
  19. package/src/domain/grammar/lexicon-core.json +2 -0
  20. package/src/domain/memory/trust.mjs +15 -0
  21. package/src/domain/news-feed.mjs +219 -0
  22. package/src/domain/reasoning-config.mjs +56 -0
  23. package/src/domain/sprite-animation.mjs +20 -2
  24. package/src/domain/tableau.mjs +1225 -0
  25. package/src/domain/term-ledger.mjs +118 -0
  26. package/src/services/adventure-viz.mjs +89 -7
  27. package/src/services/chat.mjs +495 -27
  28. package/src/services/extract-facts.mjs +91 -1
  29. package/src/services/index.mjs +12 -0
  30. package/src/services/init.mjs +33 -0
  31. package/src/services/news.mjs +918 -0
  32. package/src/services/sprite-catalog-viz.mjs +148 -78
  33. package/src/surfaces/web/memory-ask-browser.bundle.js +132 -132
  34. package/src/surfaces/web/sprites-browser-entry.mjs +4 -4
@@ -0,0 +1,118 @@
1
+ // term-ledger.mjs — counts every fact-ungrounded term the news loop sees, so
2
+ // the enrichment queue can work the most-mentioned gaps first
3
+ // (PLAN_NEWS_FEED.md section 6.3). Pure: every timestamp arrives as a `now`
4
+ // parameter from the caller, nothing here reads the wall clock, so two peers
5
+ // replaying the same bump/mark/sweep sequence converge on the same ledger.
6
+
7
+ import { normFactTerm } from "./hash.mjs";
8
+
9
+ const ITEM_IDS_CAP = 12;
10
+
11
+ /** Ledger entry field order fixed once here so `ledgerPayload` serializes
12
+ * byte-identically across peers regardless of insertion order elsewhere. */
13
+ function newEntry(term, vocabGrounded, now) {
14
+ return {
15
+ term,
16
+ count: 0,
17
+ vocabGrounded,
18
+ itemIds: [],
19
+ firstSeen: now,
20
+ lastSeen: now,
21
+ status: "pending",
22
+ missedAt: "",
23
+ };
24
+ }
25
+
26
+ export function createTermLedger() {
27
+ return { terms: new Map() };
28
+ }
29
+
30
+ /** `termCounts`: Map<term, occurrences-in-this-text>. Normalizes keys through
31
+ * `normFactTerm`, so dedupe across cycles is inherent — one entry per
32
+ * normalized term. `vocabGroundedByTerm` (raw term or normalized term ->
33
+ * boolean) seeds a NEW entry's `vocabGrounded` flag once; an existing entry's
34
+ * flag is never revisited, because lexicon membership does not change. */
35
+ export function bumpTerms(ledger, termCounts, itemId, now, vocabGroundedByTerm = new Map()) {
36
+ for (const [rawTerm, occurrences] of termCounts) {
37
+ const term = normFactTerm(rawTerm);
38
+ if (!term) continue;
39
+ let entry = ledger.terms.get(term);
40
+ if (!entry) {
41
+ const vocabGrounded = vocabGroundedByTerm.has(rawTerm)
42
+ ? Boolean(vocabGroundedByTerm.get(rawTerm))
43
+ : Boolean(vocabGroundedByTerm.get(term));
44
+ entry = newEntry(term, vocabGrounded, now);
45
+ ledger.terms.set(term, entry);
46
+ }
47
+ entry.count += occurrences;
48
+ entry.lastSeen = now;
49
+ if (itemId && !entry.itemIds.includes(itemId) && entry.itemIds.length < ITEM_IDS_CAP) {
50
+ entry.itemIds.push(itemId);
51
+ }
52
+ }
53
+ return ledger;
54
+ }
55
+
56
+ const byRank = (a, b) => b.count - a.count || (a.term < b.term ? -1 : a.term > b.term ? 1 : 0);
57
+
58
+ /** A "missed" entry whose `missedAt + ttlMs` has passed `now` reads as
59
+ * "pending" here — the negative-cache expiry, computed fresh on every call
60
+ * from the arguments alone. The ledger itself is never mutated by this. */
61
+ function effectiveStatus(entry, now, ttlMs) {
62
+ if (entry.status !== "missed" || now == null || !ttlMs) return entry.status;
63
+ const missedAtMs = Date.parse(entry.missedAt);
64
+ if (!Number.isFinite(missedAtMs)) return entry.status;
65
+ const nowMs = typeof now === "number" ? now : Date.parse(now);
66
+ if (!Number.isFinite(nowMs)) return entry.status;
67
+ return nowMs - missedAtMs >= ttlMs ? "pending" : entry.status;
68
+ }
69
+
70
+ /** Entries sorted count desc then term asc; `status` filters on the entry's
71
+ * effective status (after the negative-cache expiry above) when given. */
72
+ export function rankedTerms(ledger, { limit = 20, status = null, now = null, ttlMs = 0 } = {}) {
73
+ const withEffectiveStatus = [...ledger.terms.values()].map((entry) => ({
74
+ ...entry,
75
+ status: effectiveStatus(entry, now, ttlMs),
76
+ }));
77
+ const filtered = status == null ? withEffectiveStatus : withEffectiveStatus.filter((e) => e.status === status);
78
+ return filtered.sort(byRank).slice(0, limit);
79
+ }
80
+
81
+ /** Sets an entry's status; stamps `missedAt` when the new status is
82
+ * "missed" (the negative-cache clock). A no-op for a term with no entry. */
83
+ export function markTerm(ledger, term, status, now) {
84
+ const entry = ledger.terms.get(normFactTerm(term));
85
+ if (!entry) return ledger;
86
+ entry.status = status;
87
+ if (status === "missed") entry.missedAt = now;
88
+ return ledger;
89
+ }
90
+
91
+ /** Flips every pending/missed entry `isFactGrounded(term)` now answers true
92
+ * for to "grounded"; returns the flipped terms, sorted. `vocabGrounded` never
93
+ * gates this — fact-grounding and vocab-grounding are independent states. */
94
+ export function groundedSweep(ledger, isFactGrounded) {
95
+ const flipped = [];
96
+ for (const entry of ledger.terms.values()) {
97
+ if ((entry.status === "pending" || entry.status === "missed") && isFactGrounded(entry.term)) {
98
+ entry.status = "grounded";
99
+ flipped.push(entry.term);
100
+ }
101
+ }
102
+ return flipped.sort();
103
+ }
104
+
105
+ /** JSON-safe snapshot, entries in ranking order — the determinism contract:
106
+ * two peers with the same bump/mark/sweep history serialize identically. */
107
+ export function ledgerPayload(ledger) {
108
+ const entries = [...ledger.terms.values()].sort(byRank).map((entry) => ({ ...entry, itemIds: [...entry.itemIds] }));
109
+ return { terms: entries };
110
+ }
111
+
112
+ export function ledgerFromPayload(payload) {
113
+ const ledger = createTermLedger();
114
+ for (const entry of payload?.terms ?? []) {
115
+ ledger.terms.set(entry.term, { ...entry, itemIds: [...(entry.itemIds ?? [])] });
116
+ }
117
+ return ledger;
118
+ }
@@ -40,7 +40,7 @@
40
40
  // beyond this module's own exports, which is what keeps a raw `.toString()`
41
41
  // splice safe.
42
42
  //
43
- // Four further pure helpers are exported for testing but NOT spliced,
43
+ // Five further pure helpers are exported for testing but NOT spliced,
44
44
  // because each calls another module's export — the in-page script instead
45
45
  // reaches through the browser bundle's own `tmct` surface (mirroring
46
46
  // how the spider-fly page's inline script calls it rather than re-importing
@@ -52,12 +52,16 @@
52
52
  // `pillsFor` mirrors it against `tmct.page.roomAffordances`),
53
53
  // `goalStatusLines` (calls `foldWorldState` and adventure-autoplay.mjs's own
54
54
  // `exposedFacts`; the in-page `goalStatusLinesFor` mirrors both against the
55
- // `tmct` surface too), and `visitedRoomGraph` (a directions-only
55
+ // `tmct` surface too), `visitedRoomGraph` (a directions-only
56
56
  // layout of the rooms a session has actually visited, now a thin wrapper over
57
57
  // viz-room-graph.mjs's shared `directedGridLayout` — mud-viz.mjs's own
58
58
  // burrowGraph wrote the same BFS-grid layout a second time under its own
59
59
  // name, and that shared module is where the layout lives now; see its own
60
- // header for the algorithm and what `hints`/disconnected components mean).
60
+ // header for the algorithm and what `hints`/disconnected components mean),
61
+ // and `roomWalkerPropertyFacts` (calls sprite-animation.mjs's own
62
+ // `oscillateWalkStep`; the in-page `walkerFactsFor` mirrors it against
63
+ // `tmct.page.spriteAnimation.oscillateWalkStep` — see the room-sprite
64
+ // resolution section below for how its output reaches the resolver).
61
65
  // The in-page script never splices `directedGridLayout`/`roomGraphSvg`
62
66
  // either, for the same not-self-contained reason: it calls
63
67
  // `tmct.page.directedGridLayout`/`tmct.page.roomGraphSvg` straight
@@ -93,13 +97,14 @@
93
97
  // (adventure-browser-entry.mjs), never here — this module only renders and
94
98
  // reads.
95
99
  import { THEME_TOKENS_CSS, SERIF_STACK, MONO_STACK, escapeHtml, embedJson, embedScriptText, scenarioLabel, rowsForWorld, wordBeforeCursor, demoEyebrowHtml, EYEBROW_LINKS_CSS } from "./viz-theme.mjs";
96
- import { createTicker, createSerialQueue } from "./viz-ticker.mjs";
100
+ import { createTicker, createSerialQueue, prefersReducedMotion } from "./viz-ticker.mjs";
97
101
  import { directedGridLayout } from "./viz-room-graph.mjs";
98
102
  import { worldDigestRows, roomAffordances, foldWorldState } from "./adventure.mjs";
99
103
  import { exposedFacts } from "./adventure-autoplay.mjs";
100
104
  import { relatedForTerm } from "../domain/skos-view.mjs";
101
105
  import { classAncestorChain } from "../domain/sprite-map.mjs";
102
106
  import { renderWorldEditorText } from "./adventure-editor.mjs";
107
+ import { oscillateWalkStep, SPRITE_POSE_MOVING } from "../domain/sprite-animation.mjs";
103
108
 
104
109
  const DEFAULT_TITLE = "tmct — the adventure";
105
110
  const PREVIEW_MAX_TICKS = 30;
@@ -165,6 +170,35 @@ export function factsForSubject(rows, subject) {
165
170
  return (rows || []).filter((r) => r.subject === subject);
166
171
  }
167
172
 
173
+ /** A stable animation-cycle offset for `subject` — the sum of its own
174
+ * character codes — so two members of staff sharing a room usually turn at
175
+ * different points of the SAME shared clock rather than in lockstep (a
176
+ * same-total coincidence between two particular names is possible, since
177
+ * the walk cycle only has 18 steps; harmless either way, as the two just
178
+ * read as turning together). Pure. */
179
+ function walkerPhase(subject) {
180
+ return [...String(subject || "")].reduce((sum, ch) => sum + ch.charCodeAt(0), 0);
181
+ }
182
+
183
+ /** The synthetic mgx:faces/mgx:pose property facts a room's own walking NPC
184
+ * `subject` renders with at animation `tick` — sprite-animation.mjs's own
185
+ * oscillateWalkStep read as the small `{predicate, object}` fact shape
186
+ * sprite-templates.mjs's resolver already matches a TAUGHT fact against, so
187
+ * household staff (butler/cook/gardener/housekeeper) cycle through the
188
+ * turntable art data/sprites-large/*.toml's own household-staff aliases
189
+ * carry, with nothing ever written to the store. `walkerPhase` offsets one
190
+ * NPC's own cycle from another's. Empty at the walk's own front-facing/
191
+ * at-rest instants (oscillateWalkStep's null facing, "static" pose) — the
192
+ * class's own resting template already draws that, so this never asks for a
193
+ * fact that changes nothing. Pure. */
194
+ export function roomWalkerPropertyFacts(subject, tick) {
195
+ const step = oscillateWalkStep(Number(tick) + walkerPhase(subject), {});
196
+ const facts = [];
197
+ if (step.facing) facts.push({ predicate: "mgx:faces", object: step.facing });
198
+ if (step.pose === SPRITE_POSE_MOVING) facts.push({ predicate: "mgx:pose", object: step.pose });
199
+ return facts;
200
+ }
201
+
168
202
  /** The room a subject's placement resolves into, for VISIBILITY — a room
169
203
  * resolves to itself; an object placed directly in a room resolves to that
170
204
  * room; an object one containment hop inside an OPEN container resolves to
@@ -1119,6 +1153,7 @@ ${engineBundleJs ? `<script>\n${embedScriptText(engineBundleJs)}\n</script>` : `
1119
1153
  "use strict";
1120
1154
  const createTicker = ${createTicker.toString()};
1121
1155
  const createSerialQueue = ${createSerialQueue.toString()};
1156
+ const prefersReducedMotion = ${prefersReducedMotion.toString()};
1122
1157
  const spriteClassForObject = ${spriteClassForObject.toString()};
1123
1158
  const visibleRoomOf = ${visibleRoomOf.toString()};
1124
1159
  const roomSceneObjects = ${roomSceneObjects.toString()};
@@ -1573,10 +1608,35 @@ ${engineBundleJs ? `<script>\n${embedScriptText(engineBundleJs)}\n</script>` : `
1573
1608
  // unknown character as a figure, and neither should ever draw a creature.
1574
1609
  const ROOT_FALLBACK_BY_CLASS = { adventurer: "person", person: "person", room: "room" };
1575
1610
  const rootFallbackFor = (cls) => ROOT_FALLBACK_BY_CLASS[cls] || "portable";
1611
+
1612
+ // ---- NPC idle turn — a synthetic mgx:faces/mgx:pose fact pair (never
1613
+ // written to the store) merged onto a person-classed room NPC's own
1614
+ // property facts, so household staff (butler/cook/gardener/housekeeper)
1615
+ // cycle through the turning/walking art data/sprites-large/*.toml's own
1616
+ // household-staff aliases carry, the same [match] resolver path a taught
1617
+ // fact would take. Mirrors the module's own exported, tested
1618
+ // roomWalkerPropertyFacts against the bundle's published
1619
+ // tmct.page.spriteAnimation.oscillateWalkStep (see this module's own
1620
+ // header for why the calling-another-module pieces are mirrored rather
1621
+ // than spliced). walkTick advances on its own clock below, separate from
1622
+ // the game ticker — this never touches the store or the persisted save.
1623
+ // Skipped entirely under prefers-reduced-motion, so a room with staff in
1624
+ // it looks exactly as it did before this feature shipped.
1625
+ const reducedMotion = prefersReducedMotion();
1626
+ let walkTick = 0;
1627
+ function walkerFactsFor(subject) {
1628
+ const phase = [...String(subject || "")].reduce((sum, ch) => sum + ch.charCodeAt(0), 0);
1629
+ const step = tmct.page.spriteAnimation.oscillateWalkStep(walkTick + phase, {});
1630
+ const facts = [];
1631
+ if (step.facing) facts.push({ predicate: "mgx:faces", object: step.facing });
1632
+ if (step.pose === "moving") facts.push({ predicate: "mgx:pose", object: step.pose });
1633
+ return facts;
1634
+ }
1576
1635
  function resolveObjectSprite(rows, s) {
1577
1636
  if (s.subject === "you") return tmct.page.resolveSpriteAsset("adventurer", [], [], activeSpriteTemplates, tmct.page.SPRITE_REGISTRY, { rootFallback: "person", instanceKey: "you" });
1637
+ const walkFacts = !reducedMotion && s.spriteClass === "person" ? walkerFactsFor(s.subject) : [];
1578
1638
  return tmct.page.resolveSpriteAsset(
1579
- s.subject, spriteAncestryRows(rows, s.subject), factsForSubject(rows, s.subject),
1639
+ s.subject, spriteAncestryRows(rows, s.subject), factsForSubject(rows, s.subject).concat(walkFacts),
1580
1640
  activeSpriteTemplates, tmct.page.SPRITE_REGISTRY,
1581
1641
  { rootFallback: rootFallbackFor(s.spriteClass), instanceKey: s.subject },
1582
1642
  );
@@ -1622,8 +1682,13 @@ ${engineBundleJs ? `<script>\n${embedScriptText(engineBundleJs)}\n</script>` : `
1622
1682
  runTurn("go " + btn.getAttribute("data-direction"));
1623
1683
  });
1624
1684
 
1625
- function redraw(snap) {
1626
- lastSnapshot = snap;
1685
+ // The room's own sprite tiles (wall band, floor stacks, the player's own
1686
+ // slot) — factored out of redraw() so the NPC idle-turn clock below can
1687
+ // refresh JUST these tiles on its own faster/independent cadence, without
1688
+ // re-running the caption/pills/map/goal rebuilds redraw() also does, and
1689
+ // critically without re-triggering schedulePersistSave() on every walk
1690
+ // frame.
1691
+ function redrawRoomSprites(snap) {
1627
1692
  const layout = roomSceneLayout(snap.rows, snap.state, snap.here);
1628
1693
  wallRowEl.innerHTML = layout.wall.map((s) => spriteCardHtml(s.subject, s.spriteClass, resolveObjectSprite(snap.rows, s), s.subject)).join("");
1629
1694
  floorRowEl.innerHTML = layout.floor.map((stack) => {
@@ -1634,6 +1699,11 @@ ${engineBundleJs ? `<script>\n${embedScriptText(engineBundleJs)}\n</script>` : `
1634
1699
  }).join("") + "</div>";
1635
1700
  }).join("");
1636
1701
  youSlotEl.innerHTML = spriteCardHtml("you", "adventurer", resolveObjectSprite(snap.rows, { subject: "you", spriteClass: "adventurer" }));
1702
+ }
1703
+
1704
+ function redraw(snap) {
1705
+ lastSnapshot = snap;
1706
+ redrawRoomSprites(snap);
1637
1707
  roomNameEl.textContent = "the " + snap.here;
1638
1708
  roomFrameEl.setAttribute("data-room-kind", roomKindForRoom(snap.rows, snap.here));
1639
1709
  roomKindIconEl.innerHTML = roomKindIconSvg(snap.rows, snap.here);
@@ -1852,6 +1922,18 @@ ${engineBundleJs ? `<script>\n${embedScriptText(engineBundleJs)}\n</script>` : `
1852
1922
  if (scenarioSelectEl) scenarioSelectEl.disabled = false;
1853
1923
  }
1854
1924
 
1925
+ // The NPC idle-turn clock — its own interval, separate from the game
1926
+ // ticker above (that one drives real turns and the persisted save; this
1927
+ // one only cycles which frame the room's own staff show). Paused rooms,
1928
+ // edit mode and an as-yet-unbooted session all just skip the redraw.
1929
+ if (!reducedMotion) {
1930
+ setInterval(() => {
1931
+ walkTick += 1;
1932
+ if (!lastSnapshot || document.body.classList.contains("editing")) return;
1933
+ redrawRoomSprites(lastSnapshot);
1934
+ }, ADVENTURE.tickWaitMs);
1935
+ }
1936
+
1855
1937
  const ticker = createTicker({
1856
1938
  onTick: () => withLock(async () => {
1857
1939
  const result = await session.autoplayTick();