@polycode-projects/the-mechanical-code-talker 5.0.21 → 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.
- package/README.md +4 -0
- package/bin/tmct.mjs +20 -5
- package/package.json +1 -1
- package/src/adapters/toml-config.mjs +5 -0
- package/src/domain/cli-verbs.mjs +1 -0
- package/src/domain/domain.mjs +8 -0
- package/src/domain/interpret/normalize.mjs +86 -1
- package/src/domain/router/drive.mjs +45 -4
- package/src/domain/router/recognize.mjs +345 -0
- package/src/domain/scene-compose.mjs +54 -16
- package/src/domain/scene-random.mjs +104 -0
- package/src/domain/sprite-animation.mjs +102 -0
- package/src/domain/world-snapshot.mjs +25 -0
- package/src/services/adventure-autoplay.mjs +41 -5
- package/src/services/adventure.mjs +137 -34
- package/src/services/chat-session.mjs +5 -1
- package/src/services/chat.mjs +401 -13
- package/src/services/sprite-catalog-viz.mjs +408 -184
- package/src/surfaces/web/adventure-browser-entry.mjs +11 -0
- package/src/surfaces/web/memory-ask-browser.bundle.js +119 -119
- package/src/surfaces/web/sprites-browser-entry.mjs +17 -2
package/src/services/chat.mjs
CHANGED
|
@@ -40,7 +40,7 @@ import {
|
|
|
40
40
|
stripTrailingScopeFiller, stripTrailingDiscourseTag, EDGE_NOUN_TO_METRIC, RELATIONS, LIST_TRIGGERS,
|
|
41
41
|
locativePreposition,
|
|
42
42
|
} from "../domain/ask-vocab.mjs";
|
|
43
|
-
import { COUNTERFACTUAL_RE, correctMisspellings, applyPreambleFrames, expandContractions, normalizeQuery, stripFillerWords, escapeRegex, kindNounAnaphoraHint, datedTeachSuffix, QUESTION_LEAD_RE } from "../domain/interpret/normalize.mjs";
|
|
43
|
+
import { COUNTERFACTUAL_RE, correctMisspellings, applyPreambleFrames, expandContractions, normalizeQuery, stripFillerWords, escapeRegex, kindNounAnaphoraHint, datedTeachSuffix, QUESTION_LEAD_RE, fillerClausePrefix, leadsInterrogative } from "../domain/interpret/normalize.mjs";
|
|
44
44
|
import { setDefaultNlpAdapter } from "../domain/interpret/nlp-registry.mjs";
|
|
45
45
|
import { setConstructionBanks } from "../domain/interpret/strategies/constructions.mjs";
|
|
46
46
|
import { nlpAdapter } from "../adapters/ask-nlp.mjs";
|
|
@@ -3175,7 +3175,7 @@ async function repairSharesLemma(from, to) {
|
|
|
3175
3175
|
* infix is unambiguous taxonomy-teach intent and the ACE path can't parse
|
|
3176
3176
|
* the two-word object; single-word objects stay with the ACE path. */
|
|
3177
3177
|
async function bareTaxonomyTeach(line, { memoryDir, sessionId }) {
|
|
3178
|
-
if (!memoryDir ||
|
|
3178
|
+
if (!memoryDir || leadsInterrogative(line)) return null;
|
|
3179
3179
|
if (/\?\s*$/.test(String(line).trim())) return null; // a question never writes
|
|
3180
3180
|
const inst = line.match(INSTANCE_TYPE_TEACH_RE);
|
|
3181
3181
|
if (inst) {
|
|
@@ -3272,11 +3272,44 @@ const PLAN_OPTIMALITY_CONFIRM_RE = /^(?:is\s+(?:that|this)\s+(?:really|actually)
|
|
|
3272
3272
|
// SAME reason the planner already printed, unprompted, right after "plan
|
|
3273
3273
|
// found — N moves (shortest)". Re-displays the stored becauseText (below)
|
|
3274
3274
|
// rather than an honest miss; a genuinely different justification question
|
|
3275
|
-
// ("why did you
|
|
3276
|
-
//
|
|
3277
|
-
//
|
|
3275
|
+
// ("why did you move X instead of Y", "what if X started elsewhere") is
|
|
3276
|
+
// answered by the counterfactual recognizers below instead, each re-solving
|
|
3277
|
+
// the BFS rather than re-displaying this text.
|
|
3278
3278
|
const PLAN_WHY_SHORTEST_RE = /^why\s+(?:is|was)\s+(?:that|this|it)\s+the\s+shortest\s+(?:solution|plan|path|way)[?.!\s]*$/i;
|
|
3279
3279
|
const PLAN_WHY_MOVE_RE = /^why\s+(?:that|this|the\s+next|the)\s+move[?.!\s]*$/i;
|
|
3280
|
+
// "what if disk-1 started on peg-c instead?" / "what if disk-3 rested on peg-b
|
|
3281
|
+
// at the start?" — a counterfactual PREMISE about where a piece began, answered
|
|
3282
|
+
// by re-running the same BFS from a modified start state. Active only while a
|
|
3283
|
+
// plan stands; the piece and the place must both be taught individuals, or the
|
|
3284
|
+
// branch declines and the honest miss stands.
|
|
3285
|
+
const PLAN_WHAT_IF_START_RE = new RegExp(
|
|
3286
|
+
"^(?:and\\s+|so\\s+|but\\s+)?what\\s+if\\s+([\\w-]+)\\s+"
|
|
3287
|
+
+ "(?:had\\s+)?(?:started|start|starts|begun|began|begins|was|were|is|had\\s+been"
|
|
3288
|
+
+ "|rested|rests|sat|sits|stood|stands|lay|lies|lain)"
|
|
3289
|
+
+ `(?:\\s+(?:out|off))?\\s+(?:${PREP_SRC})\\s+([\\w-]+)`
|
|
3290
|
+
+ "(?:\\s+(?:instead|initially|to\\s+start\\s+with|at\\s+the\\s+start"
|
|
3291
|
+
+ "|from\\s+the\\s+start|at\\s+the\\s+beginning))?[?.!\\s]*$", "i",
|
|
3292
|
+
);
|
|
3293
|
+
// "why did you move disk-1 first instead of disk-2?" / "why move disk-1 onto
|
|
3294
|
+
// peg-c instead of peg-b?" — a contrastive question. Answered by forcing the
|
|
3295
|
+
// named alternative as the first move and comparing the outcome against the
|
|
3296
|
+
// plan that was found.
|
|
3297
|
+
const PLAN_WHY_ALTERNATIVE_RE = new RegExp(
|
|
3298
|
+
"^(?:and\\s+|so\\s+|but\\s+)?why\\s+(?:did\\s+you\\s+|do\\s+you\\s+|would\\s+you\\s+)?"
|
|
3299
|
+
+ "(?:choose\\s+to\\s+|decide\\s+to\\s+)?([a-z]+)\\s+([\\w-]+)"
|
|
3300
|
+
+ `(?:\\s+(?:${PREP_SRC})\\s+([\\w-]+))?`
|
|
3301
|
+
+ "(?:\\s+(?:first|initially|at\\s+the\\s+start|to\\s+start(?:\\s+with)?|to\\s+begin(?:\\s+with)?))?"
|
|
3302
|
+
+ "\\s+(?:instead\\s+of|rather\\s+than|and\\s+not|not)\\s+([\\w-]+)[?.!\\s]*$", "i",
|
|
3303
|
+
);
|
|
3304
|
+
// "why not move disk-2 first?" / "why didn't you move disk-2 onto peg-b?" —
|
|
3305
|
+
// the same contrastive question with the alternative named alone. The plan's
|
|
3306
|
+
// own first move supplies the A side.
|
|
3307
|
+
const PLAN_WHY_NOT_ALTERNATIVE_RE = new RegExp(
|
|
3308
|
+
"^(?:and\\s+|so\\s+|but\\s+)?why\\s+(?:not|didn'?t\\s+you|did\\s+you\\s+not|couldn'?t\\s+you)\\s+"
|
|
3309
|
+
+ "([a-z]+)\\s+([\\w-]+)"
|
|
3310
|
+
+ `(?:\\s+(?:${PREP_SRC})\\s+([\\w-]+))?`
|
|
3311
|
+
+ "(?:\\s+(?:first|initially|at\\s+the\\s+start|to\\s+start(?:\\s+with)?))?[?.!\\s]*$", "i",
|
|
3312
|
+
);
|
|
3280
3313
|
// Board-state read-backs, answered off the CURRENT board (the latest @stepK
|
|
3281
3314
|
// snapshot, or the taught board before any step) so a read never contradicts
|
|
3282
3315
|
// the plan's own board@stepK line. Clearness is derived, never stored: a piece
|
|
@@ -5295,7 +5328,7 @@ async function teachLane(query, { memoryDir, sessionId = "", lexicon = null, cac
|
|
|
5295
5328
|
// anchored QUESTION_LEAD_RE gate below — run the SAME closed misspelling
|
|
5296
5329
|
// repair ask.mjs's typo tolerance applies BEFORE classifying, so the
|
|
5297
5330
|
// question goes back to the question side instead of a teach suggestion.
|
|
5298
|
-
if (
|
|
5331
|
+
if (leadsInterrogative(correctMisspellings(rawInput))) return null;
|
|
5299
5332
|
const m = rawInput.match(TEACH_RE);
|
|
5300
5333
|
const wrappedInput = m ? m[1].trim() : null;
|
|
5301
5334
|
// The positive exclusion test (teachExclusionReason, above) — BARE surface
|
|
@@ -7315,6 +7348,7 @@ export async function helpText(codeDomainActive = false, helpRows = undefined) {
|
|
|
7315
7348
|
["/focus <symbol>", "set the current focus (reused by 'it'/'this' and no-arg entity commands)"],
|
|
7316
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\")"],
|
|
7317
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"],
|
|
7318
7352
|
["/syllogise <term>", "work out and remember what follows from the facts about a term (needed for chains longer than 2 hops)"],
|
|
7319
7353
|
["/export <path>", "write the memory store to a file, as JSONL (the same shape `tmct memory --export` writes)"],
|
|
7320
7354
|
["/ingest <path>", "read a local text file and store every fact the recognizer grounds from it (same recognizer as `tmct extract`)"],
|
|
@@ -13347,6 +13381,128 @@ async function executePlanStep(planHolder, { memoryDir, sessionId = "", gameConf
|
|
|
13347
13381
|
};
|
|
13348
13382
|
}
|
|
13349
13383
|
|
|
13384
|
+
/** Rebuild the plan's start board with one piece moved. Replaces every row
|
|
13385
|
+
* whose SUBJECT is the piece and whose predicate is a locative (the piece
|
|
13386
|
+
* can only be in one place), keeps every other row byte-identical, and
|
|
13387
|
+
* returns the rows in their original order with the replacement in the
|
|
13388
|
+
* original row's slot — the state key is order-sensitive, so a rebuild
|
|
13389
|
+
* that reorders rows would read as a different state to the search.
|
|
13390
|
+
* Returns null when the piece has no locative row on the taught board
|
|
13391
|
+
* (nothing to counterfactualize). */
|
|
13392
|
+
function boardWithPieceMoved(startRows, piece, place) {
|
|
13393
|
+
const idx = startRows.findIndex((r) => r.subject === piece && locativePreposition(r.predicate) !== null);
|
|
13394
|
+
if (idx < 0) return null;
|
|
13395
|
+
const rows = startRows.slice();
|
|
13396
|
+
rows[idx] = { ...rows[idx], object: place };
|
|
13397
|
+
return rows;
|
|
13398
|
+
}
|
|
13399
|
+
|
|
13400
|
+
/** Which slot does the named alternative belong in? Answered from the
|
|
13401
|
+
* taught class membership, so a target-class alternative forces the
|
|
13402
|
+
* target and a subject-class alternative forces the subject. Returns
|
|
13403
|
+
* "subject", "target", or null when the alternative shares no taught
|
|
13404
|
+
* class with either side of the chosen move — the branch declines and
|
|
13405
|
+
* the honest miss stands. */
|
|
13406
|
+
function forcedSlotFor(alternative, chosenSubject, chosenTarget, domain) {
|
|
13407
|
+
const classesOf = (t) => Object.keys(domain.classMembers || {})
|
|
13408
|
+
.filter((cls) => (domain.classMembers[cls] || []).includes(t));
|
|
13409
|
+
const alt = new Set(classesOf(alternative));
|
|
13410
|
+
if (!alt.size) return null;
|
|
13411
|
+
if (chosenTarget && classesOf(chosenTarget).some((c) => alt.has(c))) return "target";
|
|
13412
|
+
if (classesOf(chosenSubject).some((c) => alt.has(c))) return "subject";
|
|
13413
|
+
return null;
|
|
13414
|
+
}
|
|
13415
|
+
|
|
13416
|
+
/** Normalize a forced-alternative match (the "instead of B" voicing or the
|
|
13417
|
+
* "why not B" voicing) into which slot B replaces. The chosen A side
|
|
13418
|
+
* always comes from the plan's own first move, never from the sentence,
|
|
13419
|
+
* so the comparison is against the SAME move a cold "what is the next
|
|
13420
|
+
* move" would report. */
|
|
13421
|
+
function resolveForcedAlternative(alternativeRaw, chosen, domain, normFactTerm) {
|
|
13422
|
+
const forced = normFactTerm(alternativeRaw);
|
|
13423
|
+
const slot = forcedSlotFor(forced, chosen.subject, chosen.target, domain);
|
|
13424
|
+
return { slot, forced };
|
|
13425
|
+
}
|
|
13426
|
+
|
|
13427
|
+
/** predicatePhrase's head verb, based rather than third-person: "rests on"
|
|
13428
|
+
* -> "rest on". The precondition clauses below read as the taught rule's
|
|
13429
|
+
* own wording ("nothing may rest on…"), never a report ("rests on…"). */
|
|
13430
|
+
function basePhraseOf(predicate) {
|
|
13431
|
+
const phrase = predicatePhrase(predicate);
|
|
13432
|
+
const [head, ...tail] = phrase.split(" ");
|
|
13433
|
+
return [baseVerbSurface(head), ...tail].join(" ");
|
|
13434
|
+
}
|
|
13435
|
+
|
|
13436
|
+
/** The bare comparative words a "-than" predicate folds ("mgx:smaller-than"
|
|
13437
|
+
* -> "smaller than"), without predicatePhrase's own leading "is". */
|
|
13438
|
+
function comparativeWords(predicate) {
|
|
13439
|
+
const m = /^mgx:([a-z]+(?:-[a-z]+)*)-than$/i.exec(String(predicate || ""));
|
|
13440
|
+
return m ? m[1].replace(/-/g, " ") : predicatePhrase(predicate);
|
|
13441
|
+
}
|
|
13442
|
+
|
|
13443
|
+
/** Why can the forced piece not take the given slot in a first move? Walks
|
|
13444
|
+
* every candidate grounding of every taught action with the forced piece
|
|
13445
|
+
* in that slot, records the first precondition each grounding fails, and
|
|
13446
|
+
* names the one that blocked the most of them. Deterministic: actions,
|
|
13447
|
+
* signatures and members are walked in compileDomain's own fixed sort
|
|
13448
|
+
* order, so a tie always breaks the same way. Returns { clause, witness }
|
|
13449
|
+
* or null when the forced piece has no candidate grounding at all to
|
|
13450
|
+
* explain (nothing identifiable blocked it). */
|
|
13451
|
+
async function firstBlockingPrecond(forced, slot, state, domain) {
|
|
13452
|
+
const { precondHolds } = await import("../domain/domain.mjs");
|
|
13453
|
+
const scopeMembers = (cls) => domain.taughtClassMembers?.[cls] || [];
|
|
13454
|
+
const precondAppliesLocal = (precond, target) =>
|
|
13455
|
+
precond.scope === "any" || (domain.classMembers[precond.scope] || []).includes(target);
|
|
13456
|
+
const tally = new Map();
|
|
13457
|
+
const order = [];
|
|
13458
|
+
for (const action of domain.actions) {
|
|
13459
|
+
for (const sig of action.signatures) {
|
|
13460
|
+
if (slot === "subject" && !scopeMembers(sig.subjectClass).includes(forced)) continue;
|
|
13461
|
+
if (slot === "target" && !scopeMembers(sig.targetClass).includes(forced)) continue;
|
|
13462
|
+
const subjects = slot === "subject" ? [forced] : scopeMembers(sig.subjectClass);
|
|
13463
|
+
const targets = slot === "target" ? [forced] : scopeMembers(sig.targetClass);
|
|
13464
|
+
for (const subject of subjects) {
|
|
13465
|
+
for (const target of targets) {
|
|
13466
|
+
if (subject === target) continue;
|
|
13467
|
+
for (const precond of action.preconds) {
|
|
13468
|
+
if (!precondAppliesLocal(precond, target)) continue;
|
|
13469
|
+
if (precondHolds(precond, subject, target, state, domain)) continue;
|
|
13470
|
+
const key = JSON.stringify(precond);
|
|
13471
|
+
if (!tally.has(key)) { tally.set(key, { count: 0, precond, action }); order.push(key); }
|
|
13472
|
+
tally.get(key).count += 1;
|
|
13473
|
+
break;
|
|
13474
|
+
}
|
|
13475
|
+
}
|
|
13476
|
+
}
|
|
13477
|
+
}
|
|
13478
|
+
}
|
|
13479
|
+
if (!tally.size) return null;
|
|
13480
|
+
let best = null;
|
|
13481
|
+
for (const key of order) {
|
|
13482
|
+
const entry = tally.get(key);
|
|
13483
|
+
if (!best || entry.count > best.count) best = entry;
|
|
13484
|
+
}
|
|
13485
|
+
const { precond: p, action } = best;
|
|
13486
|
+
const role = p.role === "target" ? "the target" : "the piece you move";
|
|
13487
|
+
if (p.shape === "no-incoming") {
|
|
13488
|
+
// The winning precond's own role almost always matches the forced
|
|
13489
|
+
// slot: it is the one that can fail for every candidate grounding
|
|
13490
|
+
// regardless of the OTHER slot's value, which is exactly what makes it
|
|
13491
|
+
// the highest tally. So the state row that names the forced piece as
|
|
13492
|
+
// the blocked object is the row worth citing.
|
|
13493
|
+
const witnessRow = state.find((r) => r.predicate === p.predicate && r.object === forced);
|
|
13494
|
+
return { clause: `your "${action.name}" rule says nothing may ${basePhraseOf(p.predicate)} ${role}`, witness: witnessRow ? factPhrase(witnessRow) : null };
|
|
13495
|
+
}
|
|
13496
|
+
if (p.shape === "comparator") {
|
|
13497
|
+
return { clause: `your "${action.name}" rule says the piece you move must be ${comparativeWords(p.predicate)} the target`, witness: null };
|
|
13498
|
+
}
|
|
13499
|
+
if (p.shape === "fact-value") {
|
|
13500
|
+
const witnessRow = state.find((r) => r.subject === forced && r.predicate === p.predicate);
|
|
13501
|
+
return { clause: `your "${action.name}" rule says the ${p.role} must${p.negate ? " not" : ""} ${basePhraseOf(p.predicate)}${p.value ? ` ${p.value}` : ""}`, witness: witnessRow ? factPhrase(witnessRow) : null };
|
|
13502
|
+
}
|
|
13503
|
+
return null;
|
|
13504
|
+
}
|
|
13505
|
+
|
|
13350
13506
|
/** Plan follow-up questions ("what is the next move", "how many moves", "why
|
|
13351
13507
|
* that move") answered off the ACTIVE plan, and board-state questions ("is X
|
|
13352
13508
|
* clear", "what rests on X", "where is X") answered off the CURRENT board (the
|
|
@@ -13357,7 +13513,7 @@ async function executePlanStep(planHolder, { memoryDir, sessionId = "", gameConf
|
|
|
13357
13513
|
* "next" moves a piece, "what rests on X" reflects the snapshot, not the stale
|
|
13358
13514
|
* pre-plan facts. Clearness is derived, never stored — a piece is clear iff
|
|
13359
13515
|
* nothing rests on it on the current board. */
|
|
13360
|
-
async function planFollowUpAnswer(query, { memoryDir, planHolder, pendingPager = false }) {
|
|
13516
|
+
async function planFollowUpAnswer(query, { memoryDir, planHolder, pendingPager = false, gameConfig = DEFAULT_GAME_CONFIG }) {
|
|
13361
13517
|
const q = String(query).trim();
|
|
13362
13518
|
const ps = planHolder?.state;
|
|
13363
13519
|
const activePlan = ps && Array.isArray(ps.actions) && ps.actions.length;
|
|
@@ -13443,6 +13599,139 @@ async function planFollowUpAnswer(query, { memoryDir, planHolder, pendingPager =
|
|
|
13443
13599
|
return { text: `${line} — it is this step's move on the shortest path.`, deduced: "explain the next planned move", note: "PLAN FOLLOW-UP — why-move from the active plan's step goals" };
|
|
13444
13600
|
}
|
|
13445
13601
|
|
|
13602
|
+
// COUNTERFACTUAL PREMISE — "what if <piece> started <place> instead?" rebuilds
|
|
13603
|
+
// the plan's own start board with one piece moved, then re-runs the same BFS
|
|
13604
|
+
// from it. Read-only: planHolder.state is never written here, so the held
|
|
13605
|
+
// plan and its cursor survive the question unchanged.
|
|
13606
|
+
const whatIf = q.match(PLAN_WHAT_IF_START_RE);
|
|
13607
|
+
if (whatIf) {
|
|
13608
|
+
if (!activePlan || !memoryDir || !Array.isArray(ps.states) || !ps.states.length) return null;
|
|
13609
|
+
let ctx;
|
|
13610
|
+
try { ctx = await loadPlanContext(memoryDir); } catch { return null; }
|
|
13611
|
+
const { domain } = ctx;
|
|
13612
|
+
const { normFactTerm } = await import("../adapters/memory/core.mjs");
|
|
13613
|
+
const individuals = new Set(Object.values(domain.classMembers || {}).flat());
|
|
13614
|
+
const piece = normFactTerm(whatIf[1]);
|
|
13615
|
+
const place = normFactTerm(whatIf[2]);
|
|
13616
|
+
if (!individuals.has(piece) || !individuals.has(place)) return null;
|
|
13617
|
+
const startRows = boardWithPieceMoved(ps.states[0], piece, place);
|
|
13618
|
+
if (!startRows) return null;
|
|
13619
|
+
const { movesFromRules, stateKeyFor, compileGoal, PlanBudgetError } = await import("../domain/domain.mjs");
|
|
13620
|
+
const { findActionPath } = await import("../domain/planning.mjs");
|
|
13621
|
+
const maxDepth = gameConfig?.planning?.maxDepth ?? DEFAULT_GAME_CONFIG.planning.maxDepth;
|
|
13622
|
+
let isGoal;
|
|
13623
|
+
try { isGoal = compileGoal(ps.goals, domain, { scope: "taught" }); } catch { return null; }
|
|
13624
|
+
let found = null;
|
|
13625
|
+
let budgetHit = null;
|
|
13626
|
+
try {
|
|
13627
|
+
found = findActionPath(startRows, isGoal, (s) => movesFromRules(s, domain, { scope: "taught" }), { maxDepth, stateKey: stateKeyFor });
|
|
13628
|
+
} catch (err) {
|
|
13629
|
+
if (!(err instanceof PlanBudgetError)) throw err;
|
|
13630
|
+
budgetHit = err.message;
|
|
13631
|
+
}
|
|
13632
|
+
const changedRow = startRows.find((r) => r.subject === piece && r.object === place);
|
|
13633
|
+
let text;
|
|
13634
|
+
if (budgetHit) {
|
|
13635
|
+
text = `I can't answer that from here — the search space from that start is too large (${budgetHit}). The real board still stands as taught.`;
|
|
13636
|
+
} else if (!found) {
|
|
13637
|
+
const legalFromHere = movesFromRules(startRows, domain, { scope: "taught" });
|
|
13638
|
+
if (!legalFromHere.length) {
|
|
13639
|
+
const blocked = await firstBlockingPrecond(piece, "subject", startRows, domain);
|
|
13640
|
+
const clause = blocked
|
|
13641
|
+
? ` ${blocked.clause.charAt(0).toUpperCase()}${blocked.clause.slice(1)}${blocked.witness ? `, and ${blocked.witness}` : ""}.`
|
|
13642
|
+
: "";
|
|
13643
|
+
text = `no plan from that start — nothing can move at all.${clause} The real board still stands as taught.`;
|
|
13644
|
+
} else {
|
|
13645
|
+
text = `no plan from that start within ${maxDepth} moves to: ${ps.goalText}. The real board still stands as taught.`;
|
|
13646
|
+
}
|
|
13647
|
+
} else if (found.actions.length === 0) {
|
|
13648
|
+
text = "from that start the goal already holds, so there is nothing to do. The real board still stands as taught.";
|
|
13649
|
+
} else {
|
|
13650
|
+
const m = found.actions.length;
|
|
13651
|
+
const moveLines = found.actions.map((a, i) => ` ${i + 1}. ${actionLabel(a.name, a.subject, a.target)}`).join("\n");
|
|
13652
|
+
text = `from that start it takes ${m} move${m === 1 ? "" : "s"} (shortest):\n${moveLines}\n\n`
|
|
13653
|
+
+ `hypothetical only — the real board still stands as taught, and the plan I found is unchanged.`;
|
|
13654
|
+
}
|
|
13655
|
+
return {
|
|
13656
|
+
text,
|
|
13657
|
+
deduced: `re-solve the plan from a hypothetical start (${piece} ${changedRow ? predicatePhrase(changedRow.predicate) : "at"} ${place})`,
|
|
13658
|
+
note: "PLAN FOLLOW-UP — counterfactual start re-solved through the same BFS over the taught rules; the plan slot is untouched",
|
|
13659
|
+
};
|
|
13660
|
+
}
|
|
13661
|
+
|
|
13662
|
+
// FORCED-ALTERNATIVE COMPARE — "why did you <act> A instead of B?" / "why not
|
|
13663
|
+
// <act> B first?" forces B into the same slot A held on the plan's own first
|
|
13664
|
+
// move, re-searches from B's successor, and compares the total cost against
|
|
13665
|
+
// the plan that was found. Also read-only: the held plan is never touched.
|
|
13666
|
+
const altPos = q.match(PLAN_WHY_ALTERNATIVE_RE);
|
|
13667
|
+
const altNeg = altPos ? null : q.match(PLAN_WHY_NOT_ALTERNATIVE_RE);
|
|
13668
|
+
if (altPos || altNeg) {
|
|
13669
|
+
if (!activePlan || !memoryDir || !Array.isArray(ps.states) || !ps.states.length) return null;
|
|
13670
|
+
let ctx;
|
|
13671
|
+
try { ctx = await loadPlanContext(memoryDir); } catch { return null; }
|
|
13672
|
+
const { domain } = ctx;
|
|
13673
|
+
const { normFactTerm } = await import("../adapters/memory/core.mjs");
|
|
13674
|
+
const chosen = ps.actions[0];
|
|
13675
|
+
const alternativeRaw = altPos ? altPos[4] : altNeg[2];
|
|
13676
|
+
const { slot, forced } = resolveForcedAlternative(alternativeRaw, chosen, domain, normFactTerm);
|
|
13677
|
+
if (!slot) return null;
|
|
13678
|
+
|
|
13679
|
+
const { movesFromRules, stateKeyFor, compileGoal, PlanBudgetError } = await import("../domain/domain.mjs");
|
|
13680
|
+
const { findActionPath } = await import("../domain/planning.mjs");
|
|
13681
|
+
const maxDepth = gameConfig?.planning?.maxDepth ?? DEFAULT_GAME_CONFIG.planning.maxDepth;
|
|
13682
|
+
let isGoal;
|
|
13683
|
+
try { isGoal = compileGoal(ps.goals, domain, { scope: "taught" }); } catch { return null; }
|
|
13684
|
+
|
|
13685
|
+
const start = ps.states[0];
|
|
13686
|
+
const n = ps.actions.length;
|
|
13687
|
+
const chosenLabel = chosen.label;
|
|
13688
|
+
const forcedLabel = actionLabel(chosen.name,
|
|
13689
|
+
slot === "subject" ? forced : chosen.subject,
|
|
13690
|
+
slot === "target" ? forced : chosen.target);
|
|
13691
|
+
const legal = movesFromRules(start, domain, { scope: "taught" });
|
|
13692
|
+
const forcedMoves = legal.filter((mv) => (slot === "subject"
|
|
13693
|
+
? mv.action.subject === forced
|
|
13694
|
+
: mv.action.target === forced && mv.action.subject === chosen.subject));
|
|
13695
|
+
|
|
13696
|
+
let text;
|
|
13697
|
+
if (!forcedMoves.length) {
|
|
13698
|
+
const blocked = await firstBlockingPrecond(forced, slot, start, domain);
|
|
13699
|
+
text = blocked
|
|
13700
|
+
? `${forced} can't go first — ${blocked.witness ? `${blocked.witness}, and ` : ""}${blocked.clause}.`
|
|
13701
|
+
: `${forced} has no legal first move from the board this plan started on. ${chosenLabel} is the move I found.`;
|
|
13702
|
+
} else {
|
|
13703
|
+
let best = null;
|
|
13704
|
+
for (const move of forcedMoves) {
|
|
13705
|
+
let rest;
|
|
13706
|
+
try {
|
|
13707
|
+
rest = findActionPath(move.nextState, isGoal, (s) => movesFromRules(s, domain, { scope: "taught" }), { maxDepth, stateKey: stateKeyFor });
|
|
13708
|
+
} catch (err) {
|
|
13709
|
+
if (!(err instanceof PlanBudgetError)) throw err;
|
|
13710
|
+
continue;
|
|
13711
|
+
}
|
|
13712
|
+
if (!rest) continue;
|
|
13713
|
+
const cost = 1 + rest.actions.length;
|
|
13714
|
+
if (best === null || cost < best) best = cost;
|
|
13715
|
+
}
|
|
13716
|
+
if (best === null) {
|
|
13717
|
+
text = `forcing ${forcedLabel} first has no legal continuation within ${maxDepth} moves. ${chosenLabel} is the move on the plan I found.`;
|
|
13718
|
+
} else if (best > n) {
|
|
13719
|
+
text = `forcing ${forcedLabel} first costs ${best} moves against ${n}. The plan I found is ${best - n} move${best - n === 1 ? "" : "s"} shorter.`;
|
|
13720
|
+
} else if (best === n) {
|
|
13721
|
+
text = `forcing ${forcedLabel} first also takes ${n} moves. Both are shortest. `
|
|
13722
|
+
+ `The search walks every legal move breadth-first and returns the first shortest path it reaches, `
|
|
13723
|
+
+ `which is ${chosenLabel}.`;
|
|
13724
|
+
} else {
|
|
13725
|
+
text = `forcing ${forcedLabel} first costs ${best} moves — no more than the plan I found (${n}).`;
|
|
13726
|
+
}
|
|
13727
|
+
}
|
|
13728
|
+
return {
|
|
13729
|
+
text,
|
|
13730
|
+
deduced: `compare the planned first move against a forced alternative (${forcedLabel})`,
|
|
13731
|
+
note: "PLAN FOLLOW-UP — contrastive compare: the alternative was forced as the first move and re-searched through the same BFS; the plan slot is untouched",
|
|
13732
|
+
};
|
|
13733
|
+
}
|
|
13734
|
+
|
|
13446
13735
|
const clear = q.match(IS_CLEAR_RE);
|
|
13447
13736
|
const rev = clear ? null : q.match(BOARD_REVERSE_LOC_RE);
|
|
13448
13737
|
const fwd = clear || rev ? null : q.match(BOARD_FORWARD_LOC_RE);
|
|
@@ -13586,11 +13875,11 @@ async function runAsk(query, { config, source, graph, focus, last, templates, me
|
|
|
13586
13875
|
// A count erases its own matches to [], so the previous turn carries no id
|
|
13587
13876
|
// set for the next "which of those" to narrow. When the carry is empty, fall
|
|
13588
13877
|
// back to the session record: a standing `set` referent that "those" binds
|
|
13589
|
-
// keeps a narrowed set alive across a counting hop.
|
|
13590
|
-
//
|
|
13591
|
-
// probe
|
|
13878
|
+
// keeps a narrowed set alive across a counting hop. A tie leaves `prev` empty
|
|
13879
|
+
// and the anaphora node makes its own "needs a previous answer" decline —
|
|
13880
|
+
// this probe never picks one of two sets registered in the same turn.
|
|
13592
13881
|
if (!prev.length && discourseHolder) {
|
|
13593
|
-
const boundSet = bindDiscourseForm(discourseHolder.record, "those");
|
|
13882
|
+
const boundSet = bindDiscourseForm(discourseHolder.record, "those", { tieRefuses: true });
|
|
13594
13883
|
if (boundSet?.referent?.ids?.length) prev = boundSet.referent.ids.filter(Boolean);
|
|
13595
13884
|
}
|
|
13596
13885
|
// The query the ENGINE parses: a "what about X" continuation is rewritten to the
|
|
@@ -14067,7 +14356,7 @@ async function runAsk(query, { config, source, graph, focus, last, templates, me
|
|
|
14067
14356
|
// short-circuit to null, and `miss` below (askMiss || THIS) would record a
|
|
14068
14357
|
// null miss flag on every relaxation-rescued turn of a memory-less session.
|
|
14069
14358
|
const relaxedTeachCollision = Boolean(!!(envelope?.relaxed?.dropped?.length) && !askMiss && memoryDir
|
|
14070
|
-
&& !
|
|
14359
|
+
&& !leadsInterrogative(trimmedQuery) && !/\?\s*$/.test(trimmedQuery)
|
|
14071
14360
|
&& DECLARATIVE_KIND_OF_RE.test(trimmedQuery));
|
|
14072
14361
|
const preCollisionAnswer = relaxedTeachCollision ? answer : null;
|
|
14073
14362
|
const miss = askMiss || relaxedTeachCollision;
|
|
@@ -15294,6 +15583,7 @@ const GOAL_BY_COMMAND = {
|
|
|
15294
15583
|
exports: GOAL_BY_KIND.reexports,
|
|
15295
15584
|
arch: "understand the overall architecture (package/module boundaries)",
|
|
15296
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",
|
|
15297
15587
|
syllogise: "materialize the entailed facts that follow from what's remembered about one term",
|
|
15298
15588
|
wiki: "toggle the live Wikipedia supplement for questions nothing local can answer",
|
|
15299
15589
|
wikipedia: "choose which source the research lane fetches from",
|
|
@@ -15322,6 +15612,58 @@ function domainPackLine({ name, groundingKind, groundingAdapter, commandCount, c
|
|
|
15322
15612
|
return parts.length ? `${name} — ${parts.join("; ")}` : String(name);
|
|
15323
15613
|
}
|
|
15324
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
|
+
|
|
15325
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 }) {
|
|
15326
15668
|
const ts = new Date().toISOString();
|
|
15327
15669
|
const sp = line.indexOf(" ");
|
|
@@ -15465,6 +15807,28 @@ async function runCommand(line, { config, source, graph, focus, memoryDir, trace
|
|
|
15465
15807
|
return mk(lines.join("\n"));
|
|
15466
15808
|
}
|
|
15467
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
|
+
|
|
15468
15832
|
// /syllogise <term> — forward-chain what's remembered about <term> into
|
|
15469
15833
|
// entailed facts and WRITE them to the store, so a chain too long for the
|
|
15470
15834
|
// live isa ladder to walk becomes a single stored step it can read.
|
|
@@ -16594,6 +16958,27 @@ async function factsTouchedSince(memoryDir, before) {
|
|
|
16594
16958
|
return touchedFactRows(before, after);
|
|
16595
16959
|
}
|
|
16596
16960
|
|
|
16961
|
+
/** A whole-line miss whose only problem is a closed filler clause in front of a
|
|
16962
|
+
* real question. Peels the clause and re-runs the ORDINARY dispatcher once on
|
|
16963
|
+
* the remainder; accepted only on a double match — the peeled prefix comes from
|
|
16964
|
+
* the closed inventory AND the remainder grounds. A failed retry returns null
|
|
16965
|
+
* and the original miss stands untouched. Interrogative remainders only: a
|
|
16966
|
+
* stripped remainder must never reach the write boundary. */
|
|
16967
|
+
async function answerWithoutFillerPrefix(input, options, missed) {
|
|
16968
|
+
if (!missed || typeof missed !== "object" || !missed.record?.miss) return null;
|
|
16969
|
+
const peel = fillerClausePrefix(input);
|
|
16970
|
+
if (!peel) return null;
|
|
16971
|
+
const rest = peel.remainder;
|
|
16972
|
+
if (!QUESTION_LEAD_RE.test(rest) && !/\?\s*$/.test(rest)) return null;
|
|
16973
|
+
const retry = await dispatchTurn(rest, options);
|
|
16974
|
+
if (!retry || typeof retry !== "object" || retry.record?.miss) return null;
|
|
16975
|
+
if (retry.record?.type === "turn") retry.record.input = String(input ?? "").trim();
|
|
16976
|
+
if (Array.isArray(retry.logLines) && retry.logLines.length > 1) {
|
|
16977
|
+
retry.logLines[1] = `> ${String(input ?? "").trim()}`;
|
|
16978
|
+
}
|
|
16979
|
+
return retry;
|
|
16980
|
+
}
|
|
16981
|
+
|
|
16597
16982
|
/** Run one turn and report which Fact rows it wrote, as `factsTouched` beside
|
|
16598
16983
|
* the answer/record/logLines every caller already reads. The dispatch itself
|
|
16599
16984
|
* is dispatchTurn, below; this wrapper exists so the field lands on EVERY
|
|
@@ -16601,7 +16986,9 @@ async function factsTouchedSince(memoryDir, before) {
|
|
|
16601
16986
|
export async function runTurn(input, options = {}) {
|
|
16602
16987
|
const memoryDir = options?.memoryDir ?? null;
|
|
16603
16988
|
const before = await factRowSnapshot(memoryDir);
|
|
16604
|
-
|
|
16989
|
+
let result = await dispatchTurn(input, options);
|
|
16990
|
+
const rescued = await answerWithoutFillerPrefix(input, options, result);
|
|
16991
|
+
if (rescued) result = rescued;
|
|
16605
16992
|
if (!result || typeof result !== "object") return result;
|
|
16606
16993
|
return { ...result, factsTouched: await factsTouchedSince(memoryDir, before) };
|
|
16607
16994
|
}
|
|
@@ -16968,6 +17355,7 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
|
|
|
16968
17355
|
const follow = await planFollowUpAnswer(workingLine, {
|
|
16969
17356
|
memoryDir, planHolder,
|
|
16970
17357
|
pendingPager: !!(Array.isArray(last?.detail?.pending?.items) && last.detail.pending.items.length),
|
|
17358
|
+
gameConfig: resolvedGameConfig,
|
|
16971
17359
|
});
|
|
16972
17360
|
if (follow) {
|
|
16973
17361
|
note(trace, `goal: ${follow.deduced}`);
|