@polycode-projects/the-mechanical-code-talker 5.0.20 → 5.0.22
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 -27
- package/package.json +1 -6
- package/src/adapters/toml-config.mjs +5 -0
- package/src/domain/domain.mjs +8 -0
- package/src/domain/interpret/normalize.mjs +86 -1
- package/src/domain/router/recognize.mjs +0 -0
- package/src/domain/world-snapshot.mjs +25 -0
- package/src/services/adventure-autoplay.mjs +1 -3
- package/src/services/adventure.mjs +17 -29
- package/src/services/chat.mjs +325 -13
- package/src/services/viz-boot.mjs +8 -8
- package/src/surfaces/web/memory-ask-browser.bundle.js +91 -91
- package/src/domain/code-explorer-hints.mjs +0 -180
- package/src/services/code-explorer-viz.mjs +0 -596
- package/src/surfaces/web/code-explorer-browser-entry.mjs +0 -253
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
|
|
@@ -13347,6 +13380,128 @@ async function executePlanStep(planHolder, { memoryDir, sessionId = "", gameConf
|
|
|
13347
13380
|
};
|
|
13348
13381
|
}
|
|
13349
13382
|
|
|
13383
|
+
/** Rebuild the plan's start board with one piece moved. Replaces every row
|
|
13384
|
+
* whose SUBJECT is the piece and whose predicate is a locative (the piece
|
|
13385
|
+
* can only be in one place), keeps every other row byte-identical, and
|
|
13386
|
+
* returns the rows in their original order with the replacement in the
|
|
13387
|
+
* original row's slot — the state key is order-sensitive, so a rebuild
|
|
13388
|
+
* that reorders rows would read as a different state to the search.
|
|
13389
|
+
* Returns null when the piece has no locative row on the taught board
|
|
13390
|
+
* (nothing to counterfactualize). */
|
|
13391
|
+
function boardWithPieceMoved(startRows, piece, place) {
|
|
13392
|
+
const idx = startRows.findIndex((r) => r.subject === piece && locativePreposition(r.predicate) !== null);
|
|
13393
|
+
if (idx < 0) return null;
|
|
13394
|
+
const rows = startRows.slice();
|
|
13395
|
+
rows[idx] = { ...rows[idx], object: place };
|
|
13396
|
+
return rows;
|
|
13397
|
+
}
|
|
13398
|
+
|
|
13399
|
+
/** Which slot does the named alternative belong in? Answered from the
|
|
13400
|
+
* taught class membership, so a target-class alternative forces the
|
|
13401
|
+
* target and a subject-class alternative forces the subject. Returns
|
|
13402
|
+
* "subject", "target", or null when the alternative shares no taught
|
|
13403
|
+
* class with either side of the chosen move — the branch declines and
|
|
13404
|
+
* the honest miss stands. */
|
|
13405
|
+
function forcedSlotFor(alternative, chosenSubject, chosenTarget, domain) {
|
|
13406
|
+
const classesOf = (t) => Object.keys(domain.classMembers || {})
|
|
13407
|
+
.filter((cls) => (domain.classMembers[cls] || []).includes(t));
|
|
13408
|
+
const alt = new Set(classesOf(alternative));
|
|
13409
|
+
if (!alt.size) return null;
|
|
13410
|
+
if (chosenTarget && classesOf(chosenTarget).some((c) => alt.has(c))) return "target";
|
|
13411
|
+
if (classesOf(chosenSubject).some((c) => alt.has(c))) return "subject";
|
|
13412
|
+
return null;
|
|
13413
|
+
}
|
|
13414
|
+
|
|
13415
|
+
/** Normalize a forced-alternative match (the "instead of B" voicing or the
|
|
13416
|
+
* "why not B" voicing) into which slot B replaces. The chosen A side
|
|
13417
|
+
* always comes from the plan's own first move, never from the sentence,
|
|
13418
|
+
* so the comparison is against the SAME move a cold "what is the next
|
|
13419
|
+
* move" would report. */
|
|
13420
|
+
function resolveForcedAlternative(alternativeRaw, chosen, domain, normFactTerm) {
|
|
13421
|
+
const forced = normFactTerm(alternativeRaw);
|
|
13422
|
+
const slot = forcedSlotFor(forced, chosen.subject, chosen.target, domain);
|
|
13423
|
+
return { slot, forced };
|
|
13424
|
+
}
|
|
13425
|
+
|
|
13426
|
+
/** predicatePhrase's head verb, based rather than third-person: "rests on"
|
|
13427
|
+
* -> "rest on". The precondition clauses below read as the taught rule's
|
|
13428
|
+
* own wording ("nothing may rest on…"), never a report ("rests on…"). */
|
|
13429
|
+
function basePhraseOf(predicate) {
|
|
13430
|
+
const phrase = predicatePhrase(predicate);
|
|
13431
|
+
const [head, ...tail] = phrase.split(" ");
|
|
13432
|
+
return [baseVerbSurface(head), ...tail].join(" ");
|
|
13433
|
+
}
|
|
13434
|
+
|
|
13435
|
+
/** The bare comparative words a "-than" predicate folds ("mgx:smaller-than"
|
|
13436
|
+
* -> "smaller than"), without predicatePhrase's own leading "is". */
|
|
13437
|
+
function comparativeWords(predicate) {
|
|
13438
|
+
const m = /^mgx:([a-z]+(?:-[a-z]+)*)-than$/i.exec(String(predicate || ""));
|
|
13439
|
+
return m ? m[1].replace(/-/g, " ") : predicatePhrase(predicate);
|
|
13440
|
+
}
|
|
13441
|
+
|
|
13442
|
+
/** Why can the forced piece not take the given slot in a first move? Walks
|
|
13443
|
+
* every candidate grounding of every taught action with the forced piece
|
|
13444
|
+
* in that slot, records the first precondition each grounding fails, and
|
|
13445
|
+
* names the one that blocked the most of them. Deterministic: actions,
|
|
13446
|
+
* signatures and members are walked in compileDomain's own fixed sort
|
|
13447
|
+
* order, so a tie always breaks the same way. Returns { clause, witness }
|
|
13448
|
+
* or null when the forced piece has no candidate grounding at all to
|
|
13449
|
+
* explain (nothing identifiable blocked it). */
|
|
13450
|
+
async function firstBlockingPrecond(forced, slot, state, domain) {
|
|
13451
|
+
const { precondHolds } = await import("../domain/domain.mjs");
|
|
13452
|
+
const scopeMembers = (cls) => domain.taughtClassMembers?.[cls] || [];
|
|
13453
|
+
const precondAppliesLocal = (precond, target) =>
|
|
13454
|
+
precond.scope === "any" || (domain.classMembers[precond.scope] || []).includes(target);
|
|
13455
|
+
const tally = new Map();
|
|
13456
|
+
const order = [];
|
|
13457
|
+
for (const action of domain.actions) {
|
|
13458
|
+
for (const sig of action.signatures) {
|
|
13459
|
+
if (slot === "subject" && !scopeMembers(sig.subjectClass).includes(forced)) continue;
|
|
13460
|
+
if (slot === "target" && !scopeMembers(sig.targetClass).includes(forced)) continue;
|
|
13461
|
+
const subjects = slot === "subject" ? [forced] : scopeMembers(sig.subjectClass);
|
|
13462
|
+
const targets = slot === "target" ? [forced] : scopeMembers(sig.targetClass);
|
|
13463
|
+
for (const subject of subjects) {
|
|
13464
|
+
for (const target of targets) {
|
|
13465
|
+
if (subject === target) continue;
|
|
13466
|
+
for (const precond of action.preconds) {
|
|
13467
|
+
if (!precondAppliesLocal(precond, target)) continue;
|
|
13468
|
+
if (precondHolds(precond, subject, target, state, domain)) continue;
|
|
13469
|
+
const key = JSON.stringify(precond);
|
|
13470
|
+
if (!tally.has(key)) { tally.set(key, { count: 0, precond, action }); order.push(key); }
|
|
13471
|
+
tally.get(key).count += 1;
|
|
13472
|
+
break;
|
|
13473
|
+
}
|
|
13474
|
+
}
|
|
13475
|
+
}
|
|
13476
|
+
}
|
|
13477
|
+
}
|
|
13478
|
+
if (!tally.size) return null;
|
|
13479
|
+
let best = null;
|
|
13480
|
+
for (const key of order) {
|
|
13481
|
+
const entry = tally.get(key);
|
|
13482
|
+
if (!best || entry.count > best.count) best = entry;
|
|
13483
|
+
}
|
|
13484
|
+
const { precond: p, action } = best;
|
|
13485
|
+
const role = p.role === "target" ? "the target" : "the piece you move";
|
|
13486
|
+
if (p.shape === "no-incoming") {
|
|
13487
|
+
// The winning precond's own role almost always matches the forced
|
|
13488
|
+
// slot: it is the one that can fail for every candidate grounding
|
|
13489
|
+
// regardless of the OTHER slot's value, which is exactly what makes it
|
|
13490
|
+
// the highest tally. So the state row that names the forced piece as
|
|
13491
|
+
// the blocked object is the row worth citing.
|
|
13492
|
+
const witnessRow = state.find((r) => r.predicate === p.predicate && r.object === forced);
|
|
13493
|
+
return { clause: `your "${action.name}" rule says nothing may ${basePhraseOf(p.predicate)} ${role}`, witness: witnessRow ? factPhrase(witnessRow) : null };
|
|
13494
|
+
}
|
|
13495
|
+
if (p.shape === "comparator") {
|
|
13496
|
+
return { clause: `your "${action.name}" rule says the piece you move must be ${comparativeWords(p.predicate)} the target`, witness: null };
|
|
13497
|
+
}
|
|
13498
|
+
if (p.shape === "fact-value") {
|
|
13499
|
+
const witnessRow = state.find((r) => r.subject === forced && r.predicate === p.predicate);
|
|
13500
|
+
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 };
|
|
13501
|
+
}
|
|
13502
|
+
return null;
|
|
13503
|
+
}
|
|
13504
|
+
|
|
13350
13505
|
/** Plan follow-up questions ("what is the next move", "how many moves", "why
|
|
13351
13506
|
* that move") answered off the ACTIVE plan, and board-state questions ("is X
|
|
13352
13507
|
* clear", "what rests on X", "where is X") answered off the CURRENT board (the
|
|
@@ -13357,7 +13512,7 @@ async function executePlanStep(planHolder, { memoryDir, sessionId = "", gameConf
|
|
|
13357
13512
|
* "next" moves a piece, "what rests on X" reflects the snapshot, not the stale
|
|
13358
13513
|
* pre-plan facts. Clearness is derived, never stored — a piece is clear iff
|
|
13359
13514
|
* nothing rests on it on the current board. */
|
|
13360
|
-
async function planFollowUpAnswer(query, { memoryDir, planHolder, pendingPager = false }) {
|
|
13515
|
+
async function planFollowUpAnswer(query, { memoryDir, planHolder, pendingPager = false, gameConfig = DEFAULT_GAME_CONFIG }) {
|
|
13361
13516
|
const q = String(query).trim();
|
|
13362
13517
|
const ps = planHolder?.state;
|
|
13363
13518
|
const activePlan = ps && Array.isArray(ps.actions) && ps.actions.length;
|
|
@@ -13443,6 +13598,139 @@ async function planFollowUpAnswer(query, { memoryDir, planHolder, pendingPager =
|
|
|
13443
13598
|
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
13599
|
}
|
|
13445
13600
|
|
|
13601
|
+
// COUNTERFACTUAL PREMISE — "what if <piece> started <place> instead?" rebuilds
|
|
13602
|
+
// the plan's own start board with one piece moved, then re-runs the same BFS
|
|
13603
|
+
// from it. Read-only: planHolder.state is never written here, so the held
|
|
13604
|
+
// plan and its cursor survive the question unchanged.
|
|
13605
|
+
const whatIf = q.match(PLAN_WHAT_IF_START_RE);
|
|
13606
|
+
if (whatIf) {
|
|
13607
|
+
if (!activePlan || !memoryDir || !Array.isArray(ps.states) || !ps.states.length) return null;
|
|
13608
|
+
let ctx;
|
|
13609
|
+
try { ctx = await loadPlanContext(memoryDir); } catch { return null; }
|
|
13610
|
+
const { domain } = ctx;
|
|
13611
|
+
const { normFactTerm } = await import("../adapters/memory/core.mjs");
|
|
13612
|
+
const individuals = new Set(Object.values(domain.classMembers || {}).flat());
|
|
13613
|
+
const piece = normFactTerm(whatIf[1]);
|
|
13614
|
+
const place = normFactTerm(whatIf[2]);
|
|
13615
|
+
if (!individuals.has(piece) || !individuals.has(place)) return null;
|
|
13616
|
+
const startRows = boardWithPieceMoved(ps.states[0], piece, place);
|
|
13617
|
+
if (!startRows) return null;
|
|
13618
|
+
const { movesFromRules, stateKeyFor, compileGoal, PlanBudgetError } = await import("../domain/domain.mjs");
|
|
13619
|
+
const { findActionPath } = await import("../domain/planning.mjs");
|
|
13620
|
+
const maxDepth = gameConfig?.planning?.maxDepth ?? DEFAULT_GAME_CONFIG.planning.maxDepth;
|
|
13621
|
+
let isGoal;
|
|
13622
|
+
try { isGoal = compileGoal(ps.goals, domain, { scope: "taught" }); } catch { return null; }
|
|
13623
|
+
let found = null;
|
|
13624
|
+
let budgetHit = null;
|
|
13625
|
+
try {
|
|
13626
|
+
found = findActionPath(startRows, isGoal, (s) => movesFromRules(s, domain, { scope: "taught" }), { maxDepth, stateKey: stateKeyFor });
|
|
13627
|
+
} catch (err) {
|
|
13628
|
+
if (!(err instanceof PlanBudgetError)) throw err;
|
|
13629
|
+
budgetHit = err.message;
|
|
13630
|
+
}
|
|
13631
|
+
const changedRow = startRows.find((r) => r.subject === piece && r.object === place);
|
|
13632
|
+
let text;
|
|
13633
|
+
if (budgetHit) {
|
|
13634
|
+
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.`;
|
|
13635
|
+
} else if (!found) {
|
|
13636
|
+
const legalFromHere = movesFromRules(startRows, domain, { scope: "taught" });
|
|
13637
|
+
if (!legalFromHere.length) {
|
|
13638
|
+
const blocked = await firstBlockingPrecond(piece, "subject", startRows, domain);
|
|
13639
|
+
const clause = blocked
|
|
13640
|
+
? ` ${blocked.clause.charAt(0).toUpperCase()}${blocked.clause.slice(1)}${blocked.witness ? `, and ${blocked.witness}` : ""}.`
|
|
13641
|
+
: "";
|
|
13642
|
+
text = `no plan from that start — nothing can move at all.${clause} The real board still stands as taught.`;
|
|
13643
|
+
} else {
|
|
13644
|
+
text = `no plan from that start within ${maxDepth} moves to: ${ps.goalText}. The real board still stands as taught.`;
|
|
13645
|
+
}
|
|
13646
|
+
} else if (found.actions.length === 0) {
|
|
13647
|
+
text = "from that start the goal already holds, so there is nothing to do. The real board still stands as taught.";
|
|
13648
|
+
} else {
|
|
13649
|
+
const m = found.actions.length;
|
|
13650
|
+
const moveLines = found.actions.map((a, i) => ` ${i + 1}. ${actionLabel(a.name, a.subject, a.target)}`).join("\n");
|
|
13651
|
+
text = `from that start it takes ${m} move${m === 1 ? "" : "s"} (shortest):\n${moveLines}\n\n`
|
|
13652
|
+
+ `hypothetical only — the real board still stands as taught, and the plan I found is unchanged.`;
|
|
13653
|
+
}
|
|
13654
|
+
return {
|
|
13655
|
+
text,
|
|
13656
|
+
deduced: `re-solve the plan from a hypothetical start (${piece} ${changedRow ? predicatePhrase(changedRow.predicate) : "at"} ${place})`,
|
|
13657
|
+
note: "PLAN FOLLOW-UP — counterfactual start re-solved through the same BFS over the taught rules; the plan slot is untouched",
|
|
13658
|
+
};
|
|
13659
|
+
}
|
|
13660
|
+
|
|
13661
|
+
// FORCED-ALTERNATIVE COMPARE — "why did you <act> A instead of B?" / "why not
|
|
13662
|
+
// <act> B first?" forces B into the same slot A held on the plan's own first
|
|
13663
|
+
// move, re-searches from B's successor, and compares the total cost against
|
|
13664
|
+
// the plan that was found. Also read-only: the held plan is never touched.
|
|
13665
|
+
const altPos = q.match(PLAN_WHY_ALTERNATIVE_RE);
|
|
13666
|
+
const altNeg = altPos ? null : q.match(PLAN_WHY_NOT_ALTERNATIVE_RE);
|
|
13667
|
+
if (altPos || altNeg) {
|
|
13668
|
+
if (!activePlan || !memoryDir || !Array.isArray(ps.states) || !ps.states.length) return null;
|
|
13669
|
+
let ctx;
|
|
13670
|
+
try { ctx = await loadPlanContext(memoryDir); } catch { return null; }
|
|
13671
|
+
const { domain } = ctx;
|
|
13672
|
+
const { normFactTerm } = await import("../adapters/memory/core.mjs");
|
|
13673
|
+
const chosen = ps.actions[0];
|
|
13674
|
+
const alternativeRaw = altPos ? altPos[4] : altNeg[2];
|
|
13675
|
+
const { slot, forced } = resolveForcedAlternative(alternativeRaw, chosen, domain, normFactTerm);
|
|
13676
|
+
if (!slot) return null;
|
|
13677
|
+
|
|
13678
|
+
const { movesFromRules, stateKeyFor, compileGoal, PlanBudgetError } = await import("../domain/domain.mjs");
|
|
13679
|
+
const { findActionPath } = await import("../domain/planning.mjs");
|
|
13680
|
+
const maxDepth = gameConfig?.planning?.maxDepth ?? DEFAULT_GAME_CONFIG.planning.maxDepth;
|
|
13681
|
+
let isGoal;
|
|
13682
|
+
try { isGoal = compileGoal(ps.goals, domain, { scope: "taught" }); } catch { return null; }
|
|
13683
|
+
|
|
13684
|
+
const start = ps.states[0];
|
|
13685
|
+
const n = ps.actions.length;
|
|
13686
|
+
const chosenLabel = chosen.label;
|
|
13687
|
+
const forcedLabel = actionLabel(chosen.name,
|
|
13688
|
+
slot === "subject" ? forced : chosen.subject,
|
|
13689
|
+
slot === "target" ? forced : chosen.target);
|
|
13690
|
+
const legal = movesFromRules(start, domain, { scope: "taught" });
|
|
13691
|
+
const forcedMoves = legal.filter((mv) => (slot === "subject"
|
|
13692
|
+
? mv.action.subject === forced
|
|
13693
|
+
: mv.action.target === forced && mv.action.subject === chosen.subject));
|
|
13694
|
+
|
|
13695
|
+
let text;
|
|
13696
|
+
if (!forcedMoves.length) {
|
|
13697
|
+
const blocked = await firstBlockingPrecond(forced, slot, start, domain);
|
|
13698
|
+
text = blocked
|
|
13699
|
+
? `${forced} can't go first — ${blocked.witness ? `${blocked.witness}, and ` : ""}${blocked.clause}.`
|
|
13700
|
+
: `${forced} has no legal first move from the board this plan started on. ${chosenLabel} is the move I found.`;
|
|
13701
|
+
} else {
|
|
13702
|
+
let best = null;
|
|
13703
|
+
for (const move of forcedMoves) {
|
|
13704
|
+
let rest;
|
|
13705
|
+
try {
|
|
13706
|
+
rest = findActionPath(move.nextState, isGoal, (s) => movesFromRules(s, domain, { scope: "taught" }), { maxDepth, stateKey: stateKeyFor });
|
|
13707
|
+
} catch (err) {
|
|
13708
|
+
if (!(err instanceof PlanBudgetError)) throw err;
|
|
13709
|
+
continue;
|
|
13710
|
+
}
|
|
13711
|
+
if (!rest) continue;
|
|
13712
|
+
const cost = 1 + rest.actions.length;
|
|
13713
|
+
if (best === null || cost < best) best = cost;
|
|
13714
|
+
}
|
|
13715
|
+
if (best === null) {
|
|
13716
|
+
text = `forcing ${forcedLabel} first has no legal continuation within ${maxDepth} moves. ${chosenLabel} is the move on the plan I found.`;
|
|
13717
|
+
} else if (best > n) {
|
|
13718
|
+
text = `forcing ${forcedLabel} first costs ${best} moves against ${n}. The plan I found is ${best - n} move${best - n === 1 ? "" : "s"} shorter.`;
|
|
13719
|
+
} else if (best === n) {
|
|
13720
|
+
text = `forcing ${forcedLabel} first also takes ${n} moves. Both are shortest. `
|
|
13721
|
+
+ `The search walks every legal move breadth-first and returns the first shortest path it reaches, `
|
|
13722
|
+
+ `which is ${chosenLabel}.`;
|
|
13723
|
+
} else {
|
|
13724
|
+
text = `forcing ${forcedLabel} first costs ${best} moves — no more than the plan I found (${n}).`;
|
|
13725
|
+
}
|
|
13726
|
+
}
|
|
13727
|
+
return {
|
|
13728
|
+
text,
|
|
13729
|
+
deduced: `compare the planned first move against a forced alternative (${forcedLabel})`,
|
|
13730
|
+
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",
|
|
13731
|
+
};
|
|
13732
|
+
}
|
|
13733
|
+
|
|
13446
13734
|
const clear = q.match(IS_CLEAR_RE);
|
|
13447
13735
|
const rev = clear ? null : q.match(BOARD_REVERSE_LOC_RE);
|
|
13448
13736
|
const fwd = clear || rev ? null : q.match(BOARD_FORWARD_LOC_RE);
|
|
@@ -13586,11 +13874,11 @@ async function runAsk(query, { config, source, graph, focus, last, templates, me
|
|
|
13586
13874
|
// A count erases its own matches to [], so the previous turn carries no id
|
|
13587
13875
|
// set for the next "which of those" to narrow. When the carry is empty, fall
|
|
13588
13876
|
// 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
|
|
13877
|
+
// keeps a narrowed set alive across a counting hop. A tie leaves `prev` empty
|
|
13878
|
+
// and the anaphora node makes its own "needs a previous answer" decline —
|
|
13879
|
+
// this probe never picks one of two sets registered in the same turn.
|
|
13592
13880
|
if (!prev.length && discourseHolder) {
|
|
13593
|
-
const boundSet = bindDiscourseForm(discourseHolder.record, "those");
|
|
13881
|
+
const boundSet = bindDiscourseForm(discourseHolder.record, "those", { tieRefuses: true });
|
|
13594
13882
|
if (boundSet?.referent?.ids?.length) prev = boundSet.referent.ids.filter(Boolean);
|
|
13595
13883
|
}
|
|
13596
13884
|
// The query the ENGINE parses: a "what about X" continuation is rewritten to the
|
|
@@ -14067,7 +14355,7 @@ async function runAsk(query, { config, source, graph, focus, last, templates, me
|
|
|
14067
14355
|
// short-circuit to null, and `miss` below (askMiss || THIS) would record a
|
|
14068
14356
|
// null miss flag on every relaxation-rescued turn of a memory-less session.
|
|
14069
14357
|
const relaxedTeachCollision = Boolean(!!(envelope?.relaxed?.dropped?.length) && !askMiss && memoryDir
|
|
14070
|
-
&& !
|
|
14358
|
+
&& !leadsInterrogative(trimmedQuery) && !/\?\s*$/.test(trimmedQuery)
|
|
14071
14359
|
&& DECLARATIVE_KIND_OF_RE.test(trimmedQuery));
|
|
14072
14360
|
const preCollisionAnswer = relaxedTeachCollision ? answer : null;
|
|
14073
14361
|
const miss = askMiss || relaxedTeachCollision;
|
|
@@ -16594,6 +16882,27 @@ async function factsTouchedSince(memoryDir, before) {
|
|
|
16594
16882
|
return touchedFactRows(before, after);
|
|
16595
16883
|
}
|
|
16596
16884
|
|
|
16885
|
+
/** A whole-line miss whose only problem is a closed filler clause in front of a
|
|
16886
|
+
* real question. Peels the clause and re-runs the ORDINARY dispatcher once on
|
|
16887
|
+
* the remainder; accepted only on a double match — the peeled prefix comes from
|
|
16888
|
+
* the closed inventory AND the remainder grounds. A failed retry returns null
|
|
16889
|
+
* and the original miss stands untouched. Interrogative remainders only: a
|
|
16890
|
+
* stripped remainder must never reach the write boundary. */
|
|
16891
|
+
async function answerWithoutFillerPrefix(input, options, missed) {
|
|
16892
|
+
if (!missed || typeof missed !== "object" || !missed.record?.miss) return null;
|
|
16893
|
+
const peel = fillerClausePrefix(input);
|
|
16894
|
+
if (!peel) return null;
|
|
16895
|
+
const rest = peel.remainder;
|
|
16896
|
+
if (!QUESTION_LEAD_RE.test(rest) && !/\?\s*$/.test(rest)) return null;
|
|
16897
|
+
const retry = await dispatchTurn(rest, options);
|
|
16898
|
+
if (!retry || typeof retry !== "object" || retry.record?.miss) return null;
|
|
16899
|
+
if (retry.record?.type === "turn") retry.record.input = String(input ?? "").trim();
|
|
16900
|
+
if (Array.isArray(retry.logLines) && retry.logLines.length > 1) {
|
|
16901
|
+
retry.logLines[1] = `> ${String(input ?? "").trim()}`;
|
|
16902
|
+
}
|
|
16903
|
+
return retry;
|
|
16904
|
+
}
|
|
16905
|
+
|
|
16597
16906
|
/** Run one turn and report which Fact rows it wrote, as `factsTouched` beside
|
|
16598
16907
|
* the answer/record/logLines every caller already reads. The dispatch itself
|
|
16599
16908
|
* is dispatchTurn, below; this wrapper exists so the field lands on EVERY
|
|
@@ -16601,7 +16910,9 @@ async function factsTouchedSince(memoryDir, before) {
|
|
|
16601
16910
|
export async function runTurn(input, options = {}) {
|
|
16602
16911
|
const memoryDir = options?.memoryDir ?? null;
|
|
16603
16912
|
const before = await factRowSnapshot(memoryDir);
|
|
16604
|
-
|
|
16913
|
+
let result = await dispatchTurn(input, options);
|
|
16914
|
+
const rescued = await answerWithoutFillerPrefix(input, options, result);
|
|
16915
|
+
if (rescued) result = rescued;
|
|
16605
16916
|
if (!result || typeof result !== "object") return result;
|
|
16606
16917
|
return { ...result, factsTouched: await factsTouchedSince(memoryDir, before) };
|
|
16607
16918
|
}
|
|
@@ -16968,6 +17279,7 @@ async function dispatchTurn(input, { config, source = defaultSource, graph = nul
|
|
|
16968
17279
|
const follow = await planFollowUpAnswer(workingLine, {
|
|
16969
17280
|
memoryDir, planHolder,
|
|
16970
17281
|
pendingPager: !!(Array.isArray(last?.detail?.pending?.items) && last.detail.pending.items.length),
|
|
17282
|
+
gameConfig: resolvedGameConfig,
|
|
16971
17283
|
});
|
|
16972
17284
|
if (follow) {
|
|
16973
17285
|
note(trace, `goal: ${follow.deduced}`);
|
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
// viz-boot.mjs — the shared wink-nlp vendor loader six
|
|
2
|
-
//
|
|
1
|
+
// viz-boot.mjs — the shared wink-nlp vendor loader the six viz modules each
|
|
2
|
+
// hand-rolled with the same bounded-race shape (`research-viz.mjs`,
|
|
3
3
|
// `ingest-viz.mjs`, `plan-viz.mjs`, `ledger-viz.mjs`, `sprite-catalog-viz.mjs`,
|
|
4
4
|
// `chat-page-viz.mjs`, each commenting that it uses "the same pattern" as a
|
|
5
|
-
// sibling
|
|
5
|
+
// sibling).
|
|
6
6
|
// `import()` can fail in a way that neither resolves nor rejects (a stalled
|
|
7
7
|
// network request, an old cached asset), so every copy already raced it
|
|
8
8
|
// against a timeout rather than awaiting it unbounded.
|
|
9
9
|
//
|
|
10
|
-
// This converges the
|
|
10
|
+
// This converges the six onto ONE failure behaviour: a fixed timer from
|
|
11
11
|
// the call, memoized so a second boot path awaiting the same load (every
|
|
12
12
|
// caller here has at least two — an eager fire-and-forget at page load, then
|
|
13
13
|
// an `await` inside its own session-ensuring function) resolves immediately
|
|
14
|
-
// rather than racing the import a second time. That is the shape
|
|
15
|
-
//
|
|
14
|
+
// rather than racing the import a second time. That is the shape most of the
|
|
15
|
+
// six already shared; `chat-page-viz.mjs`'s own richer variant measures the
|
|
16
16
|
// timeout from the last downloaded byte instead of the call, so a slow-but-
|
|
17
17
|
// progressing multi-megabyte download is never abandoned mid-stream — a real
|
|
18
18
|
// improvement this shared version does not attempt to fold in, so that page
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
// `import()` expression, so when this factory's returned function is spliced
|
|
24
24
|
// into a page's own inline `<script>` via `Function.prototype.toString()`,
|
|
25
25
|
// the import path resolves relative to that page, exactly like every one of
|
|
26
|
-
// the
|
|
26
|
+
// the six originals.
|
|
27
27
|
|
|
28
28
|
/**
|
|
29
29
|
* `loadWinkVendor({ timeoutMs, register, importVendor })` returns a memoized
|
|
@@ -33,7 +33,7 @@
|
|
|
33
33
|
* importing again.
|
|
34
34
|
*
|
|
35
35
|
* `register(factory)` is called once, only on a successful load, with a
|
|
36
|
-
* factory returning `{ winkNLP, model }` — the shape every one of the
|
|
36
|
+
* factory returning `{ winkNLP, model }` — the shape every one of the six
|
|
37
37
|
* originals hands to their own page's `registerWinkModel`. `importVendor`
|
|
38
38
|
* (default: `() => import("./vendor/wink.js")`) is the dynamic import call
|
|
39
39
|
* itself, injectable so a test can supply a resolved/rejected/never-settling
|