@polycode-projects/the-mechanical-code-talker 5.0.22 → 5.0.23

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.
@@ -15,6 +15,7 @@ import { loadLexicon, withProperNames, classify } from "../domain/grammar/lexico
15
15
  import { register as registerReferent, bind as bindDiscourseForm } from "../domain/discourse.mjs";
16
16
  import { createCompletionsGraphAdapter } from "../domain/completions/graph-adapter.mjs";
17
17
  import { actionFamilies } from "../domain/router/taught.mjs";
18
+ import { declaredGoals, recognizeGoal, traceOfWorldRows } from "../domain/router/recognize.mjs";
18
19
  import { compileDomain, precondHolds, roleBinding } from "../domain/domain.mjs";
19
20
  import { getWorldsPackProvider } from "../adapters/corpus/worlds-pack.mjs";
20
21
  import { appendFacts, appendRule, loadMemory, normFactTerm, readFactRows, readRuleRows } from "../adapters/memory/core.mjs";
@@ -22,6 +23,7 @@ import { COMPLETIONS_STORE, generateCompletion } from "./completions.mjs";
22
23
  import { parseEditorLine, planTaughtTriple } from "./adventure-editor.mjs";
23
24
  import { parseMudEditorLine, planTaughtMudTriple } from "./mud-editor.mjs";
24
25
  import { worldTeachTurn } from "./world-teach.mjs";
26
+ import { expandWorldGoal } from "./adventure-autoplay.mjs";
25
27
 
26
28
  // ---- recognizers: the closed opening/stop set --------------------------------
27
29
 
@@ -2040,6 +2042,17 @@ async function worldOpennessAnswer(line, { memoryDir }) {
2040
2042
  const WORLD_WHERE_AM_I_RE = /^where\s+am\s+i(?:\s+now)?[?.!\s]*$/i;
2041
2043
  const WORLD_OPTIONS_RE = /^(?:what\s+can\s+i\s+do(?:\s+(?:here|now))?|what\s+are\s+my\s+options|what\s+(?:should|do)\s+i\s+do(?:\s+(?:here|now))?|what\s+now)[?.!\s]*$/i;
2042
2044
  const WORLD_QUEST_RE = /^(?:what(?:'s|\s+is)\s+(?:the\s+|my\s+)?(?:quest|goal|objective|mission|aim)|what\s+am\s+i\s+(?:trying\s+to\s+do|(?:supposed|meant)\s+to\s+do)|what\s+do\s+i\s+do\s+here)[?.!\s]*$/i;
2045
+ // "what am I doing" — the RECOGNITION question, and a different one from
2046
+ // WORLD_QUEST_RE's "what is my goal". That asks what the world declared; this
2047
+ // asks what THIS run's own moves fit. The two live side by side because the
2048
+ // answers can honestly disagree: a player heading somewhere the world never
2049
+ // marked has a real goal and no declared one.
2050
+ const WORLD_RECOGNIZE_RE = /^(?:what\s+am\s+i\s+doing(?:\s+(?:here|now))?|what\s+have\s+i\s+been\s+doing|what\s+was\s+i\s+doing)[?.!\s]*$/i;
2051
+ // "what is the housekeeper doing" — the same recognizer, over that character's
2052
+ // own @turnN rows. An NPC's scheduled move writes the same snapshot a player
2053
+ // move writes, so nothing here is NPC-specific beyond which actor's steps the
2054
+ // trace reads.
2055
+ const WORLD_RECOGNIZE_OTHER_RE = /^what(?:'s|\s+is|\s+are)\s+(?:the\s+)?(.+?)\s+doing(?:\s+(?:here|now))?[?.!\s]*$/i;
2043
2056
  // "who is here" — the room's cast, the question a shared world invites the
2044
2057
  // moment a second animal walks in. Answered from the same currently-in
2045
2058
  // placements the talk verb resolves against, so who is named is exactly who
@@ -2063,18 +2076,99 @@ const WORLD_KNOWN_FOOD_RE = new RegExp(
2063
2076
  "i",
2064
2077
  );
2065
2078
 
2079
+ // A recognition tie lists its survivors with a short Oxford-comma "or" join —
2080
+ // the same shape chat.mjs's own joinOr produces for a discourse tie, kept as a
2081
+ // small local copy rather than an import across the file boundary.
2082
+ const joinOr = (a) => (a.length > 2 ? `${a.slice(0, -1).join(", ")}, or ${a[a.length - 1]}`
2083
+ : a.length === 2 ? `${a[0]} or ${a[1]}` : (a[0] ?? ""));
2084
+
2085
+ /** One subject's own @turnN (or @epochE@turnN) rows out of a wider row set —
2086
+ * what traceOfWorldRows folds into a step list. traceOfWorldRows reads
2087
+ * whatever rows it is given; narrowing to one subject here is what keeps a
2088
+ * "what am I doing" trace from reading another actor's moves as its own. */
2089
+ function subjectSnapshotRows(rows, subject) {
2090
+ return (rows || []).filter((row) => parseSnapshotSubject(row.subject)?.base === subject);
2091
+ }
2092
+
2093
+ /** The world's own cast member `spoken` names, matched by plain id (worlds
2094
+ * name their cast in plain lowercase words — "housekeeper", "gardener" —
2095
+ * same as any other individual), or null when nobody in this world goes by
2096
+ * that name. */
2097
+ function resolveCastMemberByName(rows, state, spoken) {
2098
+ const norm = String(spoken).trim().toLowerCase();
2099
+ if (!norm) return null;
2100
+ return worldIndividualNames(rows).find((id) => id.toLowerCase() === norm && isCastMember(rows, state, id)) ?? null;
2101
+ }
2102
+
2103
+ /** `subject`'s room BEFORE any observed step — the base (unstamped) row a
2104
+ * world writes at turn 0, ignoring every later @turnN move. A recognition
2105
+ * plan has to start where the trace itself starts: expandWorldGoal's search
2106
+ * from the subject's CURRENT room would return only the few steps still
2107
+ * left to take, which a trace of the moves already made can never fit. */
2108
+ function subjectStartRoom(actionRows, subject) {
2109
+ const baseRows = actionRows.filter((row) => !parseSnapshotSubject(row.subject));
2110
+ return foldWorldState(baseRows).placements.get(subject)?.object ?? null;
2111
+ }
2112
+
2113
+ /** The recognition surface's four outcomes — recognized, tied, reject, or
2114
+ * nothing observed yet — over `subject`'s own trace. `thirdPerson` renders
2115
+ * the same recognition in the third person for an NPC intent question
2116
+ * instead of the player's own "what am I doing". Only world and taught goals
2117
+ * are in play here (`tools: []` screens out the tool/maintenance goals a
2118
+ * world never declares), so "the goals this world declares" names what it
2119
+ * actually reads as declared, not the whole router's registry. */
2120
+ function recognitionOutcomeAnswer(subject, { actionRows, ruleRows, state, thirdPerson }) {
2121
+ const trace = traceOfWorldRows(subjectSnapshotRows(actionRows, subject), { actor: subject });
2122
+ if (!trace.length) {
2123
+ return answer(
2124
+ "you haven't done anything yet — make a move and ask again.",
2125
+ `ADVENTURE — recognition aside: no observed step for ${subject} yet`,
2126
+ { goal: "see what I'm recognized as doing" },
2127
+ );
2128
+ }
2129
+ const goals = declaredGoals({ worldRows: actionRows, ruleRows }, { tools: [] });
2130
+ const origin = subjectStartRoom(actionRows, subject);
2131
+ const expand = (goal) => (origin ? expandWorldGoal(goal, { here: origin, exposedRows: actionRows, exposedState: state }) : []);
2132
+ const r = recognizeGoal(trace, goals, { expand });
2133
+ const note = `ADVENTURE — recognition aside: ${trace.length} observed step(s) against ${goals.length} declared goal(s); ${r.why}`;
2134
+
2135
+ if (r.goal) {
2136
+ const target = r.goal.label.replace(/^carry /, "");
2137
+ const text = thirdPerson
2138
+ ? `the ${subject} is heading for ${target} — the last ${trace.length} moves it made are a subsequence of the route that gets there.`
2139
+ : `you're heading for ${target} — your last ${trace.length} move${trace.length === 1 ? "" : "s"} ${trace.length === 1 ? "is" : "are"} a subsequence of the route that gets you there.`;
2140
+ return answer(text, note, { goal: "see what I'm recognized as doing" });
2141
+ }
2142
+ if (r.reject) {
2143
+ const text = thirdPerson
2144
+ ? `nothing the ${subject} has done fits any of the ${goals.length} goals this world declares.`
2145
+ : `nothing you've done so far fits any of the ${goals.length} goals this world declares. Say "what is my goal" to see what it does declare.`;
2146
+ return answer(text, note, { miss: true, goal: "see what I'm recognized as doing" });
2147
+ }
2148
+ const labels = r.ambiguous.map((g) => g.label);
2149
+ const text = thirdPerson
2150
+ ? `what the ${subject} has done so far fits ${labels.length} goals equally well: ${joinOr(labels)}. A few more moves would tell them apart.`
2151
+ : `what you've done so far fits ${labels.length} goals equally well: ${joinOr(labels)}. A few more moves would tell them apart, so I won't pick one.`;
2152
+ return answer(text, note, { goal: "see what I'm recognized as doing" });
2153
+ }
2154
+
2066
2155
  /** The in-game orientation asides, answered from the world fold: the player's
2067
- * room, the room's real affordances, and the world's objective. Null when the
2068
- * line is none of them, so an ordinary question keeps its lane. */
2156
+ * room, the room's real affordances, the world's objective, and what a
2157
+ * trace — the player's own, or a named character's — is recognized as
2158
+ * doing. Null when the line is none of them, so an ordinary question keeps
2159
+ * its lane. */
2069
2160
  async function worldContextAnswer(line, { memoryDir, actingSubject = "player" }) {
2070
2161
  const l = String(line).trim();
2071
2162
  const asksWhere = WORLD_WHERE_AM_I_RE.test(l);
2072
2163
  const asksOptions = WORLD_OPTIONS_RE.test(l);
2073
2164
  const asksQuest = WORLD_QUEST_RE.test(l);
2074
2165
  const asksWhoIsHere = WORLD_WHO_HERE_RE.test(l);
2075
- if (!asksWhere && !asksOptions && !asksQuest && !asksWhoIsHere) return null;
2076
- let rows;
2077
- try { rows = readFactRows(await loadMemory(memoryDir)); } catch { return null; }
2166
+ const asksRecognize = WORLD_RECOGNIZE_RE.test(l);
2167
+ const recognizeOther = WORLD_RECOGNIZE_OTHER_RE.exec(l);
2168
+ if (!asksWhere && !asksOptions && !asksQuest && !asksWhoIsHere && !asksRecognize && !recognizeOther) return null;
2169
+ let memory;
2170
+ try { memory = await loadMemory(memoryDir); } catch { return null; }
2171
+ const rows = readFactRows(memory);
2078
2172
  const state = foldWorldState(worldActionRows(rows));
2079
2173
  const here = state.placements.get(actingSubject)?.object ?? null;
2080
2174
 
@@ -2104,6 +2198,27 @@ async function worldContextAnswer(line, { memoryDir, actingSubject = "player" })
2104
2198
  );
2105
2199
  }
2106
2200
 
2201
+ if (asksRecognize) {
2202
+ const actionRows = worldActionRows(rows);
2203
+ const ruleRows = readRuleRows(memory);
2204
+ return recognitionOutcomeAnswer(actingSubject, { actionRows, ruleRows, state, thirdPerson: false });
2205
+ }
2206
+
2207
+ if (recognizeOther) {
2208
+ const spoken = recognizeOther[1].trim();
2209
+ const resolved = resolveCastMemberByName(rows, state, spoken);
2210
+ if (!resolved) {
2211
+ return answer(
2212
+ `there's nobody called "${spoken}" in this world.`,
2213
+ `ADVENTURE — recognition aside: "${spoken}" resolves to no cast member this world names`,
2214
+ { miss: true },
2215
+ );
2216
+ }
2217
+ const actionRows = worldActionRows(rows);
2218
+ const ruleRows = readRuleRows(memory);
2219
+ return recognitionOutcomeAnswer(resolved, { actionRows, ruleRows, state, thirdPerson: true });
2220
+ }
2221
+
2107
2222
  const objectiveId = rows.find((r) => r.predicate === "mgx:is-objective" && r.object === "true")?.subject ?? null;
2108
2223
  return objectiveId
2109
2224
  ? answer(
@@ -29,6 +29,7 @@ import { resolveExtensions, mergedLexiconExtra, mergedLaneVocab, defaultCodeLane
29
29
  import { runTurn, hasSeededVocabulary, vocabExampleHint, codeDomainActive as codeDomainActiveOf } from "./chat.mjs";
30
30
  import { resolveGameConfig } from "../domain/game-config.mjs";
31
31
  import { emptyRecord, resolveDiscourseConfig } from "../domain/discourse.mjs";
32
+ import { resolveRecognitionConfig } from "../domain/router/recognize.mjs";
32
33
  import { resolveResearchConfig } from "./research.mjs";
33
34
  import { normalizeResearchChoice } from "../adapters/corpus/research-source.mjs";
34
35
  import { sessionLogHeaderMarkdown, sessionLogTurnMarkdown, sessionLogEndMarkdown } from "./session-log-format.mjs";
@@ -486,6 +487,9 @@ export async function createSession({
486
487
  // The typed discourse record ([discourse] max_referents caps it) — session-scoped
487
488
  // like the focus, threaded turn to turn, never persisted.
488
489
  let discourseRecord = emptyRecord(resolveDiscourseConfig(toml));
490
+ // The recognition trace cap ([recognition] max_trace) — resolved once per
491
+ // session, read by the surfaces that fold a trace back out of the store.
492
+ const recognitionConfig = resolveRecognitionConfig(toml);
489
493
  let closed = false;
490
494
 
491
495
  return {
@@ -516,7 +520,7 @@ export async function createSession({
516
520
  async turn(line) {
517
521
  let result;
518
522
  try {
519
- result = await runTurn(line, { config, source, graph, focus, last, memoryDir, sessionId, env, lexicon, narrate: narrateOn, liveReference: liveReferenceOn, researchSource: researchSourceOn, vocabHint, tel, biasByBundle, planState, gameConfig, researchState, researchConfig, discourse: discourseRecord, actingSubject, codeDomainActive: domainActive, laneVocab, domainPacks });
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 });
520
524
  } catch (e) {
521
525
  const ts = new Date().toISOString();
522
526
  const message = e instanceof Error ? e.message : String(e);
@@ -7348,6 +7348,7 @@ export async function helpText(codeDomainActive = false, helpRows = undefined) {
7348
7348
  ["/focus <symbol>", "set the current focus (reused by 'it'/'this' and no-arg entity commands)"],
7349
7349
  ["/plan <request>", "the capability router: plan+execute a compound or maintenance-goal request (\"of the modules impacted by X, which are untested\", \"what most needs a test\")"],
7350
7350
  ["/capabilities", "what /plan can plan over: the built-in graph tools plus your taught actions"],
7351
+ ["/goals", "the goals a trace can be recognized against: the maintenance invariants, the tool goals, this world's objective, and your taught actions"],
7351
7352
  ["/syllogise <term>", "work out and remember what follows from the facts about a term (needed for chains longer than 2 hops)"],
7352
7353
  ["/export <path>", "write the memory store to a file, as JSONL (the same shape `tmct memory --export` writes)"],
7353
7354
  ["/ingest <path>", "read a local text file and store every fact the recognizer grounds from it (same recognizer as `tmct extract`)"],
@@ -15582,6 +15583,7 @@ const GOAL_BY_COMMAND = {
15582
15583
  exports: GOAL_BY_KIND.reexports,
15583
15584
  arch: "understand the overall architecture (package/module boundaries)",
15584
15585
  capabilities: "see what /plan can plan over — built-in query tools and taught actions",
15586
+ goals: "see the declared goals a trace is recognized against, and where each one came from",
15585
15587
  syllogise: "materialize the entailed facts that follow from what's remembered about one term",
15586
15588
  wiki: "toggle the live Wikipedia supplement for questions nothing local can answer",
15587
15589
  wikipedia: "choose which source the research lane fetches from",
@@ -15610,6 +15612,58 @@ function domainPackLine({ name, groundingKind, groundingAdapter, commandCount, c
15610
15612
  return parts.length ? `${name} — ${parts.join("; ")}` : String(name);
15611
15613
  }
15612
15614
 
15615
+ const GOAL_ID_COLUMN = 21;
15616
+
15617
+ /** One /goals (or `tmct plan --goals`) listing row: the id padded to a fixed
15618
+ * column, the goal's own label, and an optional short provenance tail. */
15619
+ function goalListingRow(goal, tail) {
15620
+ return ` ${goal.id.padEnd(GOAL_ID_COLUMN)}— ${goal.label}${tail ? ` (${tail})` : ""}`;
15621
+ }
15622
+
15623
+ /** The declared goal set, grouped by source in the order a reader reasons
15624
+ * about them: the maintenance invariants first (they're deduced, not
15625
+ * declared per-tool), the tool goals, this world's own objective, then the
15626
+ * taught actions. An empty world/taught group still prints one line, so the
15627
+ * reader can tell "none declared" from "not looked for" — /goals and
15628
+ * `tmct plan --goals` share this renderer so the two surfaces never drift. */
15629
+ export function renderDeclaredGoals(goals) {
15630
+ const bySource = (source) => goals.filter((g) => g.source === source);
15631
+ const goalRules = bySource("goal-rules");
15632
+ const capGoals = bySource("capability");
15633
+ const worldGoals = bySource("world");
15634
+ const taughtGoals = bySource("taught");
15635
+
15636
+ const lines = [`${goals.length} declared goals — a trace that fits none of them is a reject, and I say so.`, ""];
15637
+
15638
+ lines.push(`maintenance invariants (${goalRules.length}):`);
15639
+ for (const g of goalRules) lines.push(goalListingRow(g, g.provenance.split(" — ")[0]));
15640
+ lines.push("");
15641
+
15642
+ lines.push(`tool goals (${capGoals.length}), one per declared capability:`);
15643
+ for (const g of capGoals) lines.push(goalListingRow(g, null));
15644
+ lines.push("");
15645
+
15646
+ if (worldGoals.length) {
15647
+ lines.push(`this world's objective (${worldGoals.length}):`);
15648
+ for (const g of worldGoals) lines.push(goalListingRow(g, g.provenance.replace(/^world marker /, "")));
15649
+ } else {
15650
+ lines.push("this world's objective: none — no world is loaded, so nothing marks an objective.");
15651
+ }
15652
+ lines.push("");
15653
+
15654
+ if (taughtGoals.length) {
15655
+ lines.push(`taught actions (${taughtGoals.length}):`);
15656
+ for (const g of taughtGoals) {
15657
+ const tail = g.provenance.split("; ").map((part) => part.split(" — effect ")[0]).join(", ");
15658
+ lines.push(goalListingRow(g, tail));
15659
+ }
15660
+ } else {
15661
+ lines.push('taught actions: none yet — teach one ("you can move a disk onto a peg.") and it joins this list.');
15662
+ }
15663
+
15664
+ return lines.join("\n").replace(/\n+$/, "");
15665
+ }
15666
+
15613
15667
  async function runCommand(line, { config, source, graph, focus, memoryDir, trace, narrate = false, liveReference = false, researchSource = null, tel = null, biasByBundle = {}, cache = null, codeDomainActive = false, laneVocab = null, domainPacks = null }) {
15614
15668
  const ts = new Date().toISOString();
15615
15669
  const sp = line.indexOf(" ");
@@ -15753,6 +15807,28 @@ async function runCommand(line, { config, source, graph, focus, memoryDir, trace
15753
15807
  return mk(lines.join("\n"));
15754
15808
  }
15755
15809
 
15810
+ // /goals — the bounded set a recognized trace is checked against: the
15811
+ // maintenance invariants the goal-reasoner deduces, one goal per declared
15812
+ // tool, this world's own objective marker, and the taught actions' effect
15813
+ // states. Printable on purpose: "the trace fits none of these" only reads as
15814
+ // honest when you can see the set it did not fit.
15815
+ if (name === "goals") {
15816
+ note(trace, "goal: see the declared goals a trace is recognized against, and where each one came from");
15817
+ const { declaredGoals } = await import("../domain/router/recognize.mjs");
15818
+ let worldRows = [];
15819
+ let ruleRows = [];
15820
+ if (memoryDir) {
15821
+ try {
15822
+ const { loadMemory, readFactRows, readRuleRows } = await import("../adapters/memory/core.mjs");
15823
+ const memory = await loadMemory(memoryDir);
15824
+ worldRows = readFactRows(memory);
15825
+ ruleRows = readRuleRows(memory);
15826
+ } catch { /* an unreadable store lists like an empty one */ }
15827
+ }
15828
+ const goals = declaredGoals({ worldRows, ruleRows });
15829
+ return mk(renderDeclaredGoals(goals));
15830
+ }
15831
+
15756
15832
  // /syllogise <term> — forward-chain what's remembered about <term> into
15757
15833
  // entailed facts and WRITE them to the store, so a chain too long for the
15758
15834
  // live isa ladder to walk becomes a single stored step it can read.