@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.
@@ -1,253 +0,0 @@
1
- // code-explorer-browser-entry.mjs — the esbuild entry for the code explorer's
2
- // LIVE chat (public/code-explorer.bundle.js / electron/renderer/
3
- // code-explorer.bundle.js). It mirrors ledger-browser-entry.mjs, but seeds the
4
- // full runTurn engine from a CODE graph — and, when the page hands one over,
5
- // the same general-knowledge seed payload chat.html boots from — so one
6
- // session answers "which functions call Y" over the loaded graph and "what is
7
- // a queue" over the seeded memory.
8
- //
9
- // The graph enters through source.mjs's provider seam — the same seam the CLI
10
- // and HTTP surfaces read — so runTurn's symbol-grain lanes see the whole
11
- // payload, while parseEntities builds the coarse graph the flat lanes read.
12
- // The seed enters the in-memory store the same way createChatSession's does.
13
- // Gitignored, built fresh by scripts/build-code-explorer-bundle.mjs; the page
14
- // degrades to a static view when it is absent (renderCodeExplorerHtml's own
15
- // contract), so nothing here is ever published.
16
- import { vocabExampleHint } from "../../services/chat.mjs";
17
- import { createInMemoryStore, normFactTerm } from "../../adapters/memory/core.mjs";
18
- import { parseEntities } from "../../domain/codegraph.mjs";
19
- import { loadLexicon } from "../../domain/grammar/lexicon.mjs";
20
- import { registerWinkModel } from "../../adapters/wink-model.mjs";
21
- import * as source from "../../adapters/source.mjs";
22
- import { computeCodeExplorerData, computeCodeLedger, edgePhrase } from "../../services/code-explorer-viz.mjs";
23
- import { generateCodeHints } from "../../domain/code-explorer-hints.mjs";
24
- import { createTurnSession } from "./turn-session.mjs";
25
- import { publishTmctSurface } from "./tmct-surface.mjs";
26
- import { graphAsk, enginePlan } from "./engine-surface.mjs";
27
- import { tmct_ask } from "../../tools/handlers/tmct-ask.mjs";
28
- import { RELATIONS } from "../../domain/ask-vocab.mjs";
29
-
30
- /**
31
- * A browser code-explorer session over the real turn engine. Registers the
32
- * loaded payload with source.mjs's provider seam, parses the coarse graph, and
33
- * dispatches every turn through the same runTurn the CLI runs.
34
- *
35
- * `seedPayload` (optional) is a serialized memory graph (loadMemory's shape,
36
- * built by scripts/build-chat-seed.mjs) assigned onto the session's fresh
37
- * in-memory store, so general-knowledge questions ground alongside the code
38
- * graph's own lanes. `vocabSeeded` tells the vocabulary hint whether that
39
- * payload carries the starter vocabulary. Teaches land in the same in-memory
40
- * store, so a taught fact never touches disk.
41
- *
42
- * Returns { memoryDir, sessionId, graph, turn }, the createChatSession shape the
43
- * page's chat expects.
44
- */
45
- export function createCodeExplorerSession({ graphPayload, seedPayload = null, vocabSeeded = false } = {}) {
46
- const payload = graphPayload || { individuals: [], objectProperties: [] };
47
- source.registerProvider(() => payload);
48
-
49
- const graph = parseEntities(payload);
50
- const memoryDir = createInMemoryStore();
51
- // Spread onto the store's own empty payload so a partial seed (individuals
52
- // and objectProperties only) still carries the classes/prefixes scaffolding
53
- // the write path recounts — teach turns must work on any seed.
54
- if (seedPayload) memoryDir.payload = { ...memoryDir.payload, ...seedPayload };
55
- const lexicon = loadLexicon();
56
- const vocabHint = vocabExampleHint(vocabSeeded, "browser");
57
- const sessionId = globalThis.crypto?.randomUUID?.() ?? String(Date.now());
58
- // A stable virtual path: the provider answers every fetch, so no file is
59
- // ever read, but the code lanes still do path math (join/dirname) on it.
60
- const config = { graphFile: "graph.json" };
61
-
62
- const turnSession = createTurnSession({
63
- memoryDir, graph, lexicon, sessionId, vocabHint,
64
- // The code explorer is the one page whose turns run against a real
65
- // provider seam (source.mjs, registered above) and a virtual graph file
66
- // path, so both override createTurnSession's config:null/source:null
67
- // defaults on every call.
68
- buildExtraOptions: () => ({ config, source }),
69
- });
70
-
71
- return {
72
- memoryDir,
73
- sessionId,
74
- graph,
75
- turn: turnSession.turn,
76
- };
77
- }
78
-
79
- // ---- "what relates to X", asked ------------------------------------------
80
-
81
- // A symbol-grain predicate asks as its coarse sibling: ask()'s relation
82
- // vocabulary carries one question per grain pair, not two.
83
- const COARSE_RELATION = { callsSymbol: "calls", touchesSymbol: "touches" };
84
-
85
- /** The two questions ask() understands about one relation kind, both spelled
86
- * from its own vocabulary: `verbs[0]` reads as the reverse direction ("what
87
- * couples to X"), `bare` as the forward one ("what does X import"). A relation
88
- * taught to ask-vocab is asked here with no second table to keep in step. */
89
- function relationQuestions(kind, term) {
90
- const { bare, verbs } = RELATIONS[kind];
91
- return [
92
- { shape: "reverse", query: `what ${verbs[0]} ${term}` },
93
- { shape: "forward", query: `what does ${term} ${bare}` },
94
- ];
95
- }
96
-
97
- /** The kinds worth asking about: the ones this graph actually stores, folded
98
- * onto ask()'s vocabulary keys. A graph carrying only imports asks two
99
- * questions, not twenty. */
100
- function askableRelationKinds(graph) {
101
- const kinds = new Set();
102
- for (const relation of graph.relations) {
103
- if (!relation.edges.length) continue;
104
- const kind = COARSE_RELATION[relation.predicate] || relation.predicate;
105
- if (Object.hasOwn(RELATIONS, kind)) kinds.add(kind);
106
- }
107
- return [...kinds];
108
- }
109
-
110
- /** Every stored edge as `<subjectId> <objectId>`, keyed by the coarse relation
111
- * kind so both grains of a pair land in one set, beside a label-to-ids index.
112
- * An answer names the individuals it found; these two decide whether the row
113
- * built from that answer is an edge the graph actually holds. */
114
- function indexEdges(graph) {
115
- const edgesByKind = new Map();
116
- for (const relation of graph.relations) {
117
- const kind = COARSE_RELATION[relation.predicate] || relation.predicate;
118
- let pairs = edgesByKind.get(kind);
119
- if (!pairs) edgesByKind.set(kind, (pairs = new Set()));
120
- for (const edge of relation.edges) pairs.add(`${edge.subject} ${edge.object}`);
121
- }
122
- const idsByLabel = new Map();
123
- for (const individual of graph.individuals) {
124
- if (!individual?.label || !individual.id) continue;
125
- const ids = idsByLabel.get(individual.label);
126
- if (ids) ids.push(individual.id);
127
- else idsByLabel.set(individual.label, [individual.id]);
128
- }
129
- return { edgesByKind, idsByLabel };
130
- }
131
-
132
- // parseEntities walks the whole payload, and a focus click re-asks the same
133
- // graph, so one parse and one edge index per payload serve every question put
134
- // to it.
135
- const readGraphs = new WeakMap();
136
- function readGraph(payload) {
137
- let read = readGraphs.get(payload);
138
- if (!read) {
139
- const graph = parseEntities(payload);
140
- read = { graph, ...indexEdges(graph) };
141
- readGraphs.set(payload, read);
142
- }
143
- return read;
144
- }
145
-
146
- const rowKey = (row) => JSON.stringify([row.s, row.kind, row.o]);
147
-
148
- /**
149
- * "What relates to <term>", asked instead of computed. Every relation kind the
150
- * loaded graph carries becomes two real tmct_ask round trips over that graph —
151
- * the same ask() every chat turn on this page already reaches — and the
152
- * answers' typed `matches` become the explorer sidebar's rows. The page stops
153
- * deciding what relates to what, so the panel and the conversation cannot
154
- * scope or phrase one question two ways.
155
- *
156
- * Two things have to hold before an answer becomes a row. ask() must have
157
- * parsed the question as the question asked: an identifier that is itself a
158
- * relation verb makes it read "what tests run" as a question about testing, and
159
- * rows off that answer would describe the wrong term. And the row must be an
160
- * edge this graph holds between the term and what the answer named — ask()
161
- * resolves a term against the asked relation's own range, so "what contains
162
- * Task" legitimately answers about `Task.title`'s container, which is a true
163
- * sentence about a different pair than the one the sidebar is drawing. A row
164
- * the graph cannot confirm is dropped rather than shown; the engine's own prose
165
- * is where an inexact resolution belongs, because there it can say so.
166
- *
167
- * `grounded` is false when no question was understood as asked, which is the
168
- * caller's signal to fall back rather than show an empty neighbourhood for a
169
- * term the graph plainly has edges for.
170
- *
171
- * Returns { term, rows, asked, grounded }: `rows` in computeCodeLedger's own
172
- * row shape so one renderer draws both, `asked` every question put to the
173
- * engine beside what came back.
174
- */
175
- export function askRelatedFacts(graphPayload, term) {
176
- const rows = [];
177
- const asked = [];
178
- let grounded = false;
179
- if (!graphPayload || !term) return { term: term || null, rows, asked, grounded };
180
-
181
- const { graph, edgesByKind, idsByLabel } = readGraph(graphPayload);
182
- // An edge group's objectLabel is denormalized and can be shorter than the
183
- // individual's own ("assignTo" for `Task.assignTo`), so the row list offers
184
- // clickable terms this graph holds no individual for. There is nothing to ask
185
- // about one, and saying so leaves the caller its row-list fallback instead of
186
- // an answered-and-empty neighbourhood.
187
- const termIds = idsByLabel.get(term) || [];
188
- if (!termIds.length) return { term, rows, asked, grounded };
189
-
190
- const seen = new Set();
191
- for (const kind of askableRelationKinds(graph)) {
192
- const storedEdges = edgesByKind.get(kind) || new Set();
193
- const holdsEdge = (subjectId, objectId) => storedEdges.has(`${subjectId} ${objectId}`);
194
- for (const { shape, query } of relationQuestions(kind, term)) {
195
- const envelope = tmct_ask({ query }, { graph }).data;
196
- const parsed = envelope?.parsed;
197
- const answeredAsAsked = parsed?.shape === shape
198
- && parsed?.kind === kind
199
- && parsed?.object === term
200
- && !envelope.ambiguous;
201
- if (!answeredAsAsked) {
202
- asked.push({ query, kind, shape, used: false, parsedAs: parsed?.canonical?.machine ?? null });
203
- continue;
204
- }
205
- grounded = true;
206
- const matches = Array.isArray(envelope.matches) ? envelope.matches : [];
207
- let confirmed = 0;
208
- for (const match of matches) {
209
- if (!match?.label || !match.id) continue;
210
- const aboutTerm = termIds.some((termId) => (shape === "reverse"
211
- ? holdsEdge(match.id, termId)
212
- : holdsEdge(termId, match.id)));
213
- if (!aboutTerm) continue;
214
- confirmed += 1;
215
- const row = shape === "reverse"
216
- ? { s: match.label, kind, phrase: edgePhrase(kind), o: term, sClass: match.type || "", oClass: "" }
217
- : { s: term, kind, phrase: edgePhrase(kind), o: match.label, sClass: "", oClass: match.type || "" };
218
- const key = rowKey(row);
219
- if (seen.has(key)) continue;
220
- seen.add(key);
221
- rows.push(row);
222
- }
223
- asked.push({ query, kind, shape, used: true, miss: Boolean(envelope.miss), matched: matches.length, confirmed, traversal: envelope.traversal ?? null });
224
- }
225
- }
226
- return { term, rows, asked, grounded };
227
- }
228
-
229
- // This page holds a REAL code graph, so `tmct.ask` is the engine answering
230
- // over it — the same round trip askRelatedFacts already makes twice per
231
- // relation kind to build the sidebar's rows.
232
- //
233
- // `tmct.page` keeps the re-derivation helpers a graph swapped through the
234
- // desktop picker re-renders with, plus the wink and term-normalizing seams the
235
- // chat shares with the ledger page. `createCodeExplorerSession` sits there
236
- // too: the page keeps its own session slot, created lazily on the first turn
237
- // once the general-knowledge seed has landed, rather than the one `tmct.open`
238
- // would install eagerly — so it calls the factory straight from the bag.
239
- publishTmctSurface({
240
- open: createCodeExplorerSession,
241
- ask: graphAsk,
242
- plan: enginePlan,
243
- page: {
244
- createCodeExplorerSession,
245
- askRelatedFacts,
246
- computeCodeExplorerData,
247
- computeCodeLedger,
248
- generateCodeHints,
249
- parseEntities,
250
- normFactTerm,
251
- registerWinkModel,
252
- },
253
- });