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

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/corpus/worlds/index.json.gz +0 -0
  2. package/corpus/worlds/manifest.json +27 -17
  3. package/corpus/worlds/shards/river-crossing.jsonl.gz +0 -0
  4. package/corpus/worlds/shards/town-square-chapel.jsonl.gz +0 -0
  5. package/corpus/worlds/shards/town-square-market.jsonl.gz +0 -0
  6. package/corpus/worlds/shards/town-square.jsonl.gz +0 -0
  7. package/corpus/worlds/src/river-crossing.jsonl +29 -0
  8. package/corpus/worlds/src/town-square-chapel.jsonl +12 -8
  9. package/corpus/worlds/src/town-square-market.jsonl +12 -8
  10. package/corpus/worlds/src/town-square.jsonl +12 -8
  11. package/package.json +2 -1
  12. package/src/adapters/memory/inspect.mjs +37 -0
  13. package/src/domain/agent-traits.mjs +282 -0
  14. package/src/domain/ask.mjs +19 -6
  15. package/src/domain/choice-question.mjs +135 -6
  16. package/src/domain/codegraph.mjs +8 -1
  17. package/src/domain/el-classify.mjs +39 -7
  18. package/src/domain/fact-phrase.mjs +7 -4
  19. package/src/domain/interpret/normalize.mjs +58 -2
  20. package/src/domain/town-square-world.mjs +44 -19
  21. package/src/services/adventure.mjs +5 -16
  22. package/src/services/agent-editor.mjs +216 -0
  23. package/src/services/chat-session.mjs +26 -5
  24. package/src/services/chat.mjs +221 -58
  25. package/src/services/mudiii-scene.mjs +32 -5
  26. package/src/services/mudiii-turn.mjs +7 -3
  27. package/src/services/mudiii-viz.mjs +215 -1
  28. package/src/services/news-viz.mjs +489 -0
  29. package/src/services/predator-prey.mjs +157 -24
  30. package/src/surfaces/web/chat-browser-entry.mjs +69 -3
  31. package/src/surfaces/web/memory-ask-browser.bundle.js +155 -155
  32. package/src/surfaces/web/mudiii-browser-entry.mjs +35 -0
  33. package/src/surfaces/web/news-browser-entry.mjs +384 -0
  34. package/src/surfaces/web/turn-session.mjs +13 -9
@@ -0,0 +1,216 @@
1
+ // agent-editor.mjs — the actor card's text<->fact bridge, mudiii's third
2
+ // sentence table. Modelled on mud-editor.mjs's four-part shape (render,
3
+ // parse, plan), but reading and writing a different, disjoint predicate set:
4
+ // the ten `AGENT_TRAIT_PREDICATES` agent-traits.mjs already resolves off a
5
+ // class chain, never the placement/openness/exit/dig vocabulary
6
+ // mud-editor.mjs owns and never the drive-knob teach sentences
7
+ // mudiii-turn.mjs's TOWN_SQUARE_TEACH_PATTERNS owns. Three tables, three
8
+ // disjoint predicate sets, said once here so the next predicate added to any
9
+ // one of them has an obvious place to go rather than a guess.
10
+ //
11
+ // Unlike mud-editor.mjs, this module is not spliced into a page script by
12
+ // `.toString()` — it leans on agent-traits.mjs's class-chain walk
13
+ // (classChainOf, traitOriginOf, traitValueOf, traitValuesOf), which closes
14
+ // over nothing a `.toString()` splice could carry, so the page reaches the
15
+ // render functions through the `window.tmct.page` bag instead, the same way
16
+ // it already reaches `agentTraitsOf`.
17
+ //
18
+ // `renderAgentEditorText`/`renderAgentClassText` take a SUBJECT — an
19
+ // instance id or a class name — and print only that subject's own rows,
20
+ // never the resolved (chain-walked) values a caller like `agentTraitsOf`
21
+ // would hand back. That is the whole point of a per-instance editor: what
22
+ // you see in the box is what the instance itself has, not what it inherits.
23
+ // `planAgentEditorSync` mirrors that discipline on the way back in — it
24
+ // only ever reads and writes rows whose subject is the one passed in, so an
25
+ // edit to `goblin-1` cannot touch `goblin-2` or the `goblin` class no matter
26
+ // what a pasted line happens to say.
27
+ import {
28
+ AGENT_TRAIT_PREDICATES, AGENT_TRAIT_MULTI, classChainOf, classFactRowsFor,
29
+ traitOriginOf, traitValueOf, traitValuesOf,
30
+ } from "../domain/agent-traits.mjs";
31
+
32
+ const LOW = (s) => String(s || "").trim().toLowerCase();
33
+
34
+ // The closed sentence table for AGENT_TRAIT_PREDICATES, checked in this
35
+ // order (irrelevant here since no two phrases overlap, but kept in
36
+ // AGENT_TRAIT_PREDICATES's own order for readability). One entry per
37
+ // predicate: `sentence` renders a row, `re` parses it back. `mgx:is-predator`
38
+ // carries no object group of its own — the sentence states only "true",
39
+ // mirroring mud-editor.mjs's TRUE_ONLY_FLAG_PREDICATES: a row saying "false"
40
+ // has no sentence here, so it is unrenderable and (by the same rule
41
+ // mud-editor.mjs states) undiffable too.
42
+ const AGENT_LINE_PATTERNS = [
43
+ { predicate: "mgx:consumes", sentence: (s, o) => `${s} eats ${o}.`,
44
+ re: /^(.+?)\s+eats\s+(.+?)\.?$/i },
45
+ { predicate: "mgx:display-name", sentence: (s, o) => `${s} is called ${o}.`,
46
+ re: /^(.+?)\s+is\s+called\s+(.+?)\.?$/i },
47
+ { predicate: "mgx:evades", sentence: (s, o) => `${s} evades ${o}.`,
48
+ re: /^(.+?)\s+evades\s+(.+?)\.?$/i },
49
+ { predicate: "mgx:guards", sentence: (s, o) => `${s} guards ${o}.`,
50
+ re: /^(.+?)\s+guards\s+(.+?)\.?$/i },
51
+ { predicate: "mgx:hasMass", sentence: (s, o) => `${s} weighs ${o}.`,
52
+ // The digit group is a real decimal, not a `[\d.]+` bag: that pattern's
53
+ // trailing period would swallow the sentence's own full stop into the
54
+ // captured number ("8." instead of "8") whenever nothing follows it.
55
+ re: /^(.+?)\s+weighs\s+(\d+(?:\.\d+)?)\.?$/i },
56
+ { predicate: "mgx:is-predator", sentence: (s) => `${s} is a predator.`,
57
+ re: /^(.+?)\s+is\s+a\s+predator\.?$/i, flag: true },
58
+ { predicate: "mgx:mass-drain-per-turn", sentence: (s, o) => `${s} loses ${o} each turn.`,
59
+ re: /^(.+?)\s+loses\s+([\d.]+)\s+each\s+turn\.?$/i },
60
+ { predicate: "mgx:model", sentence: (s, o) => `${s} looks like ${o}.`,
61
+ re: /^(.+?)\s+looks\s+like\s+(.+?)\.?$/i },
62
+ { predicate: "mgx:pursues", sentence: (s, o) => `${s} pursues ${o}.`,
63
+ re: /^(.+?)\s+pursues\s+(.+?)\.?$/i },
64
+ { predicate: "mgx:vision-radius", sentence: (s, o) => `${s} sees ${o} cells.`,
65
+ re: /^(.+?)\s+sees\s+(\d+)\s+cells?\.?$/i },
66
+ ];
67
+
68
+ const NUMERIC_PREDICATES = new Set(["mgx:hasMass", "mgx:mass-drain-per-turn", "mgx:vision-radius"]);
69
+
70
+ const patternFor = (predicate) => AGENT_LINE_PATTERNS.find((p) => p.predicate === predicate);
71
+
72
+ /** One row -> its sentence, or null when the predicate is not on this
73
+ * table's closed set, or when it is `mgx:is-predator` stated "false" (this
74
+ * table has no sentence for that direction, matching mud-editor.mjs's
75
+ * TRUE_ONLY_FLAG rule). Pure. */
76
+ export function agentTraitSentence(subject, predicate, object) {
77
+ const pattern = patternFor(predicate);
78
+ if (!pattern) return null;
79
+ if (pattern.flag && object !== "true") return null;
80
+ return pattern.sentence(subject, object);
81
+ }
82
+
83
+ // ---- rendering -----------------------------------------------------------
84
+
85
+ /** `subject`'s own trait rows (never a class's, never inherited values), as
86
+ * plain sentences, one per line, sorted by (predicate, object) — then a
87
+ * commented block naming what `subject` inherits and from where, read off
88
+ * `traitOriginOf`. A predicate no chain link declares is left out of both
89
+ * halves: an undeclared trait is a gap, never a line to render. The
90
+ * comment lines are never parsed back — `parseAgentEditorText` skips any
91
+ * line starting with "#" — so this half is free to be prose. Pure. */
92
+ export function renderAgentEditorText(rows, subject) {
93
+ const ownRows = classFactRowsFor(rows, subject);
94
+ const ownLines = ownRows
95
+ .map((r) => agentTraitSentence(r.subject, r.predicate, r.object))
96
+ .filter(Boolean);
97
+
98
+ const nearestClass = classChainOf(rows, subject)[1] ?? null;
99
+ const inheritedByClass = new Map();
100
+ for (const predicate of AGENT_TRAIT_PREDICATES) {
101
+ const origin = traitOriginOf(rows, subject, predicate);
102
+ if (!origin || origin === "instance") continue;
103
+ const values = AGENT_TRAIT_MULTI.has(predicate)
104
+ ? traitValuesOf(rows, subject, predicate)
105
+ : [traitValueOf(rows, subject, predicate)];
106
+ if (!inheritedByClass.has(origin)) inheritedByClass.set(origin, []);
107
+ for (const value of values) {
108
+ const line = agentTraitSentence(origin, predicate, value);
109
+ if (line) inheritedByClass.get(origin).push(line);
110
+ }
111
+ }
112
+
113
+ const commentLines = [];
114
+ if (inheritedByClass.size === 0) {
115
+ if (nearestClass) {
116
+ commentLines.push(`# inherited from ${nearestClass} (edit the class to change these for every ${nearestClass}):`);
117
+ commentLines.push(`# ${nearestClass} has no other stated drives.`);
118
+ }
119
+ } else {
120
+ for (const [className, lines] of inheritedByClass) {
121
+ commentLines.push(`# inherited from ${className} (edit the class to change these for every ${className}):`);
122
+ for (const line of lines) commentLines.push(`# ${line}`);
123
+ }
124
+ }
125
+
126
+ return [...ownLines, "", ...commentLines].join("\n");
127
+ }
128
+
129
+ /** `className`'s own trait rows only — no ancestor's, no inherited-block
130
+ * footer. This is what the actor card's class tab shows: editing it writes
131
+ * to `className` itself, and R2's spawn is what carries a change onto the
132
+ * next instance minted from it, never onto one already standing. Pure. */
133
+ export function renderAgentClassText(rows, className) {
134
+ return classFactRowsFor(rows, className)
135
+ .map((r) => agentTraitSentence(r.subject, r.predicate, r.object))
136
+ .filter(Boolean)
137
+ .join("\n");
138
+ }
139
+
140
+ // ---- parsing ---------------------------------------------------------------
141
+
142
+ /** One line -> `{ subject, predicate, object }`, or null when nothing in
143
+ * the table recognizes it — an honest miss, never a guessed triple.
144
+ * `mgx:hasMass`/`mgx:mass-drain-per-turn`/`mgx:vision-radius` keep the
145
+ * digits verbatim (a number has no case to normalise); every other object
146
+ * is lower-cased, matching the lower-cased class and instance names every
147
+ * world in this repo is written in. Pure. */
148
+ export function parseAgentEditorLine(line) {
149
+ const trimmed = String(line || "").trim();
150
+ if (!trimmed) return null;
151
+ for (const pattern of AGENT_LINE_PATTERNS) {
152
+ const m = trimmed.match(pattern.re);
153
+ if (!m) continue;
154
+ const subject = LOW(m[1]);
155
+ if (!subject) continue;
156
+ if (pattern.flag) return { subject, predicate: pattern.predicate, object: "true" };
157
+ const object = NUMERIC_PREDICATES.has(pattern.predicate) ? m[2] : LOW(m[2]);
158
+ if (!object) continue;
159
+ return { subject, predicate: pattern.predicate, object };
160
+ }
161
+ return null;
162
+ }
163
+
164
+ /** Parse the whole actor textarea: every non-blank, non-comment line
165
+ * becomes a triple or lands in `unrecognized` (1-based line numbers, the
166
+ * original text — never silently dropped). A line starting with `#` is the
167
+ * inherited-block prose `renderAgentEditorText` prints; it is neither a
168
+ * triple nor an honest miss, it is simply not read. Pure. */
169
+ export function parseAgentEditorText(text) {
170
+ const triples = [];
171
+ const unrecognized = [];
172
+ String(text || "").split("\n").forEach((raw, i) => {
173
+ const trimmed = raw.trim();
174
+ if (!trimmed || trimmed.startsWith("#")) return;
175
+ const parsed = parseAgentEditorLine(trimmed);
176
+ if (parsed) triples.push(parsed);
177
+ else unrecognized.push({ line: i + 1, text: raw });
178
+ });
179
+ return { triples, unrecognized };
180
+ }
181
+
182
+ // ---- sync planning ---------------------------------------------------------
183
+
184
+ const tripleKey = (t) => `${t.subject} ${t.predicate} ${t.object}`;
185
+
186
+ /** Plan the fact-store writes one actor edit implies, from already-parsed
187
+ * `triples` against `rows`. Scoped to `subject` in both directions: any
188
+ * parsed triple whose own subject is not `subject` is ignored outright
189
+ * (never appended, never used to keep an existing row alive), and only
190
+ * `subject`'s own current trait rows are ever candidates for retraction.
191
+ * That is what makes "editing an instance touches only that instance"
192
+ * true even of a line a visitor typed under someone else's name by
193
+ * mistake. Returns `{ toAppend, toRemoveIds }` — pure, no I/O. The caller
194
+ * decides whether `toRemoveIds` is safe to apply, and must skip it
195
+ * whenever the parse reported any unrecognized line, the same guard
196
+ * `planMudEditorSync`'s own caller holds. */
197
+ export function planAgentEditorSync(rows, subject, triples) {
198
+ const relevant = (triples || []).filter((t) => t.subject === subject);
199
+ const currentRows = (rows || [])
200
+ .filter((r) => r.subject === subject && AGENT_TRAIT_PREDICATES.includes(r.predicate));
201
+ const currentKeys = new Map(currentRows.map((r) => [tripleKey(r), r.id]));
202
+
203
+ const newKeys = new Set();
204
+ const toAppend = [];
205
+ for (const t of relevant) {
206
+ const key = tripleKey(t);
207
+ if (newKeys.has(key)) continue;
208
+ newKeys.add(key);
209
+ if (!currentKeys.has(key)) toAppend.push(t);
210
+ }
211
+ const toRemoveIds = [];
212
+ for (const [key, id] of currentKeys) {
213
+ if (!newKeys.has(key)) toRemoveIds.push(id);
214
+ }
215
+ return { toAppend, toRemoveIds };
216
+ }
@@ -31,6 +31,7 @@ import { resolveGameConfig } from "../domain/game-config.mjs";
31
31
  import { emptyRecord, resolveDiscourseConfig } from "../domain/discourse.mjs";
32
32
  import { resolveRecognitionConfig } from "../domain/router/recognize.mjs";
33
33
  import { resolveResearchConfig } from "./research.mjs";
34
+ import { resolveNewsConfig } from "./news.mjs";
34
35
  import { normalizeResearchChoice } from "../adapters/corpus/research-source.mjs";
35
36
  import { sessionLogHeaderMarkdown, sessionLogTurnMarkdown, sessionLogEndMarkdown } from "./session-log-format.mjs";
36
37
 
@@ -134,6 +135,15 @@ export async function createSession({
134
135
  // --research-source`) > tmct.toml's [research] source > "wikipedia".
135
136
  // Omitted (null) defers entirely to the toml/default tier.
136
137
  researchSource = null,
138
+ // The /news command's fetcher/research-provider set for this session —
139
+ // `{ newsFetchers, getResearchProvider, preflightNewsUrl }` (news.mjs's own
140
+ // ctx.providers shape). Omitted (the default) leaves it to runCommand's own
141
+ // fallback (KB enrichment through the shared research provider, contemporary
142
+ // polling reporting an honest "no-fetcher" per source). The seam a caller —
143
+ // a test, or a host embedding tmct with its own source set — hands in a
144
+ // fixed provider set without touching the network, the same way
145
+ // registerResearchProvider does for the research lane.
146
+ newsProviders = null,
137
147
  // The storage-backend seam: the default (empty or "default") resolves to
138
148
  // Backend C — the sqlite store at .tmct/memory/graph.sqlite, a live
139
149
  // node:sqlite connection lazily imported on open. The flat-file Backend A is
@@ -255,6 +265,12 @@ export async function createSession({
255
265
  // resolved once per session from the same tmct.toml, defaults filling
256
266
  // every unset key exactly as resolveGameConfig does above.
257
267
  const researchConfig = resolveResearchConfig(toml);
268
+ // The news lane's knobs (enabled sources, poll/enrich cadence, the
269
+ // enrichment/negative-cache budgets) — resolved once per session, the same
270
+ // way researchConfig is above. Threaded into every runTurn call as a
271
+ // stable, mutable object, so a `/news add`/`/news interval` mutation
272
+ // persists turn to turn by reference (see runCommand's own /news branch).
273
+ const newsConfig = resolveNewsConfig(toml);
258
274
  // This session's starting research source: the flag tier (`researchSource`,
259
275
  // e.g. `tmct chat --research-source`) over the toml tier over the shipped
260
276
  // default — /wikipedia|/wikidata in chat mutate this turn-to-turn below,
@@ -484,6 +500,7 @@ export async function createSession({
484
500
  // starting null and waiting for a "play <world>" opener line.
485
501
  let planState = adventureWorld ? { adventure: { world: adventureWorld } } : null;
486
502
  let researchState = null; // the in-progress research queue — advanced by "research next", cleared by completion or "research stop"
503
+ let newsState = null; // the news feed's session state (items/ledger/health/requestLog/metrics) — threaded the same way researchState is
487
504
  // The typed discourse record ([discourse] max_referents caps it) — session-scoped
488
505
  // like the focus, threaded turn to turn, never persisted.
489
506
  let discourseRecord = emptyRecord(resolveDiscourseConfig(toml));
@@ -506,6 +523,7 @@ export async function createSession({
506
523
  get lastAnswer() { return last; },
507
524
  get planState() { return planState; },
508
525
  get researchState() { return researchState; },
526
+ get newsState() { return newsState; },
509
527
  get turns() { return turns; },
510
528
  get narrate() { return narrateOn; },
511
529
  get liveReference() { return liveReferenceOn; },
@@ -514,13 +532,15 @@ export async function createSession({
514
532
 
515
533
  /** One dispatched turn through the FULL sink sequencing (writeLog → writeSidecar
516
534
  * → telemetry → upsertGraph, in that exact order). Returns { answer, end, prompt,
517
- * plan, record } — record is the same sidecar turn record the session persists.
518
- * A throwing runTurn must never abort the session: a piped/non-interactive
519
- * driver has no other chance to see this turn's answer. */
535
+ * plan, record, factsTouched } — record is the same sidecar turn record the
536
+ * session persists, and factsTouched is runTurn's own diffed Fact-row list
537
+ * (empty when the turn wrote nothing). A throwing runTurn must never abort
538
+ * the session: a piped/non-interactive driver has no other chance to see
539
+ * this turn's answer. */
520
540
  async turn(line) {
521
541
  let result;
522
542
  try {
523
- result = await runTurn(line, { config, source, graph, focus, last, memoryDir, sessionId, env, lexicon, narrate: narrateOn, liveReference: liveReferenceOn, researchSource: researchSourceOn, vocabHint, tel, biasByBundle, planState, gameConfig, recognitionConfig, researchState, researchConfig, discourse: discourseRecord, actingSubject, codeDomainActive: domainActive, laneVocab, domainPacks });
543
+ result = await runTurn(line, { config, source, graph, focus, last, memoryDir, sessionId, env, lexicon, narrate: narrateOn, liveReference: liveReferenceOn, researchSource: researchSourceOn, vocabHint, tel, biasByBundle, planState, gameConfig, recognitionConfig, researchState, researchConfig, newsState, newsConfig, newsProviders, discourse: discourseRecord, actingSubject, codeDomainActive: domainActive, laneVocab, domainPacks });
524
544
  } catch (e) {
525
545
  const ts = new Date().toISOString();
526
546
  const message = e instanceof Error ? e.message : String(e);
@@ -542,6 +562,7 @@ export async function createSession({
542
562
  last = nextLast;
543
563
  if ("planState" in result) planState = result.planState;
544
564
  if ("researchState" in result) researchState = result.researchState;
565
+ if ("newsState" in result) newsState = result.newsState;
545
566
  if ("discourse" in result) discourseRecord = result.discourse;
546
567
  // /narrate on|off and /wiki on|off (runCommand) ride the turn RESULT the
547
568
  // same way a focus update does — apply them to this handle's
@@ -564,7 +585,7 @@ export async function createSession({
564
585
  });
565
586
  await upsertGraph(record.ts);
566
587
  turns += 1;
567
- return { answer, end: Boolean(end), prompt: promptFor(focus), plan: result.plan ?? null, research: result.research, record };
588
+ return { answer, end: Boolean(end), prompt: promptFor(focus), plan: result.plan ?? null, research: result.research, record, factsTouched: result.factsTouched };
568
589
  },
569
590
 
570
591
  /** End-of-session close: end lines in both artifacts, the final graph upsert