@polycode-projects/the-mechanical-code-talker 5.0.19 → 5.0.21

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 CHANGED
@@ -116,7 +116,6 @@ derive by rule from both. Every answer is either grounded or an honest miss.
116
116
  | `infra/` | the AWS CDK app that provisions the deployed site and its OIDC/deploy roles |
117
117
  | `examples/` | runnable example scripts and fixture repos used by the README's own examples and the test suite |
118
118
  | `demo/` | standalone demo scripts (e.g. the agentic-loop demo) |
119
- | `electron/` | the Electron desktop app wrapper |
120
119
  | `docs/` | reference docs: the adapter/repository-interface contracts, bibliography |
121
120
  | `test/` | the unit, corpus, and estate-guard test suite (`npm test`) |
122
121
  | `test-e2e/` | the end-to-end suite: real CLI/TUI spawns and Playwright browser journeys (`npm run test:e2e`) |
@@ -124,7 +123,7 @@ derive by rule from both. Every answer is either grounded or an honest miss.
124
123
  | `reports/` | benchmark write-ups (`BENCHMARK_*.md`) and `PAGE_WEIGHTS.md` — see the root `STATUS.md` for the one-page summary these feed |
125
124
  | `playtests/` | numbered playtest session logs, one edge found and fixed per entry |
126
125
  | `archive/` | delivered `PLAN_*.md`/`BENCHMARK_*.md` docs, kept for history |
127
- | `public/` | the demo site: the hand-written home page, the eleven about pages, the shared stylesheet and the model/screenshot assets. The demo pages and browser bundles beside them are gitignored build outputs of `npm run demo:build` |
126
+ | `public/` | the demo site: the hand-written home page, the six about pages, the shared stylesheet and the model/screenshot assets. The demo pages and browser bundles beside them are gitignored build outputs of `npm run demo:build` |
128
127
 
129
128
  `node_modules/` (dependencies) and dotfiles/hidden tooling directories are omitted above.
130
129
 
@@ -412,21 +411,16 @@ tmct> /exit
412
411
 
413
412
  **[Try it live in your browser →](https://tmct.polycode.co.uk/)**
414
413
  runs the actual query engine client-side. No server, no install. The landing
415
- page answers codebase questions live, and eleven more pages each ground their
414
+ page answers codebase questions live, and six more pages each ground their
416
415
  own domain: a full chat seeded with 63,470 facts (the same nine bands as
417
416
  `npm run init:xl`), the
418
417
  **memory ledger** (every fact as a readable sentence; drill by clicking the
419
- terms inside), and the **code explorer** (the same ledger UI refocused on a
420
- code graph, with a hint rail of suggested next questions). An **ingest
421
- page** turns pasted or dropped text into grounded facts and downloads them
422
- as canonical JSONL, and a **research page** walks a stub wiki graph link by
423
- link. The rest are a Towers-of-Hanoi plan replayed move by move, the
424
- spider-and-fly and text-adventure games, a sprite gallery whose chat dock
425
- answers from 1,480 generated sprite facts, and two multi-agent worlds: a
426
- burrow that shares one world across browsers over WebRTC, and a Three.js
427
- town square where a wolf hunts goblins. The chat page and
428
- the ledger take the same paste-or-drop text in place; every page that holds
429
- a fact store exports it as JSONL.
418
+ terms inside), and a Towers-of-Hanoi **plan** replayed move by move. A 3D
419
+ **town square** has a fox and goblins each plan their own move from what
420
+ they've personally seen. The rest are the text-adventure game and a
421
+ **sprite gallery** whose chat dock answers from 1,480 generated sprite
422
+ facts. The chat page and the ledger take the same paste-or-drop text in
423
+ place; every page that holds a fact store exports it as JSONL.
430
424
  The site hosts its own copy of wink-nlp, ships its assets precompressed,
431
425
  and a service worker precaches the big ones, so a second visit works
432
426
  offline. `tmct chat --render spider-fly|adventure|sprites [--output <path>]`
@@ -457,38 +451,6 @@ npx tmct chat --prompt 'disk-1 rests on disk-2. disk-2 rests on disk-3.
457
451
 
458
452
  More on the game file and the planner under "Teach it a game" below.
459
453
 
460
- ### The code explorer (desktop)
461
-
462
- The same ledger UI, refocused on a code graph, also runs as a desktop app. It
463
- reads a `graph.json` (or a repo's `.tmct/` folder), shows every import, call and
464
- `contains` edge as a plain sentence around a focus symbol, and docks a live chat
465
- over the same graph. A hint rail suggests the next question from what the graph
466
- actually holds: "what does X import", "which functions call Y", "list
467
- functions". Every suggestion resolves to a real answer.
468
-
469
- The identical page also runs as a plain hosted page over the demo code
470
- graph, with nothing to install:
471
- **[try it live →](https://tmct.polycode.co.uk/code.html)**.
472
- The desktop build below is for exploring your own repo or graph: a browser page
473
- gets no filesystem access, so the hosted page reads the demo graph it ships with.
474
-
475
- Electron is a dev-only dependency and never ships in the npm package. Because
476
- `.npmrc` sets `ignore-scripts=true`, installing it does not fetch the runtime
477
- binary; fetch it once, then build and launch:
478
-
479
- ```bash skip=network
480
- npm i -D electron
481
- node node_modules/electron/install.js # fetch the Electron binary (ignore-scripts skips this)
482
- npm run build:electron # render electron/renderer/ from the demo graph
483
- npm run electron # open the code explorer on the demo graph
484
- ```
485
-
486
- Open a graph or a repo from the window's title bar to explore your own code.
487
- The UI is channel-agnostic. Only the Electron shell (`electron/main.mjs` +
488
- `electron/preload.cjs`) is desktop-specific. The same page stays servable as a
489
- plain web page. `npm run test:electron` runs the shell smoke via Playwright and
490
- skips cleanly when the binary is absent.
491
-
492
454
  ## How it interprets you
493
455
 
494
456
  Every message runs through **multiple concurrent interpretation strategies**:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@polycode-projects/the-mechanical-code-talker",
3
- "version": "5.0.19",
3
+ "version": "5.0.21",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "The Mechanical Code Talker (tmct) — a tolerant, offline, $0 chat surface that guides you toward precision queries about a software repository. ELIZA/PARRY-style but domain-obsessed with code. No model calls; indexes a repo on request (tmct index) or reads any producer's graph.",
@@ -172,12 +172,8 @@
172
172
  "build:ledger-bundle": "node scripts/build-ledger-bundle.mjs",
173
173
  "build:ingest-bundle": "node scripts/build-ingest-bundle.mjs",
174
174
  "build:research-bundle": "node scripts/build-research-bundle.mjs",
175
- "build:code-explorer-bundle": "node scripts/build-code-explorer-bundle.mjs",
176
175
  "build:mud-bundle": "node scripts/build-mud-bundle.mjs",
177
176
  "build:mudiii-bundle": "node scripts/build-mudiii-bundle.mjs",
178
- "build:electron": "node scripts/build-electron-app.mjs",
179
- "electron": "electron electron/main.mjs",
180
- "test:electron": "node --test electron/smoke.test.mjs",
181
177
  "build:sprites-bundle": "node scripts/build-sprites-bundle.mjs",
182
178
  "build:wink-vendor": "node scripts/build-wink-vendor.mjs",
183
179
  "build:three-vendor": "node scripts/build-three-vendor.mjs",
@@ -201,7 +197,6 @@
201
197
  "extract:facts": "node --disable-warning=ExperimentalWarning bin/tmct.mjs extract"
202
198
  },
203
199
  "devDependencies": {
204
- "electron": "^43.2.0",
205
200
  "esbuild": "0.28.1",
206
201
  "ink-testing-library": "4.0.0",
207
202
  "playwright": "1.61.1",
@@ -1,18 +1,18 @@
1
- // viz-boot.mjs — the shared wink-nlp vendor loader six-plus-one viz modules
2
- // each hand-rolled with the same bounded-race shape (`research-viz.mjs`,
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; `code-explorer-viz.mjs` is a seventh with no timeout at all).
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 seven onto ONE failure behaviour: a fixed timer from
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 five of the
15
- // seven already shared; `chat-page-viz.mjs`'s own richer variant measures the
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 seven originals.
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 seven
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
@@ -1,180 +0,0 @@
1
- // code-explorer-hints.mjs — suggested next queries drawn from what a loaded
2
- // CODE graph actually holds. Pure over the entities payload (individuals +
3
- // objectProperties), so the desktop shell and any future plain page share one
4
- // tested generator and neither hand-writes prompt strings.
5
- //
6
- // The shapes are exactly the ones ask.mjs already answers, phrased from its own
7
- // closed vocabulary (ask-vocab.mjs's RELATIONS/EDGE_NOUN_TO_METRIC): a relation
8
- // only appears in a hint when the graph carries an edge of that kind, and a
9
- // focus symbol only fills a slot when it actually sits at that end of an edge —
10
- // so every suggestion resolves to a real answer, never a guess.
11
-
12
- import { RELATIONS, EDGE_NOUN_TO_METRIC } from "./ask-vocab.mjs";
13
-
14
- // Node classes this explorer reads as code, with the singular/plural nouns
15
- // ask.mjs's own list and count lanes accept (ENTITY_TO_TYPE's inverse). Schema
16
- // documentation individuals (SchemaClass/SchemaPredicate) and anything else are
17
- // left out — they are not what a reader explores.
18
- const CODE_CLASS_NOUN = Object.freeze({
19
- Module: ["module", "modules"],
20
- Class: ["class", "classes"],
21
- Function: ["function", "functions"],
22
- Method: ["method", "methods"],
23
- Attribute: ["attribute", "attributes"],
24
- GlobalVariable: ["variable", "variables"],
25
- Commit: ["commit", "commits"],
26
- });
27
-
28
- // The classes a focus symbol is drawn from — the things a reader centres on.
29
- const FOCUSABLE_CLASSES = new Set(["Module", "Class", "Function", "Method"]);
30
-
31
- // Fine, symbol-grain predicates fold onto their coarse sibling for phrasing:
32
- // "what does X call" covers callsSymbol too, exactly as ask.mjs's
33
- // SYMBOL_GRAIN_SIBLING pairs them.
34
- const GRAIN_BASE = Object.freeze({ callsSymbol: "calls", touchesSymbol: "touches" });
35
- const baseKind = (predicate) => GRAIN_BASE[predicate] || predicate;
36
-
37
- // Forward reading (focus is the subject): "what does <focus> <bare>". The bare
38
- // verb form is ask-vocab's own, so the phrasing tracks the vocabulary.
39
- const FORWARD_TEMPLATE = Object.freeze({
40
- imports: (f) => `what does ${f} import`,
41
- calls: (f) => `what does ${f} call`,
42
- contains: (f) => `what is in ${f}`,
43
- defines: (f) => `what does ${f} define`,
44
- inherits: (f) => `what does ${f} inherit from`,
45
- serves: (f) => `what does ${f} serve`,
46
- denotes: (f) => `what does ${f} denote`,
47
- });
48
-
49
- // Reverse reading (focus is the object): "what <kind> <focus>".
50
- const REVERSE_TEMPLATE = Object.freeze({
51
- imports: (f) => `what imports ${f}`,
52
- calls: (f) => `what calls ${f}`,
53
- tests: (f) => `what tests ${f}`,
54
- inherits: (f) => `what inherits from ${f}`,
55
- contains: (f) => `what contains ${f}`,
56
- serves: (f) => `what serves ${f}`,
57
- denotes: (f) => `what denotes ${f}`,
58
- });
59
-
60
- /** Index a payload into the counts and adjacency the hints read: class →
61
- * count, base relation kind → { count, subjects, objects }, and a label →
62
- * { class, degree } term table over every example edge. */
63
- function indexGraph(payload) {
64
- const individuals = Array.isArray(payload?.individuals) ? payload.individuals : [];
65
- const classOfLabel = new Map();
66
- const classCounts = new Map();
67
- for (const ind of individuals) {
68
- if (!ind || !ind.label) continue;
69
- if (CODE_CLASS_NOUN[ind.class]) classCounts.set(ind.class, (classCounts.get(ind.class) || 0) + 1);
70
- if (!classOfLabel.has(ind.label)) classOfLabel.set(ind.label, ind.class);
71
- }
72
-
73
- const groups = Array.isArray(payload?.objectProperties) ? payload.objectProperties : [];
74
- const kinds = new Map(); // base kind -> { count, subjects:Set, objects:Set }
75
- const degree = new Map(); // label -> degree over example edges
76
- const bumpKind = (k) => kinds.get(k) || kinds.set(k, { count: 0, subjects: new Set(), objects: new Set() }).get(k);
77
- for (const g of groups) {
78
- if (!g || !g.predicate) continue;
79
- const k = baseKind(String(g.predicate));
80
- const entry = bumpKind(k);
81
- entry.count += Number(g.count) || (Array.isArray(g.examples) ? g.examples.length : 0);
82
- for (const e of Array.isArray(g.examples) ? g.examples : []) {
83
- const s = e?.subjectLabel || e?.subject;
84
- const o = e?.objectLabel || e?.object;
85
- if (s) { entry.subjects.add(s); degree.set(s, (degree.get(s) || 0) + 1); }
86
- if (o) { entry.objects.add(o); degree.set(o, (degree.get(o) || 0) + 1); }
87
- }
88
- }
89
- return { classCounts, classOfLabel, kinds, degree };
90
- }
91
-
92
- /** Pick the focus symbol: the caller's choice when it is a real term, else the
93
- * highest-degree focusable-class label, else the highest-degree label at all,
94
- * else null. Ties break on label for determinism. */
95
- function pickFocus(index, requested) {
96
- if (requested && index.degree.has(requested)) return requested;
97
- const ranked = [...index.degree.entries()]
98
- .sort((a, b) => b[1] - a[1] || String(a[0]).localeCompare(String(b[0])));
99
- const focusable = ranked.find(([label]) => FOCUSABLE_CLASSES.has(index.classOfLabel.get(label)));
100
- if (focusable) return focusable[0];
101
- return ranked.length ? ranked[0][0] : null;
102
- }
103
-
104
- /**
105
- * Suggested queries for a loaded code graph.
106
- *
107
- * @param {object} payload the entities payload (individuals + objectProperties).
108
- * @param {object} [opts]
109
- * @param {string} [opts.focus] centre the neighbourhood on this symbol.
110
- * @param {number} [opts.limit] cap the returned hints (default 12).
111
- * @returns {{ focus: (string|null), hints: Array<{text,group,rationale}> }}
112
- * `hints` is ordered neighbourhood → compositional → explore; empty
113
- * when the graph holds nothing to explore.
114
- */
115
- export function generateCodeHints(payload, { focus: requestedFocus = null, limit = 12 } = {}) {
116
- const index = indexGraph(payload);
117
- const focus = pickFocus(index, requestedFocus);
118
- const hints = [];
119
- const add = (text, group, rationale) => hints.push({ text, group, rationale });
120
- const kindPresent = (k) => (index.kinds.get(k)?.count || 0) > 0;
121
-
122
- if (focus) {
123
- for (const [kind, template] of Object.entries(FORWARD_TEMPLATE)) {
124
- if (index.kinds.get(kind)?.subjects.has(focus)) {
125
- add(template(focus), "neighbourhood", `${focus} ${verbBare(kind)} other symbols in this graph`);
126
- }
127
- }
128
- for (const [kind, template] of Object.entries(REVERSE_TEMPLATE)) {
129
- if (index.kinds.get(kind)?.objects.has(focus)) {
130
- add(template(focus), "neighbourhood", `other symbols ${kind} ${focus}`);
131
- }
132
- }
133
- }
134
-
135
- // Compositional shapes over the graph's own edges and classes.
136
- const calls = index.kinds.get("calls");
137
- if (calls && index.classCounts.has("Function") && calls.objects.size) {
138
- const target = [...calls.objects].sort()[0];
139
- add(`which functions call ${target}`, "compositional", `${target} is called somewhere in this graph`);
140
- }
141
- const contains = index.kinds.get("contains");
142
- if (contains && index.classCounts.has("Method")) {
143
- const owner = [...contains.subjects].sort().find((s) => index.classOfLabel.get(s) === "Class");
144
- if (owner) add(`public methods of ${owner}`, "compositional", `${owner} contains members`);
145
- }
146
-
147
- // Explore-the-whole-graph shapes. The rankings and the coverage filter come
148
- // first — they are the more useful whole-graph questions — then a list and a
149
- // count per present class. EDGE_NOUN_TO_METRIC names the nouns ask.mjs's
150
- // superlative lane accepts, so a hint only offers a ranking the graph can
151
- // actually compute.
152
- const superlatives = [
153
- { noun: "imports", entity: "module", filter: "Module" },
154
- { noun: "callers", entity: "function", filter: "Function" },
155
- ];
156
- for (const s of superlatives) {
157
- const metric = EDGE_NOUN_TO_METRIC[s.noun];
158
- if (metric && kindPresent(metric.kind) && index.classCounts.has(s.filter)) {
159
- add(`which ${s.entity} has the most ${s.noun}`, "explore", `rank ${s.entity}s by ${s.noun}`);
160
- }
161
- }
162
- if (kindPresent("tests")) {
163
- add("which of those are tested", "explore", "filter a listing by test coverage");
164
- }
165
- const classesByCount = [...index.classCounts.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
166
- for (const [cls, count] of classesByCount) {
167
- const [, plural] = CODE_CLASS_NOUN[cls];
168
- add(`list ${plural}`, "explore", `${count} ${plural} in this graph`);
169
- add(`how many ${plural}`, "explore", `count the ${plural}`);
170
- }
171
-
172
- return { focus, hints: hints.slice(0, limit) };
173
- }
174
-
175
- // The infinitive ask-vocab curates for each relation, used in rationales.
176
- function verbBare(kind) {
177
- return RELATIONS[kind]?.bare || kind;
178
- }
179
-
180
- export { CODE_CLASS_NOUN, indexGraph };
@@ -1,596 +0,0 @@
1
- // code-explorer-viz.mjs — the code explorer as a full-viewport IDE shell:
2
- // a title bar (graph source, Open graph…/Open repo…), an explorer sidebar
3
- // reading each import/call/contains edge back as a plain sentence, a chat
4
- // centre over the same graph with a rail of suggested questions, and a status
5
- // bar carrying the graph's own counts. Clicking a term asks the engine what
6
- // relates to it (askRelatedFacts, over tmct_ask) and renders the answer, so the
7
- // sidebar and the chat put the same question to the same place.
8
- //
9
- // The chat session seeds BOTH the loaded code graph and chat.html's
10
- // general-knowledge bands (./chat-seed.json, fetched lazily at runtime), so one
11
- // conversation answers "what is a queue" and "what imports src/core/model.mjs"
12
- // alike — and degrades to graph-only when the seed asset is unavailable.
13
- //
14
- // The derivations are pure so the shell, the packaging scripts, and the unit
15
- // tests all share one code path; renderCodeExplorerHtml builds one
16
- // self-contained document that both packagers ship unchanged — the site build
17
- // (scripts/build-demo-site.mjs) and the Electron desktop shell
18
- // (scripts/build-electron-app.mjs). Panels are plain sections inside the
19
- // sidebar/centre grid, so a later panel is one more <section class="panel">,
20
- // not a re-architecture.
21
-
22
- import { THEME_TOKENS_CSS, SERIF_STACK, MONO_STACK, escapeHtml, embedJson, embedScriptText, demoEyebrowHtml, EYEBROW_LINKS_CSS } from "./viz-theme.mjs";
23
- import { generateCodeHints } from "../domain/code-explorer-hints.mjs";
24
- import { phraseForRelation } from "../domain/ask-vocab.mjs";
25
- import { fetchWithProgress } from "./memory-panel-viz.mjs";
26
-
27
- // Third-person verb for each stored relation kind, symbol grain folded onto
28
- // its coarse sibling — derived from ask-vocab.mjs's own RELATIONS table
29
- // rather than a second hand-curated relation-verb table.
30
- export function edgePhrase(kind) {
31
- return phraseForRelation(kind);
32
- }
33
-
34
- // Both packagers (build-electron-app.mjs, build-demo-site.mjs) place
35
- // vendor/wink.js one level below the page they render, so the same loader
36
- // script inlines into renderCodeExplorerHtml's `winkLoaderInline` slot for
37
- // either channel.
38
- export const VENDOR_WINK_LOADER_JS = `window.__WINK_LOADER__ = async function () {
39
- var m = await import("./vendor/wink.js");
40
- return { winkNLP: m.winkNLP, model: m.model };
41
- };`;
42
-
43
- export const DESKTOP_APP_URL = "https://gitlab.com/polycode-projects/the-mechanical-code-talker#the-code-explorer-desktop";
44
-
45
- const LEDGER_ROW_LIMIT_DEFAULT = 4000;
46
-
47
- /** Pure derivation over an entities payload (individuals + objectProperties).
48
- * Returns { rows, terms, focus, stats, meta } — rows are one readable
49
- * sentence per example edge, terms is the degree-ranked label index, and the
50
- * neighbourhood of `focus` survives a row cap first so a huge graph degrades
51
- * to "local + rest" rather than truncating the centre. */
52
- export function computeCodeLedger(payload, { focus = null, rowLimit = LEDGER_ROW_LIMIT_DEFAULT } = {}) {
53
- const individuals = Array.isArray(payload?.individuals) ? payload.individuals : [];
54
- const classOf = new Map();
55
- for (const ind of individuals) if (ind?.label && !classOf.has(ind.label)) classOf.set(ind.label, ind.class || "");
56
-
57
- const groups = Array.isArray(payload?.objectProperties) ? payload.objectProperties : [];
58
- const rows = [];
59
- const degree = new Map();
60
- const kindCounts = new Map();
61
- const bumpTerm = (t) => { if (t) degree.set(t, (degree.get(t) || 0) + 1); };
62
- for (const g of groups) {
63
- if (!g?.predicate) continue;
64
- const kind = String(g.predicate);
65
- kindCounts.set(kind, (kindCounts.get(kind) || 0) + (Number(g.count) || 0));
66
- for (const e of Array.isArray(g.examples) ? g.examples : []) {
67
- const s = e?.subjectLabel || e?.subject;
68
- const o = e?.objectLabel || e?.object;
69
- if (!s || !o) continue;
70
- rows.push({ s, kind, phrase: edgePhrase(kind), o, sClass: classOf.get(s) || "", oClass: classOf.get(o) || "" });
71
- bumpTerm(s); bumpTerm(o);
72
- }
73
- }
74
-
75
- const terms = [...degree.entries()]
76
- .map(([term, deg]) => ({ term, degree: deg, class: classOf.get(term) || "" }))
77
- .sort((a, b) => b.degree - a.degree || a.term.localeCompare(b.term));
78
-
79
- let focusTerm = focus && degree.has(focus) ? focus : null;
80
- if (!focusTerm && terms.length) focusTerm = terms[0].term;
81
-
82
- const classCounts = new Map();
83
- for (const ind of individuals) if (ind?.class) classCounts.set(ind.class, (classCounts.get(ind.class) || 0) + 1);
84
- const stats = {
85
- individuals: individuals.length,
86
- edges: rows.length,
87
- classes: [...classCounts.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])),
88
- kinds: [...kindCounts.entries()].filter(([, c]) => c > 0).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])),
89
- };
90
-
91
- const total = rows.length;
92
- let shown = rows;
93
- if (total > rowLimit) {
94
- const near = new Set([focusTerm]);
95
- for (const r of rows) { if (r.s === focusTerm) near.add(r.o); if (r.o === focusTerm) near.add(r.s); }
96
- const inHood = (r) => near.has(r.s) || near.has(r.o);
97
- shown = [...rows.filter(inHood), ...rows.filter((r) => !inHood(r))].slice(0, rowLimit);
98
- }
99
- return { rows: shown, terms, focus: focusTerm, stats, meta: { shown: shown.length, total, truncated: shown.length < total } };
100
- }
101
-
102
- /** Everything the page embeds, derived once from a payload: the ledger, the
103
- * degree-ranked terms, the suggested queries, and the focus symbol. */
104
- export function computeCodeExplorerData(payload, opts = {}) {
105
- const ledger = computeCodeLedger(payload, opts);
106
- const { focus, hints } = generateCodeHints(payload, { focus: ledger.focus });
107
- return { payload, ledger, hints, focus: ledger.focus || focus, meta: { title: opts.title || "code graph" } };
108
- }
109
-
110
- // ---- client script pieces, spliced into CLIENT_JS below -------------------
111
- // Named module functions so the page's own source reads as a list of calls
112
- // into real, unit-tested code rather than an inlined block. Each is written
113
- // to survive a `.toString()` round trip into a browser `<script>` tag: no
114
- // closure over this module's own scope, only its parameters and whichever
115
- // sibling below it is also spliced into the same page script.
116
-
117
- /** One line naming the loaded graph's own size: individual/edge counts, then
118
- * up to four of its most common classes. */
119
- export function statsSummaryLine(ledgerStats) {
120
- var parts = [ledgerStats.individuals + " individuals", ledgerStats.edges + " edges"];
121
- var cls = ledgerStats.classes.slice(0, 4).map(function (c) { return c[1] + " " + c[0]; });
122
- return parts.concat(cls).join(" · ");
123
- }
124
-
125
- /** Every fact the chat can draw on: the graph's own edges plus whatever the
126
- * general-knowledge seed has counted so far. */
127
- export function factTotalText(edges, seedFacts) {
128
- return (edges + seedFacts).toLocaleString();
129
- }
130
-
131
- export function rowKey(row) { return JSON.stringify([row.s, row.kind, row.o]); }
132
-
133
- /** The sidebar's rows: the engine's own answer about the focus when it
134
- * grounded one, the row list's plain filter otherwise, then whatever
135
- * neither named — a fold over the rest of the graph. */
136
- export function focusRowsHtml(data, related) {
137
- var focus = data.focus;
138
- var rows = data.ledger.rows;
139
- var grounded = Boolean(related && related.grounded);
140
- var near = grounded ? related.rows : rows.filter(function (r) { return r.s === focus || r.o === focus; });
141
- var nearKeys = {};
142
- near.forEach(function (r) { nearKeys[rowKey(r)] = true; });
143
- var rest = rows.filter(function (r) { return !nearKeys[rowKey(r)]; });
144
- var ordered = near.concat(rest);
145
- return ordered.map(function (r) {
146
- var hot = (r.s === focus || r.o === focus) ? " row-focus" : "";
147
- return '<li class="row' + hot + '">'
148
- + '<button class="term" data-term="' + escapeHtml(r.s) + '">' + escapeHtml(r.s) + '</button> '
149
- + '<span class="verb">' + escapeHtml(r.phrase) + '</span> '
150
- + '<button class="term" data-term="' + escapeHtml(r.o) + '">' + escapeHtml(r.o) + '</button>'
151
- + '</li>';
152
- }).join("") || (grounded
153
- ? '<li class="row muted">nothing in this graph relates to ' + escapeHtml(focus) + '.</li>'
154
- : '<li class="row muted">no edges in this graph.</li>');
155
- }
156
-
157
- export function hintsHtml(hints) {
158
- return hints.map(function (h) {
159
- return '<button class="hint" data-q="' + escapeHtml(h.text) + '" title="' + escapeHtml(h.rationale) + '">'
160
- + escapeHtml(h.text) + '</button>';
161
- }).join("") || '<span class="muted">nothing to suggest for this graph.</span>';
162
- }
163
-
164
- export function turnHtml(role, text) {
165
- return '<span class="who">' + (role === "you" ? "you" : "tmct") + '</span><span class="said">' + escapeHtml(text) + '</span>';
166
- }
167
-
168
- export function chatEmptyStateHtml(hasEngine) {
169
- return hasEngine
170
- ? '<p class="chat-empty-head">Ask the graph, or ask it anything</p>'
171
- + '<p>Ask about the code graph on the left, or about anything its general knowledge covers, like “what is a queue”.</p>'
172
- + '<p class="chat-empty-hint">Try one of the questions below, or type your own.</p>'
173
- : '<p class="chat-empty-head">Static view</p>'
174
- + '<p>This page shows a fixed snapshot of the graph. The live chat is not available here.</p>';
175
- }
176
-
177
- export function mbText(n) { return (n / 1048576).toFixed(1); }
178
-
179
- /** How many of the seed's own individuals are facts — the general-knowledge
180
- * half of the fact-total pill. */
181
- export function seedFactsFromPayload(payload) {
182
- return (payload.individuals || []).filter(function (i) { return i.class === "Fact"; }).length;
183
- }
184
-
185
- export function seedLoadingNote(loadedBytes, totalBytes) {
186
- return "loading general knowledge… " + mbText(loadedBytes) + (totalBytes ? " of " + mbText(totalBytes) : "") + " MB";
187
- }
188
-
189
- /** One retry with a cache-busting query param, fetch side only: a CDN edge
190
- * can serve a corrupted or truncated precompressed response (a transient
191
- * bad cache entry, not a code defect — real bytes decompress fine, and the
192
- * same URL fetched moments later is clean), and JSON.parse throwing is the
193
- * only signal of that. `fetcher` is `fetchWithProgress` (or a stand-in for
194
- * a test); `baseUrl` already carries the build's own content-hash query
195
- * string, if any, so the bust param joins with `&` or `?` accordingly. */
196
- export async function fetchSeedPayloadWithRetry(fetcher, baseUrl, seedQuery, onProgress) {
197
- var lastErr = null;
198
- for (var attempt = 1; attempt <= 2; attempt++) {
199
- try {
200
- var bust = attempt === 1 ? "" : (seedQuery ? "&" : "?") + "retry=1";
201
- var seedBlob = await fetcher(baseUrl + seedQuery + bust, onProgress);
202
- var text = await seedBlob.text();
203
- return JSON.parse(text); // throwing here is the corrupted/truncated-response retry signal
204
- } catch (e) {
205
- lastErr = e;
206
- }
207
- }
208
- throw lastErr;
209
- }
210
-
211
- const CLIENT_JS = String.raw`
212
- (function () {
213
- var DATA = window.__CODE_EXPLORER__;
214
- var api = window.tmct ? window.tmct.page : null;
215
- var els = {
216
- focus: document.getElementById("focus-name"),
217
- ledger: document.getElementById("ledger"),
218
- hints: document.getElementById("hints"),
219
- stats: document.getElementById("stats"),
220
- log: document.getElementById("chat-log"),
221
- form: document.getElementById("chat-form"),
222
- input: document.getElementById("chat-input"),
223
- dockNote: document.getElementById("dock-note"),
224
- source: document.getElementById("source-name"),
225
- seedStatus: document.getElementById("seed-status"),
226
- factTotal: document.getElementById("fact-total-value"),
227
- };
228
- var session = null;
229
-
230
- var escapeHtml = ${escapeHtml.toString()};
231
- var rowKey = ${rowKey.toString()};
232
- var statsSummaryLine = ${statsSummaryLine.toString()};
233
- var factTotalText = ${factTotalText.toString()};
234
- var focusRowsHtml = ${focusRowsHtml.toString()};
235
- var hintsHtml = ${hintsHtml.toString()};
236
- var turnHtml = ${turnHtml.toString()};
237
- var chatEmptyStateHtml = ${chatEmptyStateHtml.toString()};
238
-
239
- function renderStats(data) {
240
- els.stats.textContent = statsSummaryLine(data.ledger.stats);
241
- renderFactTotal(data);
242
- }
243
-
244
- // Everything the chat can answer from: the graph's own edges plus the
245
- // general-knowledge seed, which arrives later and re-renders this.
246
- function renderFactTotal(data) {
247
- if (!els.factTotal) return;
248
- var edges = (data && data.ledger && data.ledger.stats && data.ledger.stats.edges) || 0;
249
- els.factTotal.textContent = factTotalText(edges, seedState.facts);
250
- }
251
-
252
- // "What relates to the focus", put to the engine. askRelatedFacts asks
253
- // tmct_ask one question per relation kind the loaded graph carries, in both
254
- // directions, and hands back the answers' own typed rows — the same ask()
255
- // this page's chat turns reach, so the panel and the conversation answer one
256
- // question one way. Null on the static page, which has no engine to ask.
257
- function askRelated(focus) {
258
- if (!api || !api.askRelatedFacts || !focus) return null;
259
- try {
260
- return api.askRelatedFacts(DATA.payload, focus);
261
- } catch (e) {
262
- console.warn("tmct code explorer: the related-facts ask failed, splitting the row list instead", e);
263
- return null;
264
- }
265
- }
266
-
267
- // The engine's answer whenever it grounded one. The row list's own split is
268
- // what is left when there is no engine (the static page) or when every
269
- // question came back parsed as something else — an identifier that is
270
- // itself a relation verb reads as a question about the verb. Whatever the
271
- // neighbourhood did not already name follows, in degree order: a bulk view
272
- // of the rest of the graph, which is a fold and not a question.
273
- function renderFocusRows(data, related) {
274
- els.ledger.innerHTML = focusRowsHtml(data, related);
275
- els.focus.textContent = data.focus || "—";
276
- }
277
-
278
- function renderHints(data) {
279
- els.hints.innerHTML = hintsHtml(data.hints);
280
- }
281
-
282
- function focusOn(term) {
283
- if (!api || !api.computeCodeExplorerData) return;
284
- DATA = api.computeCodeExplorerData(DATA.payload, { focus: term, title: DATA.meta.title });
285
- window.__CODE_EXPLORER__ = DATA;
286
- mountView(DATA);
287
- }
288
-
289
- function mountView(data) {
290
- renderStats(data);
291
- renderFocusRows(data, askRelated(data.focus));
292
- renderHints(data);
293
- }
294
-
295
- function clearEmptyState() {
296
- var e = document.getElementById("chat-empty");
297
- if (e) e.remove();
298
- }
299
-
300
- function appendTurn(role, text) {
301
- clearEmptyState();
302
- var div = document.createElement("div");
303
- div.className = "turn turn-" + role;
304
- div.innerHTML = turnHtml(role, text);
305
- els.log.appendChild(div);
306
- els.log.scrollTop = els.log.scrollHeight;
307
- }
308
-
309
- function renderEmptyState() {
310
- var div = document.createElement("div");
311
- div.className = "chat-empty";
312
- div.id = "chat-empty";
313
- div.innerHTML = chatEmptyStateHtml(Boolean(api));
314
- els.log.appendChild(div);
315
- }
316
-
317
- // ---- the general-knowledge seed --------------------------------------
318
- // The same chat-seed.json chat.html boots from, loaded lazily so the shell
319
- // paints instantly: same-origin fetch on the site, the preload bridge's
320
- // readSeed under the desktop shell (a file:// page cannot fetch). The
321
- // status bar narrates the load; a missing or failing seed leaves the chat
322
- // graph-only and says so, never broken.
323
- // The build's own content hash for the seed rides in the URL, so the service
324
- // worker's cache-first read can only return the copy this page asked for.
325
- // Empty under the desktop shell, which reads the seed off disk instead.
326
- var SEED_QUERY = DATA.seedStamp ? "?b=" + DATA.seedStamp : "";
327
- var seedState = { status: api ? "loading" : "absent", payload: null, facts: 0 };
328
- function seedNote(text) { if (els.seedStatus) els.seedStatus.textContent = text; }
329
-
330
- var mbText = ${mbText.toString()};
331
- var fetchWithProgress = ${fetchWithProgress.toString()};
332
- var seedFactsFromPayload = ${seedFactsFromPayload.toString()};
333
- var seedLoadingNote = ${seedLoadingNote.toString()};
334
- var fetchSeedPayloadWithRetry = ${fetchSeedPayloadWithRetry.toString()};
335
-
336
- // The desktop shell's readSeed() reads off local disk, not a CDN, so it
337
- // keeps its single attempt in loadSeed() below; only this fetch path retries.
338
- function fetchSeedPayload() {
339
- return fetchSeedPayloadWithRetry(fetchWithProgress, "./chat-seed.json", SEED_QUERY, function (loaded, total) {
340
- seedNote(seedLoadingNote(loaded, total));
341
- });
342
- }
343
-
344
- async function loadSeed() {
345
- try {
346
- var payload = null;
347
- if (window.tmctDesktop && typeof window.tmctDesktop.readSeed === "function") {
348
- seedNote("loading general knowledge…");
349
- var text = await window.tmctDesktop.readSeed();
350
- if (text) payload = JSON.parse(text);
351
- } else {
352
- payload = await fetchSeedPayload();
353
- }
354
- if (payload) {
355
- seedState.payload = payload;
356
- seedState.facts = seedFactsFromPayload(seedState.payload);
357
- seedState.status = "ready";
358
- seedNote("general knowledge: " + seedState.facts + " facts");
359
- renderFactTotal(DATA);
360
- return;
361
- }
362
- } catch (e) {
363
- console.warn("tmct code explorer: chat-seed unavailable, continuing graph-only", e);
364
- }
365
- seedState.status = "absent";
366
- seedNote("graph-only, general knowledge unavailable");
367
- }
368
- var seedPromise = api ? loadSeed() : Promise.resolve();
369
-
370
- function cloneSeed() {
371
- if (!seedState.payload) return null;
372
- try { return structuredClone(seedState.payload); } catch (e) { return JSON.parse(JSON.stringify(seedState.payload)); }
373
- }
374
-
375
- async function ensureSession() {
376
- if (session || !api || !api.createCodeExplorerSession) return session;
377
- if (api.registerWinkModel && window.__WINK_LOADER__) {
378
- try { var mod = await window.__WINK_LOADER__(); api.registerWinkModel(function () { return mod; }); }
379
- catch (e) { /* the lemma/POS tier is optional */ }
380
- }
381
- await seedPromise;
382
- session = api.createCodeExplorerSession({
383
- graphPayload: DATA.payload,
384
- seedPayload: cloneSeed(),
385
- vocabSeeded: seedState.status === "ready",
386
- });
387
- return session;
388
- }
389
-
390
- async function ask(q) {
391
- appendTurn("you", q);
392
- var s = await ensureSession();
393
- if (!s) { appendTurn("tmct", "the live chat is not loaded on this page."); return; }
394
- var res = await s.turn(q);
395
- appendTurn("tmct", res.answer);
396
- }
397
-
398
- // Delegate term + hint clicks.
399
- document.addEventListener("click", function (ev) {
400
- var t = ev.target.closest ? ev.target.closest("[data-term]") : null;
401
- if (t) { focusOn(t.getAttribute("data-term")); return; }
402
- var h = ev.target.closest ? ev.target.closest("[data-q]") : null;
403
- if (h) { els.input.value = h.getAttribute("data-q"); els.input.focus(); if (api) ask(h.getAttribute("data-q")); return; }
404
- });
405
-
406
- if (els.form) {
407
- els.form.addEventListener("submit", function (ev) {
408
- ev.preventDefault();
409
- var q = els.input.value.trim();
410
- if (!q) return;
411
- els.input.value = "";
412
- ask(q);
413
- });
414
- }
415
-
416
- // Desktop pickers, present only under the Electron shell. A swapped graph
417
- // starts a fresh session; the general-knowledge seed carries over.
418
- function wirePicker(id, method, updateSource) {
419
- var btn = document.getElementById(id);
420
- if (!btn) return;
421
- if (!window.tmctDesktop || typeof window.tmctDesktop[method] !== "function") { btn.disabled = true; return; }
422
- btn.addEventListener("click", async function () {
423
- btn.disabled = true;
424
- try {
425
- var picked = await window.tmctDesktop[method]();
426
- if (picked && picked.payload) {
427
- session = null;
428
- DATA = (api && api.computeCodeExplorerData)
429
- ? api.computeCodeExplorerData(picked.payload, { title: picked.name || "code graph" })
430
- : DATA;
431
- window.__CODE_EXPLORER__ = DATA;
432
- if (updateSource && els.source) els.source.textContent = picked.name || "(loaded graph)";
433
- els.log.innerHTML = "";
434
- renderEmptyState();
435
- mountView(DATA);
436
- }
437
- } finally { btn.disabled = false; }
438
- });
439
- }
440
- wirePicker("open-graph", "openGraph", true);
441
- wirePicker("open-repo", "openRepo", true);
442
-
443
- if (!api) {
444
- if (els.dockNote) els.dockNote.textContent = "static view, live chat unavailable here.";
445
- if (els.input) els.input.disabled = true;
446
- seedNote("static view");
447
- }
448
- renderEmptyState();
449
-
450
- mountView(DATA);
451
- })();
452
- `;
453
-
454
- /**
455
- * One self-contained HTML document: the full-viewport IDE shell over
456
- * computeCodeExplorerData's output. `bundleInline` inlines the chat engine
457
- * (for a single-file page / a data: URL); otherwise `bundleAvailable` links
458
- * `./code-explorer.bundle.js`. `winkLoaderInline` optionally inlines a wink
459
- * model loader as `window.__WINK_LOADER__`. `showDesktopLink` adds a line
460
- * pointing at the desktop app's README section — the desktop shell itself
461
- * renders this page too and passes `false`, since it has nothing to point at.
462
- */
463
- export function renderCodeExplorerHtml(data, { bundleInline = "", bundleAvailable = false, winkLoaderInline = "", sourceName = "demo code graph", showDesktopLink = false, seedStamp = "" } = {}) {
464
- const payloadJson = embedJson(data.payload);
465
- const dataJson = embedJson({ ledger: data.ledger, hints: data.hints, focus: data.focus, meta: data.meta });
466
-
467
- return `<!doctype html>
468
- <html lang="en">
469
- <head>
470
- <meta charset="utf-8">
471
- <meta name="viewport" content="width=device-width, initial-scale=1">
472
- <title>tmct code explorer</title>
473
- <link rel="icon" href="./favicon.svg" type="image/svg+xml">
474
- <link rel="icon" href="./favicon.ico" sizes="any">
475
- <link rel="apple-touch-icon" href="./apple-touch-icon.png">
476
- <style>
477
- ${THEME_TOKENS_CSS}
478
- * { box-sizing: border-box; }
479
- html, body { height: 100%; }
480
- body { margin: 0; overflow: hidden; background: var(--bg); color: var(--ink); font-family: ${SERIF_STACK}; }
481
- .shell { height: 100%; display: grid; grid-template-rows: auto minmax(0, 1fr) auto; }
482
-
483
- .titlebar { display: flex; align-items: center; gap: 0.7rem; flex-wrap: wrap; padding: 0.5rem 0.9rem; background: var(--card); border-bottom: 1px solid var(--line); box-shadow: inset 0 -2px 0 var(--entail-soft); }
484
- .titlebar .mark { width: 15px; height: 15px; color: var(--entail); flex: none; }
485
- .titlebar h1 { font-size: 0.95rem; margin: 0; font-weight: 600; letter-spacing: 0.02em; }
486
- ${EYEBROW_LINKS_CSS}
487
- .titlebar .sub { color: var(--muted); font-size: 0.76rem; font-family: ${MONO_STACK}; }
488
- .titlebar .sub a { color: var(--corpus); }
489
- /* the fact count sits in the titlebar, not the footer status bar: it is what
490
- the chat can actually answer from, and the footer is where a wrong number
491
- goes unread. */
492
- .titlebar .factpill { display: inline-flex; align-items: baseline; gap: 0.34rem; font-family: ${MONO_STACK}; font-size: 0.62rem; letter-spacing: 0.07em; text-transform: uppercase; color: var(--muted); border: 1px solid var(--entail); border-radius: 99px; padding: 0.14rem 0.7rem; background: var(--entail-soft); white-space: nowrap; }
493
- .titlebar .factpill-value { font-size: 0.9rem; letter-spacing: 0; font-variant-numeric: tabular-nums; font-weight: 600; color: var(--ink); }
494
- .titlebar .pickers { margin-left: auto; display: flex; gap: 0.45rem; }
495
- button { font: inherit; cursor: pointer; }
496
- button:disabled { cursor: default; opacity: 0.5; }
497
- button:focus-visible, input:focus-visible { outline: 2px solid var(--entail); outline-offset: 1px; }
498
- .pickers button { background: var(--bg); color: var(--ink); border: 1px solid var(--line); border-radius: 4px; padding: 0.3rem 0.65rem; font-size: 0.8rem; }
499
- .pickers button:hover { border-color: var(--entail); }
500
-
501
- .workbench { display: grid; grid-template-columns: minmax(230px, 320px) minmax(0, 1fr); min-height: 0; }
502
- .sidebar { display: flex; flex-direction: column; min-height: 0; border-right: 1px solid var(--line); }
503
- .panel { display: flex; flex-direction: column; min-height: 0; flex: 1; }
504
- .panel-head { margin: 0; padding: 0.45rem 0.9rem; flex: none; display: flex; align-items: baseline; gap: 0.45rem; font-family: ${MONO_STACK}; font-size: 0.66rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.09em; color: var(--muted); border-bottom: 1px solid var(--line); }
505
- .panel-body { flex: 1; min-height: 0; overflow-y: auto; padding: 0.5rem 0.9rem 1rem; }
506
- .focus-line { font-family: ${MONO_STACK}; font-size: 0.72rem; color: var(--corpus); text-transform: none; letter-spacing: 0; overflow-wrap: anywhere; }
507
- ul.rows { list-style: none; margin: 0; padding: 0; }
508
- .row { padding: 0.26rem 0.35rem; border-radius: 4px; font-size: 0.88rem; line-height: 1.45; }
509
- .row-focus { background: var(--corpus-soft); }
510
- .row.muted, .muted { color: var(--muted); }
511
- .term { background: none; border: none; padding: 0; color: var(--corpus); font-family: ${MONO_STACK}; font-size: 0.8rem; text-align: left; text-decoration: underline; text-decoration-color: var(--line); overflow-wrap: anywhere; }
512
- .term:hover { text-decoration-color: var(--corpus); }
513
- .verb { color: var(--muted); }
514
-
515
- .editor { display: flex; flex-direction: column; min-height: 0; background: var(--card); }
516
- #chat-log { flex: 1; min-height: 0; overflow-y: auto; padding: 0.9rem 1.1rem; display: flex; flex-direction: column; gap: 0.7rem; }
517
- .turn { max-width: 46rem; font-size: 0.95rem; line-height: 1.5; }
518
- .turn .who { display: block; font-family: ${MONO_STACK}; font-size: 0.62rem; text-transform: uppercase; letter-spacing: 0.07em; color: var(--muted); margin-bottom: 0.15rem; }
519
- .turn-you .said { font-family: ${MONO_STACK}; font-size: 0.84rem; }
520
- .turn-tmct { border-left: 2px solid var(--entail); padding-left: 0.7rem; }
521
- .turn-tmct .said { white-space: pre-wrap; }
522
- .chat-empty { margin: auto; max-width: 26rem; text-align: center; color: var(--muted); }
523
- .chat-empty-head { color: var(--ink); font-weight: 600; font-size: 1.05rem; margin: 0 0 0.5rem; }
524
- .chat-empty p { margin: 0.3rem 0; line-height: 1.55; font-size: 0.92rem; }
525
- .chat-empty-hint { font-size: 0.82rem; }
526
- .suggest { flex: none; border-top: 1px solid var(--line); padding: 0.65rem 1.1rem 0.4rem; }
527
- .suggest-label { font-family: ${MONO_STACK}; font-size: 0.66rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.09em; color: var(--muted); }
528
- .hints { display: flex; flex-wrap: wrap; gap: 0.4rem; max-height: 5.6rem; overflow-y: auto; padding: 0.45rem 0 0.55rem; }
529
- .hint { background: var(--bg); border: 1px solid var(--line); border-radius: 999px; padding: 0.24rem 0.7rem; font-size: 0.8rem; color: var(--ink); text-align: left; }
530
- .hint:hover { border-color: var(--entail); }
531
- #chat-form { flex: none; display: flex; gap: 0.5rem; padding: 0.75rem 1.1rem 0.9rem; border-top: 1px solid var(--line); }
532
- #chat-input { flex: 1; min-width: 0; font: inherit; font-size: 0.92rem; padding: 0.5rem 0.65rem; border: 1px solid var(--line); border-radius: 4px; background: var(--bg); color: var(--ink); }
533
- #chat-form button { background: var(--entail); color: var(--card); font-weight: 600; border: none; border-radius: 4px; padding: 0.5rem 1rem; font-size: 0.9rem; }
534
-
535
- .statusbar { display: flex; align-items: baseline; gap: 1rem; flex-wrap: wrap; padding: 0.32rem 0.9rem; font-family: ${MONO_STACK}; font-size: 0.7rem; color: var(--muted); background: var(--entail-soft); border-top: 1px solid var(--entail); }
536
- #seed-status { margin-left: auto; text-align: right; }
537
-
538
- @media (max-width: 760px) {
539
- .workbench { grid-template-columns: 1fr; grid-template-rows: minmax(0, 34%) minmax(0, 1fr); }
540
- .sidebar { border-right: none; border-bottom: 1px solid var(--line); }
541
- }
542
- </style>
543
- </head>
544
- <body>
545
- <div class="shell">
546
- <header class="titlebar">
547
- <svg class="mark" viewBox="0 0 16 16" aria-hidden="true"><path fill="currentColor" d="M8 0l1 2.3a5.8 5.8 0 0 1 1.9.8L13.3 2l.7.7-1.1 2.4c.4.6.6 1.2.8 1.9L16 8l-2.3 1a5.8 5.8 0 0 1-.8 1.9l1.1 2.4-.7.7-2.4-1.1a5.8 5.8 0 0 1-1.9.8L8 16l-1-2.3a5.8 5.8 0 0 1-1.9-.8L2.7 14l-.7-.7 1.1-2.4a5.8 5.8 0 0 1-.8-1.9L0 8l2.3-1c.2-.7.4-1.3.8-1.9L2 2.7l.7-.7 2.4 1.1A5.8 5.8 0 0 1 7 2.3L8 0zm0 5.2A2.8 2.8 0 1 0 8 10.8 2.8 2.8 0 0 0 8 5.2z"/></svg>
548
- <h1>${demoEyebrowHtml("code", "code explorer")}</h1>
549
- <span class="sub">source: <span id="source-name">${escapeHtml(sourceName)}</span></span>
550
- <span class="factpill" id="fact-total" aria-live="polite" title="every fact this page's chat can draw on — the code graph's own edges plus the general-knowledge seed once it lands">
551
- <span class="factpill-value" id="fact-total-value">&mdash;</span> facts loaded
552
- </span>
553
- ${showDesktopLink ? `<span class="sub">Also available as a <a href="${DESKTOP_APP_URL}">desktop app</a>.</span>` : ""}
554
- <div class="pickers">
555
- <button id="open-graph">Open graph…</button>
556
- <button id="open-repo">Open repo…</button>
557
- </div>
558
- </header>
559
- <div class="workbench">
560
- <aside class="sidebar">
561
- <section class="panel" data-panel="explorer">
562
- <h2 class="panel-head">Facts around <span class="focus-line" id="focus-name">—</span></h2>
563
- <div class="panel-body">
564
- <ul class="rows" id="ledger"></ul>
565
- </div>
566
- </section>
567
- </aside>
568
- <section class="editor" data-panel="conversation">
569
- <h2 class="panel-head">Conversation</h2>
570
- <div id="chat-log"></div>
571
- <div class="suggest">
572
- <span class="suggest-label">Try asking</span>
573
- <div class="hints" id="hints"></div>
574
- </div>
575
- <form id="chat-form">
576
- <input id="chat-input" type="text" autocomplete="off" placeholder="ask about this graph, or anything it knows…">
577
- <button type="submit">Ask</button>
578
- </form>
579
- </section>
580
- </div>
581
- <footer class="statusbar">
582
- <span id="stats"></span>
583
- <span id="dock-note"></span>
584
- <span id="seed-status"></span>
585
- </footer>
586
- </div>
587
- <script>window.__CODE_EXPLORER__ = Object.assign({ payload: ${payloadJson}, seedStamp: ${JSON.stringify(seedStamp)} }, ${dataJson});</script>
588
- ${winkLoaderInline ? `<script>\n${embedScriptText(winkLoaderInline)}\n</script>` : ""}
589
- ${bundleInline ? `<script>\n${embedScriptText(bundleInline)}\n</script>` : ""}
590
- ${bundleAvailable && !bundleInline ? `<script src="./code-explorer.bundle.js"></script>` : ""}
591
- <script>
592
- ${embedScriptText(CLIENT_JS)}
593
- </script>
594
- </body>
595
- </html>`;
596
- }
@@ -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
- });