@polycode-projects/the-mechanical-code-talker 5.0.28 → 5.0.30
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/corpus/conceptnet/README.md +85 -41
- package/corpus/conceptnet/commonsenseqa-seed.mjs +322 -0
- package/corpus/conceptnet/filter-dump.mjs +6 -1
- package/corpus/conceptnet/manifest.json +51 -0
- package/corpus/conceptnet/quality-filter.mjs +11 -0
- package/corpus/conceptnet/slice.jsonl +28365 -42942
- package/package.json +2 -2
- package/src/domain/agent-belief.mjs +33 -11
- package/src/domain/choice-question.mjs +125 -1
- package/src/domain/el-classify.mjs +16 -0
- package/src/domain/grammar/ace.mjs +66 -3
- package/src/domain/news-feed.mjs +30 -6
- package/src/domain/tableau.mjs +101 -14
- package/src/services/chat-page-viz.mjs +6 -3
- package/src/services/extensions.mjs +9 -2
- package/src/services/mudiii-turn.mjs +114 -3
- package/src/services/mudiii-viz.mjs +85 -1
- package/src/services/news-viz.mjs +2 -0
- package/src/services/news.mjs +3 -2
- package/src/services/predator-prey.mjs +77 -33
- package/src/surfaces/web/memory-ask-browser.bundle.js +132 -132
- package/src/surfaces/web/mudiii-browser-entry.mjs +13 -2
- package/src/surfaces/web/news-browser-entry.mjs +20 -1
- package/src/surfaces/web/planner-instances.mjs +64 -3
package/src/domain/tableau.mjs
CHANGED
|
@@ -47,6 +47,7 @@ const notE = (c) => ({ t: "not", c });
|
|
|
47
47
|
const andE = (cs) => ({ t: "and", cs });
|
|
48
48
|
const orE = (cs) => ({ t: "or", cs });
|
|
49
49
|
const someE = (r, c) => ({ t: "some", r, c });
|
|
50
|
+
const allE = (r, c) => ({ t: "all", r, c });
|
|
50
51
|
|
|
51
52
|
/** A stable string key for a concept expression. Sorting, dedup and clash
|
|
52
53
|
* detection all go through this, so two structurally equal expressions are
|
|
@@ -222,6 +223,10 @@ export const DEFAULT_PROVE_NODES = 512;
|
|
|
222
223
|
* module never sees, so the caller pairs this with entailedTrustFrom. */
|
|
223
224
|
export const TABLEAU_RULE_CONFIDENCE = 0.95;
|
|
224
225
|
export const DEFAULT_MODULE_HOPS = 4;
|
|
226
|
+
/** Caps how many asserted ABox role edges one KB admits — a data-structure
|
|
227
|
+
* size bound for termination, applied after sorting so truncation is
|
|
228
|
+
* deterministic rather than arrival-ordered. */
|
|
229
|
+
export const MAX_ROLE_ASSERTIONS = 256;
|
|
225
230
|
|
|
226
231
|
// ---- identity: the UNA-lite merge machinery --------------------------------
|
|
227
232
|
//
|
|
@@ -838,7 +843,19 @@ function buildInitialBranch(kb, extraAssertions) {
|
|
|
838
843
|
inequalityFrom.set(key, existing ? sortedUnique([...existing, ...pair.from]) : sortedUnique(pair.from));
|
|
839
844
|
}
|
|
840
845
|
|
|
841
|
-
|
|
846
|
+
// An asserted ABox role edge — the only source of a branch edge besides
|
|
847
|
+
// the ∃/≥-rules' own generated successors. Pushed in the KB's own sorted
|
|
848
|
+
// order (buildTableauKb sorts roleAssertions by subject/predicate/object
|
|
849
|
+
// before returning), so the branch is byte-identical whatever order the
|
|
850
|
+
// underlying rows arrived in.
|
|
851
|
+
const edges = [];
|
|
852
|
+
for (const ra of kb.roleAssertions || []) {
|
|
853
|
+
ensureNode(ra.a);
|
|
854
|
+
ensureNode(ra.b);
|
|
855
|
+
edges.push({ from: ra.a, r: ra.r, to: ra.b, fromFacts: ra.from.slice() });
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
return { nodes, edges, closed: false, clash: null, inequalityFrom };
|
|
842
859
|
}
|
|
843
860
|
|
|
844
861
|
/** Is the KB plus the given assertions satisfiable? `extraAssertions` is
|
|
@@ -905,15 +922,30 @@ function describeClashKind(clash) {
|
|
|
905
922
|
return `complement:${clash.keyA}~${clash.keyB}`;
|
|
906
923
|
}
|
|
907
924
|
|
|
925
|
+
// The closed OWL/RDFS vocabulary buildTableauKb's own predicate dispatch
|
|
926
|
+
// recognises (lower-cased, matching the `p` this file always compares
|
|
927
|
+
// against). Shared with extractTableauModule so both agree on what counts
|
|
928
|
+
// as a role assertion — any row whose predicate is NOT in this set — rather
|
|
929
|
+
// than drifting into two separate definitions of "recognised vocabulary".
|
|
930
|
+
const RECOGNISED_KB_PREDICATES = new Set([
|
|
931
|
+
"owl:onproperty", "owl:somevaluesfrom", "owl:allvaluesfrom", "owl:onclass",
|
|
932
|
+
"owl:mincardinality", "owl:maxcardinality", "owl:cardinality",
|
|
933
|
+
"rdfs:subclassof", "owl:disjointwith", "rdf:type", "mgxneg:subclassof",
|
|
934
|
+
"owl:unionof", "owl:complementof", "rdfs:subpropertyof", "owl:differentfrom",
|
|
935
|
+
"owl:oneof", "owl:inverseof",
|
|
936
|
+
]);
|
|
937
|
+
|
|
908
938
|
/** Build the tableau knowledge base from a row set — on a real question,
|
|
909
939
|
* the output of extractTableauModule, never the raw store. Pure. Returns
|
|
910
940
|
* { axioms, assertions, roles, individuals, transitiveRoles, roleClosure,
|
|
911
|
-
* namedIndividuals, nominalIndividuals, differentFrom, inverseOf
|
|
941
|
+
* namedIndividuals, nominalIndividuals, differentFrom, inverseOf,
|
|
942
|
+
* roleAssertions }. */
|
|
912
943
|
export function buildTableauKb(rows) {
|
|
913
944
|
const list = Array.isArray(rows) ? rows.filter((r) => r && r.subject && r.predicate) : [];
|
|
914
945
|
|
|
915
946
|
const onPropertyOf = new Map(); // restriction -> { object, id }
|
|
916
947
|
const someValuesFromOf = new Map();
|
|
948
|
+
const allValuesFromOf = new Map();
|
|
917
949
|
const onClassOf = new Map();
|
|
918
950
|
const cardinalityOf = new Map(); // restriction -> { kind, n, id }
|
|
919
951
|
const unionMembersOf = new Map(); // union node -> [row, …]
|
|
@@ -927,6 +959,7 @@ export function buildTableauKb(rows) {
|
|
|
927
959
|
const subPropertyRows = [];
|
|
928
960
|
const differentFromRows = [];
|
|
929
961
|
const inverseOfRows = [];
|
|
962
|
+
const roleAssertionCandidates = [];
|
|
930
963
|
|
|
931
964
|
const pushMap = (map, key, value) => {
|
|
932
965
|
if (!map.has(key)) map.set(key, []);
|
|
@@ -937,6 +970,7 @@ export function buildTableauKb(rows) {
|
|
|
937
970
|
const p = String(r.predicate).trim().toLowerCase();
|
|
938
971
|
if (p === "owl:onproperty") onPropertyOf.set(r.subject, { object: r.object, id: r.id });
|
|
939
972
|
else if (p === "owl:somevaluesfrom") someValuesFromOf.set(r.subject, { object: r.object, id: r.id });
|
|
973
|
+
else if (p === "owl:allvaluesfrom") allValuesFromOf.set(r.subject, { object: r.object, id: r.id });
|
|
940
974
|
else if (p === "owl:onclass") onClassOf.set(r.subject, { object: r.object, id: r.id });
|
|
941
975
|
else if (p === "owl:mincardinality") cardinalityOf.set(r.subject, { kind: "min", n: Number(r.object), id: r.id });
|
|
942
976
|
else if (p === "owl:maxcardinality") cardinalityOf.set(r.subject, { kind: "max", n: Number(r.object), id: r.id });
|
|
@@ -954,6 +988,7 @@ export function buildTableauKb(rows) {
|
|
|
954
988
|
else if (p === "owl:differentfrom") differentFromRows.push(r);
|
|
955
989
|
else if (p === "owl:oneof") pushMap(oneOfMembersOf, r.subject, r);
|
|
956
990
|
else if (p === "owl:inverseof") inverseOfRows.push(r);
|
|
991
|
+
else roleAssertionCandidates.push(r);
|
|
957
992
|
}
|
|
958
993
|
|
|
959
994
|
const individualNamesFromType = new Set();
|
|
@@ -963,6 +998,20 @@ export function buildTableauKb(rows) {
|
|
|
963
998
|
}
|
|
964
999
|
const isIndividualTerm = (term) => CODE_REF_SHAPE.test(term) || individualNamesFromType.has(term);
|
|
965
1000
|
|
|
1001
|
+
// An asserted role edge between two named individuals: any predicate
|
|
1002
|
+
// outside the recognised OWL/RDFS vocabulary, both of whose terms resolve
|
|
1003
|
+
// as individuals — a class-level relation ("human mgx:capableOf think")
|
|
1004
|
+
// is not read as an ABox edge. Classification waits for
|
|
1005
|
+
// individualNamesFromType above to exist, so candidates are collected in
|
|
1006
|
+
// the predicate-dispatch pass and filtered here, in a second pass. Sorted
|
|
1007
|
+
// by subject, then predicate, then object, and capped AFTER sorting so
|
|
1008
|
+
// truncation is deterministic rather than arrival-ordered.
|
|
1009
|
+
const roleAssertions = roleAssertionCandidates
|
|
1010
|
+
.filter((r) => isIndividualTerm(r.subject) && isIndividualTerm(r.object))
|
|
1011
|
+
.sort((a, b) => a.subject.localeCompare(b.subject) || a.predicate.localeCompare(b.predicate) || a.object.localeCompare(b.object))
|
|
1012
|
+
.slice(0, MAX_ROLE_ASSERTIONS)
|
|
1013
|
+
.map((r) => ({ a: r.subject, r: r.predicate, b: r.object, from: [r.id] }));
|
|
1014
|
+
|
|
966
1015
|
const mkAxiom = (sub, sup, from) => ({ sub, sup, from: sortedUnique(from), disjunction: toNNF(orE([notE(sub), sup])) });
|
|
967
1016
|
|
|
968
1017
|
const axioms = [];
|
|
@@ -980,6 +1029,11 @@ export function buildTableauKb(rows) {
|
|
|
980
1029
|
axioms.push(mkAxiom(atom(r.subject), someE(propRow.object, atom(svfRow.object)), [r.id, propRow.id, svfRow.id]));
|
|
981
1030
|
continue;
|
|
982
1031
|
}
|
|
1032
|
+
const avfRow = allValuesFromOf.get(restriction);
|
|
1033
|
+
if (avfRow) {
|
|
1034
|
+
axioms.push(mkAxiom(atom(r.subject), allE(propRow.object, atom(avfRow.object)), [r.id, propRow.id, avfRow.id]));
|
|
1035
|
+
continue;
|
|
1036
|
+
}
|
|
983
1037
|
const cardRow = cardinalityOf.get(restriction);
|
|
984
1038
|
const onClassRow = onClassOf.get(restriction);
|
|
985
1039
|
if (cardRow && onClassRow) {
|
|
@@ -1057,6 +1111,7 @@ export function buildTableauKb(rows) {
|
|
|
1057
1111
|
|
|
1058
1112
|
const roles = new Set();
|
|
1059
1113
|
for (const { object } of onPropertyOf.values()) roles.add(object);
|
|
1114
|
+
for (const ra of roleAssertions) roles.add(ra.r);
|
|
1060
1115
|
|
|
1061
1116
|
const subPropertyEdges = subPropertyRows
|
|
1062
1117
|
.map((r) => [r.subject, r.object])
|
|
@@ -1070,12 +1125,15 @@ export function buildTableauKb(rows) {
|
|
|
1070
1125
|
a.from.join(",").localeCompare(b.from.join(",")));
|
|
1071
1126
|
assertions.sort((a, b) => a.ind.localeCompare(b.ind) || canonicalKey(a.expr).localeCompare(canonicalKey(b.expr)));
|
|
1072
1127
|
|
|
1073
|
-
const individuals = [...new Set(
|
|
1128
|
+
const individuals = [...new Set([
|
|
1129
|
+
...assertions.map((a) => a.ind),
|
|
1130
|
+
...roleAssertions.flatMap((ra) => [ra.a, ra.b]),
|
|
1131
|
+
])].sort();
|
|
1074
1132
|
const namedIndividuals = new Set(individuals);
|
|
1075
1133
|
|
|
1076
1134
|
return {
|
|
1077
1135
|
axioms, assertions, roles: [...roles].sort(), individuals, transitiveRoles, roleClosure,
|
|
1078
|
-
namedIndividuals, nominalIndividuals, differentFrom, inverseOf,
|
|
1136
|
+
namedIndividuals, nominalIndividuals, differentFrom, inverseOf, roleAssertions,
|
|
1079
1137
|
};
|
|
1080
1138
|
}
|
|
1081
1139
|
|
|
@@ -1086,6 +1144,7 @@ function restrictKbToIndividual(kb, ind) {
|
|
|
1086
1144
|
roles: kb.roles,
|
|
1087
1145
|
individuals: [ind],
|
|
1088
1146
|
transitiveRoles: kb.transitiveRoles,
|
|
1147
|
+
roleAssertions: kb.roleAssertions,
|
|
1089
1148
|
roleClosure: kb.roleClosure,
|
|
1090
1149
|
namedIndividuals: kb.namedIndividuals,
|
|
1091
1150
|
nominalIndividuals: kb.nominalIndividuals,
|
|
@@ -1123,15 +1182,20 @@ function addToSetMap(map, key, value) {
|
|
|
1123
1182
|
/** Restrict fact rows to the signature-connected module around a set of
|
|
1124
1183
|
* seed terms. `rdfs:subClassOf` closes unbounded in both directions (it is
|
|
1125
1184
|
* always followed, at no hop cost); a restriction's filler (owl:onProperty
|
|
1126
|
-
* / owl:someValuesFrom / owl:onClass) and owl:unionOf /
|
|
1127
|
-
* owl:oneOf membership are hop-bounded structural edges.
|
|
1128
|
-
* through a restriction's filler edge re-seeds that term's
|
|
1129
|
-
* full hop budget, so a chain of restrictions extends the
|
|
1130
|
-
* an unbounded hop count; a union/complement/oneOf
|
|
1131
|
-
* spends one hop.
|
|
1132
|
-
*
|
|
1133
|
-
*
|
|
1134
|
-
*
|
|
1185
|
+
* / owl:someValuesFrom / owl:allValuesFrom / owl:onClass) and owl:unionOf /
|
|
1186
|
+
* owl:complementOf / owl:oneOf membership are hop-bounded structural edges.
|
|
1187
|
+
* Reaching a term through a restriction's filler edge re-seeds that term's
|
|
1188
|
+
* own walk at the full hop budget, so a chain of restrictions extends the
|
|
1189
|
+
* module without an unbounded hop count; a union/complement/oneOf
|
|
1190
|
+
* membership edge simply spends one hop. An asserted ABox role edge
|
|
1191
|
+
* (buildTableauKb's own role-assertion reader test: a predicate outside
|
|
1192
|
+
* the recognised OWL/RDFS vocabulary, both terms individuals) reseeds its
|
|
1193
|
+
* far endpoint's own walk the same way a restriction filler does — a chain
|
|
1194
|
+
* of asserted edges extends the module without an unbounded hop count
|
|
1195
|
+
* either. The returned rows are every row whose subject or object lands in
|
|
1196
|
+
* the resulting signature, plus any role axiom naming a role an included
|
|
1197
|
+
* restriction or role assertion uses. Pure, no I/O. Returns the restricted
|
|
1198
|
+
* row array, in the input's own row order. */
|
|
1135
1199
|
export function extractTableauModule(rows, seedTerms, { hops = DEFAULT_MODULE_HOPS } = {}) {
|
|
1136
1200
|
const list = Array.isArray(rows) ? rows.filter((r) => r && r.subject && r.predicate) : [];
|
|
1137
1201
|
const hopBudget = clampNonNegativeInt(hops, DEFAULT_MODULE_HOPS);
|
|
@@ -1147,15 +1211,30 @@ export function extractTableauModule(rows, seedTerms, { hops = DEFAULT_MODULE_HO
|
|
|
1147
1211
|
const memberComplements = new Map();
|
|
1148
1212
|
const oneOfMembers = new Map();
|
|
1149
1213
|
const memberOneOf = new Map();
|
|
1214
|
+
const roleAssertionRows = []; // { subject, predicate, object } — same reader test as buildTableauKb
|
|
1215
|
+
const roleAssertionEndpoints = new Map(); // term -> Set(other endpoint), both directions
|
|
1216
|
+
|
|
1217
|
+
const individualNamesFromType = new Set();
|
|
1218
|
+
for (const r of list) {
|
|
1219
|
+
if (String(r.predicate).trim().toLowerCase() !== "rdf:type") continue;
|
|
1220
|
+
const obj = String(r.object || "").toLowerCase();
|
|
1221
|
+
if (!META_TYPE_OBJECTS.has(obj)) individualNamesFromType.add(r.subject);
|
|
1222
|
+
}
|
|
1223
|
+
const isIndividualTerm = (term) => CODE_REF_SHAPE.test(term) || individualNamesFromType.has(term);
|
|
1150
1224
|
|
|
1151
1225
|
for (const r of list) {
|
|
1152
1226
|
const p = String(r.predicate).trim().toLowerCase();
|
|
1153
1227
|
if (p === "rdfs:subclassof") { addToSetMap(subUp, r.subject, r.object); addToSetMap(subDown, r.object, r.subject); }
|
|
1154
1228
|
else if (p === "owl:onproperty") onPropertyOf.set(r.subject, r.object);
|
|
1155
|
-
else if (p === "owl:somevaluesfrom" || p === "owl:onclass") { fillerOf.set(r.subject, r.object); addToSetMap(fillerBack, r.object, r.subject); }
|
|
1229
|
+
else if (p === "owl:somevaluesfrom" || p === "owl:allvaluesfrom" || p === "owl:onclass") { fillerOf.set(r.subject, r.object); addToSetMap(fillerBack, r.object, r.subject); }
|
|
1156
1230
|
else if (p === "owl:unionof") { addToSetMap(unionMembers, r.subject, r.object); addToSetMap(memberUnions, r.object, r.subject); }
|
|
1157
1231
|
else if (p === "owl:complementof") { complementPair.set(r.subject, r.object); addToSetMap(memberComplements, r.object, r.subject); }
|
|
1158
1232
|
else if (p === "owl:oneof") { addToSetMap(oneOfMembers, r.subject, r.object); addToSetMap(memberOneOf, r.object, r.subject); }
|
|
1233
|
+
else if (!RECOGNISED_KB_PREDICATES.has(p) && isIndividualTerm(r.subject) && isIndividualTerm(r.object)) {
|
|
1234
|
+
roleAssertionRows.push(r);
|
|
1235
|
+
addToSetMap(roleAssertionEndpoints, r.subject, r.object);
|
|
1236
|
+
addToSetMap(roleAssertionEndpoints, r.object, r.subject);
|
|
1237
|
+
}
|
|
1159
1238
|
}
|
|
1160
1239
|
|
|
1161
1240
|
const subClosureCache = new Map();
|
|
@@ -1210,10 +1289,18 @@ export function extractTableauModule(rows, seedTerms, { hops = DEFAULT_MODULE_HO
|
|
|
1210
1289
|
for (const c of memberComplements.get(term) || []) enqueue(c, hopsLeft - 1);
|
|
1211
1290
|
for (const m of oneOfMembers.get(term) || []) enqueue(m, hopsLeft - 1);
|
|
1212
1291
|
for (const c of memberOneOf.get(term) || []) enqueue(c, hopsLeft - 1);
|
|
1292
|
+
|
|
1293
|
+
// A role-assertion edge reseeds its far endpoint's own walk, the same
|
|
1294
|
+
// discipline a restriction chain gets — otherwise a question about one
|
|
1295
|
+
// end of an asserted edge extracts a module that does not contain the
|
|
1296
|
+
// edge, and the far endpoint's own facts (its type, its restrictions)
|
|
1297
|
+
// never enter the module either.
|
|
1298
|
+
for (const other of roleAssertionEndpoints.get(term) || []) enqueue(other, hopBudget);
|
|
1213
1299
|
}
|
|
1214
1300
|
|
|
1215
1301
|
const rolesUsed = new Set();
|
|
1216
1302
|
for (const [restriction, role] of onPropertyOf) if (included.has(restriction)) rolesUsed.add(role);
|
|
1303
|
+
for (const r of roleAssertionRows) if (included.has(r.subject) || included.has(r.object)) rolesUsed.add(r.predicate);
|
|
1217
1304
|
|
|
1218
1305
|
return list.filter((r) => {
|
|
1219
1306
|
if (included.has(r.subject) || included.has(r.object)) return true;
|
|
@@ -63,8 +63,11 @@ function provKey(tier) {
|
|
|
63
63
|
* (no chip: a miss, or an answer that grounds in nothing citable, e.g. /help
|
|
64
64
|
* output or a focus-set confirmation).
|
|
65
65
|
*
|
|
66
|
-
* Reads the SAME "(source: ...)" citation(s) the
|
|
67
|
-
* carries
|
|
66
|
+
* Reads the SAME "(source: ...)" / "(sources: ...; ...)" citation(s) the
|
|
67
|
+
* visible answer text already carries — the singular form a flat fact
|
|
68
|
+
* citation or a proof-chain step uses, the plural, semicolon-joined form a
|
|
69
|
+
* digest read-back's source line uses (termDigestReadBack, chat.mjs) — via
|
|
70
|
+
* `bucketFor` (the page's own spliced copy of ledger-viz.mjs's
|
|
68
71
|
* `provBucketFor`, injected rather than imported so this function stays
|
|
69
72
|
* `.toString()`-splice safe — the same discipline spider-fly-viz.mjs's own
|
|
70
73
|
* `threadCellsForSpiderPlan` holds its own injected `geometry` to).
|
|
@@ -94,7 +97,7 @@ function provKey(tier) {
|
|
|
94
97
|
*/
|
|
95
98
|
export function provenanceChipFor(answer, record, bucketFor) {
|
|
96
99
|
if (!record || record.miss) return null;
|
|
97
|
-
const cites = [...String(answer || "").matchAll(/\(
|
|
100
|
+
const cites = [...String(answer || "").matchAll(/\(sources?: ([^)]+)\)/g)].flatMap((m) => m[1].split("; "));
|
|
98
101
|
if (!cites.length) return record.via === "assert" ? "taught" : null;
|
|
99
102
|
const buckets = cites.map((c) => bucketFor([], c));
|
|
100
103
|
const allTaught = buckets.every((b) => b === "taught");
|
|
@@ -50,8 +50,15 @@ const TIER2_EMPTY_VOCAB_FILE = join(dirname(fileURLToPath(import.meta.url)), "..
|
|
|
50
50
|
export const EXTENSION_KINDS = Object.freeze(["corpus", "lexicon", "templates", "pack", "ontology"]);
|
|
51
51
|
|
|
52
52
|
// The definitional-band-first predicate order for the ConceptNet seed (re-declared,
|
|
53
|
-
// not imported, to keep this module off chat.mjs's heavy graph).
|
|
54
|
-
|
|
53
|
+
// not imported, to keep this module off chat.mjs's heavy graph). The five
|
|
54
|
+
// relational predicates after the definitional backbone are the ones a
|
|
55
|
+
// commonsense multiple-choice question keys on (atLocation, causes, desires,
|
|
56
|
+
// motivatedByGoal, hasSubevent) — ranked ahead of the rest so the band cap
|
|
57
|
+
// buys them before it buys more RelatedTo.
|
|
58
|
+
const CONCEPTNET_PREFER = [
|
|
59
|
+
"rdfs:subClassOf", "rdf:type", "mgx:usedFor", "mgx:partOf", "mgx:capableOf",
|
|
60
|
+
"mgx:atLocation", "mgx:causes", "mgx:desires", "mgx:motivatedByGoal", "mgx:hasSubevent",
|
|
61
|
+
];
|
|
55
62
|
|
|
56
63
|
/** The shipped defaults — a FRESH object per call, so a caller can never
|
|
57
64
|
* accidentally mutate a module-level singleton. */
|
|
@@ -18,16 +18,21 @@ import {
|
|
|
18
18
|
agentKindOf, liveIdsOfKind, layoutNamed, isFoodId,
|
|
19
19
|
} from "../domain/town-square-world.mjs";
|
|
20
20
|
import {
|
|
21
|
-
MUDIII_ROLES, foldTownSquareState, startTownSquareGame, runTownSquareTick,
|
|
21
|
+
MUDIII_ROLES, foldTownSquareState, startTownSquareGame, runTownSquareTick, planTownSquareTurn,
|
|
22
22
|
placeFood, roleOfId, beliefSnapshotFor,
|
|
23
23
|
} from "./predator-prey.mjs";
|
|
24
24
|
import { snapshotSubject, parseSnapshotSubject } from "./adventure.mjs";
|
|
25
25
|
import { correctMisspellings, QUESTION_LEAD_RE } from "../domain/interpret/normalize.mjs";
|
|
26
26
|
import { worldProvenanceTag } from "../domain/worlds-pack.mjs";
|
|
27
27
|
import { getWorldsPackProvider } from "../adapters/corpus/worlds-pack.mjs";
|
|
28
|
-
import { appendFacts, appendRule, loadMemory, readFactRows } from "../adapters/memory/core.mjs";
|
|
28
|
+
import { appendFacts, appendRule, loadMemory, readFactRows, readRuleRows } from "../adapters/memory/core.mjs";
|
|
29
29
|
import { DEFAULT_GAME_CONFIG } from "../domain/game-config.mjs";
|
|
30
|
-
import { agentTraitsOf } from "../domain/agent-traits.mjs";
|
|
30
|
+
import { agentTraitsOf, constraintsFromDrives } from "../domain/agent-traits.mjs";
|
|
31
|
+
import { beliefOriginOf } from "../domain/agent-belief.mjs";
|
|
32
|
+
import {
|
|
33
|
+
compileDomain, stateFromFacts, stateKeyFor, movesFromRules, compileGoal, PlanBudgetError,
|
|
34
|
+
} from "../domain/domain.mjs";
|
|
35
|
+
import { findActionPath } from "../domain/planning.mjs";
|
|
31
36
|
|
|
32
37
|
const PREDATOR_KIND = MUDIII_ROLES.predator.kind; // "fox"
|
|
33
38
|
const PREY_KIND = MUDIII_ROLES.prey.kind; // "goblin"
|
|
@@ -522,6 +527,112 @@ async function mudiiiBeliefAnswer(match, { memoryDir, gameConfig = DEFAULT_GAME_
|
|
|
522
527
|
};
|
|
523
528
|
}
|
|
524
529
|
|
|
530
|
+
// ---- beliefs and plans, recomputed live, no turn spent ----------------------
|
|
531
|
+
|
|
532
|
+
// The one puzzle this plan ships (PLAN_RIVER_CROSSING.md's R3): a world that
|
|
533
|
+
// carries no "ferry onto" action-signature has no puzzle plan to compute, so
|
|
534
|
+
// riverPuzzleOutlook stays null on the town square and any other board with
|
|
535
|
+
// no ferry action rule.
|
|
536
|
+
const RIVER_CROSSING_ACTION = "ferry onto";
|
|
537
|
+
const RIVER_CROSSING_GOAL = [{ universal: true, term: "passenger", predicate: "currently-in", object: "bank-west" }];
|
|
538
|
+
|
|
539
|
+
/** The river-crossing puzzle's own plan, recomputed from `rows`/`ruleRows` as
|
|
540
|
+
* they stand right now: the world's own action rules plus whatever
|
|
541
|
+
* action-constraint rows the drive facts themselves imply
|
|
542
|
+
* (constraintsFromDrives), searched the same way the chat lane solves
|
|
543
|
+
* data/games/river.txt. Null on a world whose rule rows carry no "ferry
|
|
544
|
+
* onto" action-signature, or whose action domain does not carry a
|
|
545
|
+
* "passenger" class the goal can quantify over. Returns `{ moves, plan,
|
|
546
|
+
* miss }`: `moves` is every legal move from the CURRENT position (the empty
|
|
547
|
+
* list when nothing may move), `plan` is the found action sequence or null,
|
|
548
|
+
* `miss` is null when a plan was found and the stated reason otherwise — a
|
|
549
|
+
* budget decline as well as an exhausted search, never a shortened plan
|
|
550
|
+
* either way. Pure. */
|
|
551
|
+
function riverPuzzleOutlook(rows, ruleRows) {
|
|
552
|
+
const hasFerryAction = (ruleRows || []).some((r) => r.kind === "action-signature" && r.name === RIVER_CROSSING_ACTION);
|
|
553
|
+
if (!hasFerryAction) return null;
|
|
554
|
+
const derived = constraintsFromDrives(rows).map((slots) => ({ name: RIVER_CROSSING_ACTION, kind: "action-constraint", slots }));
|
|
555
|
+
const domain = compileDomain(rows, [...(ruleRows || []), ...derived]);
|
|
556
|
+
let isGoal;
|
|
557
|
+
try {
|
|
558
|
+
isGoal = compileGoal(RIVER_CROSSING_GOAL, domain);
|
|
559
|
+
} catch {
|
|
560
|
+
return null; // this board's action domain is not the river puzzle's own shape
|
|
561
|
+
}
|
|
562
|
+
const start = stateFromFacts(rows, domain);
|
|
563
|
+
const moves = movesFromRules(start, domain).map((m) => m.action.label);
|
|
564
|
+
const maxDepth = DEFAULT_GAME_CONFIG.planning.maxDepth;
|
|
565
|
+
try {
|
|
566
|
+
const found = findActionPath(start, isGoal, (s) => movesFromRules(s, domain), { maxDepth, stateKey: stateKeyFor });
|
|
567
|
+
return { moves, plan: found ? found.actions : null, miss: found ? null : `no plan found within ${maxDepth} moves` };
|
|
568
|
+
} catch (err) {
|
|
569
|
+
if (!(err instanceof PlanBudgetError)) throw err;
|
|
570
|
+
return { moves, plan: null, miss: `action grounding count ${err.groundings} exceeds the budget of ${err.budget}` };
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
/** Every live agent's belief map and plan, computed from the store as it
|
|
575
|
+
* stands right now, without writing a fact or advancing a turn. Runs the
|
|
576
|
+
* SAME derivation runTownSquareTick's own decision phase performs
|
|
577
|
+
* (predator-prey.mjs's planTownSquareTurn) and reads only the answers — the
|
|
578
|
+
* rung, the goal line, the belief snapshot and the plan each live agent
|
|
579
|
+
* would carry into its NEXT tick — never a tick's effects (no eating, no
|
|
580
|
+
* spawn, no mass debit, no write).
|
|
581
|
+
*
|
|
582
|
+
* `layout` is optional here (unlike runTownSquareTick, which requires one):
|
|
583
|
+
* a board with no town-square roster to decide over — the puzzle world
|
|
584
|
+
* before R6 wires it to a layout, or a caller asking only about `puzzle` —
|
|
585
|
+
* still gets its `puzzle` field computed, with `agents` empty rather than a
|
|
586
|
+
* thrown "no such layout".
|
|
587
|
+
*
|
|
588
|
+
* Returns `{ turn, agents: { id: { rung, goal, belief, beliefOrigin, plan,
|
|
589
|
+
* traits } }, puzzle: { moves, plan, miss } | null }`. `beliefOrigin` mirrors
|
|
590
|
+
* `belief`'s own key set, each value `"seen"`, `{ told: turn }` or null —
|
|
591
|
+
* `beliefOriginOf` walking the exact cell/candidates/opts the tick's own
|
|
592
|
+
* belief snapshot was taken with (planTownSquareTurn's `beliefContext`), so
|
|
593
|
+
* a panel's cell and its "how it knows" label can never disagree.
|
|
594
|
+
*
|
|
595
|
+
* Deterministic: a pure function of the store's current rows (and
|
|
596
|
+
* `toldFacts`), whatever order either arrived in. Two calls with no edit
|
|
597
|
+
* between them, or the same rows fed in twice in a different order, return
|
|
598
|
+
* deep-equal results. */
|
|
599
|
+
export async function agentOutlook(memoryDir, {
|
|
600
|
+
layout = null, toldFacts = [], config = DEFAULT_GAME_CONFIG.mudiii, roles = MUDIII_ROLES,
|
|
601
|
+
} = {}) {
|
|
602
|
+
const memory = await loadMemory(memoryDir);
|
|
603
|
+
const rows = readFactRows(memory);
|
|
604
|
+
const ruleRows = readRuleRows(memory);
|
|
605
|
+
const state = foldTownSquareState(rows);
|
|
606
|
+
|
|
607
|
+
const outlookAgents = {};
|
|
608
|
+
if (layout) {
|
|
609
|
+
const { agents, rungs, beliefContext, traitRows } =
|
|
610
|
+
planTownSquareTurn(rows, state, { layout, config, roles, toldFacts, manualMoves: {} });
|
|
611
|
+
for (const id of Object.keys(agents).sort()) {
|
|
612
|
+
const ctx = beliefContext[id];
|
|
613
|
+
const beliefOrigin = {};
|
|
614
|
+
for (const candidateId of ctx.candidates) {
|
|
615
|
+
if (candidateId === id) continue;
|
|
616
|
+
beliefOrigin[candidateId] = beliefOriginOf(candidateId, id, ctx.cell, state, ctx.opts);
|
|
617
|
+
}
|
|
618
|
+
for (const candidateId of ctx.foodCandidates) {
|
|
619
|
+
if (candidateId === id) continue;
|
|
620
|
+
beliefOrigin[candidateId] = beliefOriginOf(candidateId, id, ctx.cell, state, ctx.foodOpts);
|
|
621
|
+
}
|
|
622
|
+
outlookAgents[id] = {
|
|
623
|
+
rung: rungs[id],
|
|
624
|
+
goal: agents[id].goal,
|
|
625
|
+
belief: agents[id].belief,
|
|
626
|
+
beliefOrigin,
|
|
627
|
+
plan: agents[id].plan,
|
|
628
|
+
traits: agentTraitsOf(traitRows, id),
|
|
629
|
+
};
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
return { turn: state.tickCount, agents: outlookAgents, puzzle: riverPuzzleOutlook(rows, ruleRows) };
|
|
634
|
+
}
|
|
635
|
+
|
|
525
636
|
function noLivePlacedSubjectAnswer(kind) {
|
|
526
637
|
return {
|
|
527
638
|
text: `there's no live ${kind} on the board for that to be about.`,
|
|
@@ -727,6 +727,15 @@ ${RING_POINTS.map((point) => ` <span class="dir-slot dir-${point}"><button
|
|
|
727
727
|
<div class="chatpills" id="actorEditorPills" aria-label="related words for the term before the cursor"></div>
|
|
728
728
|
<p class="edit-status" id="actorEditorStatus" role="status"></p>
|
|
729
729
|
</section>
|
|
730
|
+
<section class="outlook-panel" id="mudiiiOutlookPanel" aria-label="the followed actor's own beliefs and plan">
|
|
731
|
+
<h2>what it believes, and its plan</h2>
|
|
732
|
+
<table class="outlook-belief-table" id="outlookBeliefTable" aria-label="what the followed actor currently believes">
|
|
733
|
+
<caption>beliefs</caption>
|
|
734
|
+
<tbody id="outlookBeliefBody"></tbody>
|
|
735
|
+
</table>
|
|
736
|
+
<p class="outlook-plan" id="outlookPlanText" role="status"></p>
|
|
737
|
+
<p class="outlook-plan outlook-puzzle-plan" id="outlookPuzzlePlanText" role="status" hidden></p>
|
|
738
|
+
</section>
|
|
730
739
|
<section class="mudiii-chat" aria-label="talk to the square">
|
|
731
740
|
<div class="chatlog" id="chatLog" aria-live="polite"></div>
|
|
732
741
|
<div class="log-popup" id="chatLogPopup" role="dialog" aria-label="the whole reply" hidden>
|
|
@@ -991,6 +1000,18 @@ const MUDIII_STYLE = `
|
|
|
991
1000
|
}
|
|
992
1001
|
#actorEditorText:disabled { opacity: .55; }
|
|
993
1002
|
|
|
1003
|
+
.outlook-panel {
|
|
1004
|
+
display: none; flex-direction: column; gap: .45rem; margin-bottom: 1rem;
|
|
1005
|
+
background: var(--parchment); border: 1px solid var(--square-stone-dark); border-radius: 4px;
|
|
1006
|
+
box-shadow: 0 2px 0 rgba(0,0,0,.18); padding: .7rem .8rem; min-width: 0;
|
|
1007
|
+
}
|
|
1008
|
+
body.editing .outlook-panel { display: flex; }
|
|
1009
|
+
.outlook-panel h2 { margin: 0; font-size: .8rem; }
|
|
1010
|
+
.outlook-belief-table { width: 100%; border-collapse: collapse; font-family: ${MONO_STACK}; font-size: .68rem; }
|
|
1011
|
+
.outlook-belief-table caption { caption-side: top; text-align: left; font-size: .62rem; color: var(--square-stone-dark); padding-bottom: .2rem; }
|
|
1012
|
+
.outlook-belief-table td { padding: .12rem .4rem .12rem 0; vertical-align: top; }
|
|
1013
|
+
.outlook-plan { margin: 0; font-family: ${MONO_STACK}; font-size: .68rem; white-space: pre-wrap; color: var(--square-ink); }
|
|
1014
|
+
|
|
994
1015
|
.mudiii-chat { background: var(--parchment); border: 1px solid var(--square-stone-dark); border-radius: 4px; box-shadow: 0 2px 0 rgba(0,0,0,.18); padding: .7rem .8rem; display: flex; flex-direction: column; gap: .5rem; }
|
|
995
1016
|
.chatlog { min-height: 8rem; max-height: 16rem; overflow-y: auto; }
|
|
996
1017
|
.chatlog > * { margin: 0 0 .32rem; }
|
|
@@ -1602,7 +1623,7 @@ function pageScript() {
|
|
|
1602
1623
|
camera = { mode: mode, selectedId: id, status: null };
|
|
1603
1624
|
renderCameraButtons();
|
|
1604
1625
|
renderDriveRing();
|
|
1605
|
-
if (editing) renderActorEditor();
|
|
1626
|
+
if (editing) { renderActorEditor(); renderOutlookPanel(); }
|
|
1606
1627
|
sendCameraToScene(camera);
|
|
1607
1628
|
});
|
|
1608
1629
|
|
|
@@ -1764,6 +1785,7 @@ function pageScript() {
|
|
|
1764
1785
|
renderSuggestionPills();
|
|
1765
1786
|
renderEditPlacements();
|
|
1766
1787
|
renderActorEditor();
|
|
1788
|
+
await refreshOutlook();
|
|
1767
1789
|
}
|
|
1768
1790
|
|
|
1769
1791
|
function exitEditMode() {
|
|
@@ -1864,6 +1886,7 @@ function pageScript() {
|
|
|
1864
1886
|
: "synced \\u2014 no change.";
|
|
1865
1887
|
}
|
|
1866
1888
|
renderEditPlacements();
|
|
1889
|
+
await refreshOutlook();
|
|
1867
1890
|
}
|
|
1868
1891
|
|
|
1869
1892
|
// ---- actor card (per-instance edit) -------------------------------------
|
|
@@ -2009,6 +2032,66 @@ function pageScript() {
|
|
|
2009
2032
|
? "synced \\u2014 " + result.added + " fact(s) written, " + result.removed + " retracted."
|
|
2010
2033
|
: "synced \\u2014 no change.";
|
|
2011
2034
|
}
|
|
2035
|
+
await refreshOutlook();
|
|
2036
|
+
}
|
|
2037
|
+
|
|
2038
|
+
// ---- belief and plan panels: recomputed live, no turn spent ------------
|
|
2039
|
+
// agentOutlook (mudiii-turn.mjs, reached through session.outlook()) is a
|
|
2040
|
+
// pure read over the store as it stands — same rows, same outlook, byte
|
|
2041
|
+
// for byte, whatever order they arrived in. Refreshed on boot and after
|
|
2042
|
+
// every edit (world or actor); the follow select alone just re-renders the
|
|
2043
|
+
// already-fetched outlook for whichever agent it now names, no new fetch.
|
|
2044
|
+
let lastOutlook = null;
|
|
2045
|
+
|
|
2046
|
+
async function refreshOutlook() {
|
|
2047
|
+
if (!session || !session.outlook) return;
|
|
2048
|
+
lastOutlook = await session.outlook();
|
|
2049
|
+
renderOutlookPanel();
|
|
2050
|
+
}
|
|
2051
|
+
|
|
2052
|
+
function beliefOriginText(cell, origin) {
|
|
2053
|
+
if (!cell) return "nothing seen, nothing told";
|
|
2054
|
+
if (origin === "seen") return "seen";
|
|
2055
|
+
if (origin && typeof origin === "object" && "told" in origin) return "told, turn " + origin.told;
|
|
2056
|
+
return "seen";
|
|
2057
|
+
}
|
|
2058
|
+
|
|
2059
|
+
function renderOutlookPanel() {
|
|
2060
|
+
const id = el("agentSelect").value;
|
|
2061
|
+
const body = el("outlookBeliefBody");
|
|
2062
|
+
const planText = el("outlookPlanText");
|
|
2063
|
+
const puzzleText = el("outlookPuzzlePlanText");
|
|
2064
|
+
const entry = (lastOutlook && id) ? lastOutlook.agents[id] : null;
|
|
2065
|
+
if (!entry) {
|
|
2066
|
+
body.innerHTML = '<tr><td class="outlook-empty" colspan="3">Follow an agent above to see what it believes.</td></tr>';
|
|
2067
|
+
planText.textContent = "";
|
|
2068
|
+
puzzleText.hidden = true;
|
|
2069
|
+
return;
|
|
2070
|
+
}
|
|
2071
|
+
const subjects = Object.keys(entry.belief).sort();
|
|
2072
|
+
body.innerHTML = subjects.length
|
|
2073
|
+
? subjects.map(function (subject) {
|
|
2074
|
+
const cell = entry.belief[subject];
|
|
2075
|
+
const howText = beliefOriginText(cell, entry.beliefOrigin[subject]);
|
|
2076
|
+
return '<tr><td class="mono">' + esc(subject) + '</td><td class="mono">' + esc(cell || "\\u2014") + "</td><td>" + esc(howText) + "</td></tr>";
|
|
2077
|
+
}).join("")
|
|
2078
|
+
: '<tr><td class="outlook-empty" colspan="3">' + esc(id) + " is alone on the board \\u2014 nothing else to believe anything about.</td></tr>";
|
|
2079
|
+
const planLine = entry.plan.length ? entry.plan.join(" \\u2192 ") : "holding";
|
|
2080
|
+
planText.textContent = id + "'s plan (" + entry.rung + "): " + planLine + " \\u2014 " + entry.goal;
|
|
2081
|
+
const puzzle = lastOutlook.puzzle;
|
|
2082
|
+
if (!puzzle) {
|
|
2083
|
+
puzzleText.hidden = true;
|
|
2084
|
+
puzzleText.textContent = "";
|
|
2085
|
+
} else {
|
|
2086
|
+
puzzleText.hidden = false;
|
|
2087
|
+
if (puzzle.plan) {
|
|
2088
|
+
const n = puzzle.plan.length;
|
|
2089
|
+
const moveLines = puzzle.plan.map(function (a, i) { return " " + (i + 1) + ". " + a.label; }).join("\\n");
|
|
2090
|
+
puzzleText.textContent = "puzzle plan \\u2014 found " + n + " move" + (n === 1 ? "" : "s") + " (shortest):\\n" + moveLines;
|
|
2091
|
+
} else {
|
|
2092
|
+
puzzleText.textContent = "puzzle plan \\u2014 " + puzzle.miss;
|
|
2093
|
+
}
|
|
2094
|
+
}
|
|
2012
2095
|
}
|
|
2013
2096
|
|
|
2014
2097
|
// ---- booting ---------------------------------------------------------
|
|
@@ -2086,6 +2169,7 @@ function pageScript() {
|
|
|
2086
2169
|
camera.selectedId = openingFollowId(opening.agents);
|
|
2087
2170
|
applyTickResult(opening);
|
|
2088
2171
|
renderAll();
|
|
2172
|
+
await refreshOutlook();
|
|
2089
2173
|
if (!prefersReducedMotion()) {
|
|
2090
2174
|
autoOn = true;
|
|
2091
2175
|
ensureTicker().play();
|
|
@@ -331,6 +331,8 @@ const SEED_BYTES = ${Number(seedBytes) || 0};
|
|
|
331
331
|
if (!feed.items.length) { emptyEl.hidden = false; setTile("tileFeedItems", 0, "nothing yet"); return; }
|
|
332
332
|
emptyEl.hidden = true;
|
|
333
333
|
for (const item of feed.items) {
|
|
334
|
+
// One yield per card keeps the page clickable while a long feed renders.
|
|
335
|
+
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
334
336
|
const card = document.createElement("div");
|
|
335
337
|
card.className = "item";
|
|
336
338
|
const seedTag = feed.seedFallback ? '<span class="seedtag">from the seed graph — start to poll live sources</span>' : "";
|
package/src/services/news.mjs
CHANGED
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
|
|
40
40
|
import { normFactTerm, normFactPredicate, factIdFor, sha256Bytes } from "../domain/hash.mjs";
|
|
41
41
|
import {
|
|
42
|
-
newsWindowRows, scoreHubs, subgraphAround, renderNewsParagraph, buildNewsItems, evictNewsFacts,
|
|
42
|
+
newsWindowRows, scoreHubs, subgraphAround, buildTermAdjacency, renderNewsParagraph, buildNewsItems, evictNewsFacts,
|
|
43
43
|
} from "../domain/news-feed.mjs";
|
|
44
44
|
import {
|
|
45
45
|
createTermLedger, bumpTerms, rankedTerms, markTerm, groundedSweep, ledgerPayload, ledgerFromPayload,
|
|
@@ -293,8 +293,9 @@ function collectItemSources(subgraphRows, sourcesByFactId) {
|
|
|
293
293
|
* buildNewsItems's own, already-pinned window contract. */
|
|
294
294
|
function assembleNewsItems(rows, windowRows, { now, limit, sourcesByFactId }) {
|
|
295
295
|
const hubs = scoreHubs(rows, windowRows, { limit });
|
|
296
|
+
const adjacency = buildTermAdjacency(rows);
|
|
296
297
|
const items = hubs.map(({ term, changed }) => {
|
|
297
|
-
const subgraphRows = subgraphAround(rows, term);
|
|
298
|
+
const subgraphRows = subgraphAround(rows, term, { adjacency });
|
|
298
299
|
const factIds = subgraphRows.map((r) => r.id).sort();
|
|
299
300
|
return {
|
|
300
301
|
id: `news-feed:${sha256HexPrefix(`${term}\0${factIds.join(",")}`, 8)}`,
|