@phren/cli 0.1.44 → 0.1.46

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.
Files changed (94) hide show
  1. package/dist/agents/providers/herdr.d.ts +18 -0
  2. package/dist/agents/providers/herdr.js +94 -0
  3. package/dist/agents/providers/spawner.d.ts +13 -0
  4. package/dist/agents/providers/spawner.js +63 -0
  5. package/dist/agents/registry.d.ts +28 -0
  6. package/dist/agents/registry.js +82 -0
  7. package/dist/agents/types.d.ts +51 -0
  8. package/dist/agents/types.js +42 -0
  9. package/dist/cli/actions.d.ts +1 -1
  10. package/dist/cli/actions.js +7 -2
  11. package/dist/cli/config-proactivity.d.ts +6 -6
  12. package/dist/cli/hooks.d.ts +1 -1
  13. package/dist/cli/hooks.js +14 -3
  14. package/dist/cli/search.js +29 -0
  15. package/dist/cli/session-stop.d.ts +1 -1
  16. package/dist/cli/session-tool-hook.d.ts +1 -1
  17. package/dist/cli-registry.d.ts +1 -1
  18. package/dist/cli-registry.js +2 -1
  19. package/dist/content/learning.js +24 -1
  20. package/dist/data/access.js +2 -1
  21. package/dist/generated/memory-ui-graph.browser.js +482 -319
  22. package/dist/governance/locks.js +6 -0
  23. package/dist/graph-core/index.d.ts +2 -0
  24. package/dist/graph-core/index.js +2 -0
  25. package/dist/graph-core/model.d.ts +84 -0
  26. package/dist/graph-core/model.js +445 -0
  27. package/dist/graph-core/types.d.ts +110 -0
  28. package/dist/graph-core/types.js +43 -0
  29. package/dist/index.js +4 -1
  30. package/dist/init/init-uninstall.d.ts +1 -0
  31. package/dist/init/init-uninstall.js +1 -1
  32. package/dist/init/setup.js +11 -4
  33. package/dist/link/context.js +2 -1
  34. package/dist/link/link.js +3 -2
  35. package/dist/link/skills.js +2 -1
  36. package/dist/memory-ui-graph.runtime.js +482 -319
  37. package/dist/phren-art.d.ts +7 -0
  38. package/dist/phren-art.js +6 -41
  39. package/dist/phren-core.d.ts +16 -0
  40. package/dist/phren-core.js +21 -0
  41. package/dist/phren-paths.js +8 -4
  42. package/dist/profile-store.js +3 -2
  43. package/dist/project-config.js +2 -1
  44. package/dist/shared/index.js +1 -1
  45. package/dist/shared/lookup-tail.d.ts +35 -0
  46. package/dist/shared/lookup-tail.js +100 -0
  47. package/dist/shared/retrieval.d.ts +28 -0
  48. package/dist/shared/retrieval.js +45 -0
  49. package/dist/shell/entry.d.ts +3 -3
  50. package/dist/shell/entry.js +19 -44
  51. package/dist/shell/graph/agents.d.ts +48 -0
  52. package/dist/shell/graph/agents.js +152 -0
  53. package/dist/shell/graph/canvas.d.ts +64 -0
  54. package/dist/shell/graph/canvas.js +256 -0
  55. package/dist/shell/graph/controller.d.ts +202 -0
  56. package/dist/shell/graph/controller.js +782 -0
  57. package/dist/shell/graph/glyphs.d.ts +12 -0
  58. package/dist/shell/graph/glyphs.js +31 -0
  59. package/dist/shell/graph/graph-view.d.ts +19 -0
  60. package/dist/shell/graph/graph-view.js +585 -0
  61. package/dist/shell/graph/layout.d.ts +87 -0
  62. package/dist/shell/graph/layout.js +335 -0
  63. package/dist/shell/graph/watch.d.ts +71 -0
  64. package/dist/shell/graph/watch.js +153 -0
  65. package/dist/shell/input.d.ts +3 -0
  66. package/dist/shell/input.js +26 -4
  67. package/dist/shell/intro.d.ts +37 -0
  68. package/dist/shell/intro.js +82 -0
  69. package/dist/shell/logo-fx.d.ts +35 -0
  70. package/dist/shell/logo-fx.js +128 -0
  71. package/dist/shell/render.d.ts +2 -2
  72. package/dist/shell/render.js +15 -28
  73. package/dist/shell/shell.d.ts +15 -1
  74. package/dist/shell/shell.js +50 -7
  75. package/dist/shell/startup.d.ts +40 -0
  76. package/dist/shell/startup.js +113 -0
  77. package/dist/shell/state-store.d.ts +1 -1
  78. package/dist/shell/state-store.js +1 -1
  79. package/dist/shell/types.js +1 -0
  80. package/dist/shell/view.d.ts +3 -0
  81. package/dist/shell/view.js +72 -63
  82. package/dist/store-registry.js +3 -3
  83. package/dist/test-global-setup.d.ts +1 -0
  84. package/dist/test-global-setup.js +22 -0
  85. package/dist/tool-registry.js +1 -0
  86. package/dist/ui/data.d.ts +15 -7
  87. package/dist/ui/data.js +102 -3
  88. package/dist/ui/server.js +6 -56
  89. package/dist/utils-fts.js +2 -1
  90. package/dist/utils-helpers.d.ts +1 -0
  91. package/dist/utils-helpers.js +6 -0
  92. package/dist/utils.d.ts +1 -1
  93. package/dist/utils.js +1 -1
  94. package/package.json +11 -7
@@ -0,0 +1,782 @@
1
+ /**
2
+ * State + interaction for the terminal graph view.
3
+ *
4
+ * The controller is the terminal-side analogue of the browser's
5
+ * `browser/graph/state.ts` + `interactions.ts`: it owns the payload built by
6
+ * `buildGraph`, the normalized model from `graph-core`, the force layout, a 2D
7
+ * camera, selection/search/focus, and the key map. Rendering lives in
8
+ * `graph-view.ts`; this module never writes to the terminal.
9
+ */
10
+ import { computePhrenLiveStateToken } from "../../phren-paths.js";
11
+ import { buildGraph } from "../../ui/data.js";
12
+ import { StoreColorAssigner, bestSearchMatch, buildFullAdjacency, buildVisibleData, nodeDetail, nodeRank, normalizeNode, recomputeSearchMatches, } from "../../graph-core/model.js";
13
+ import { errorMessage } from "../../utils.js";
14
+ import { logger } from "../../logger.js";
15
+ import { style } from "../render.js";
16
+ import { ForceSim, bounds } from "./layout.js";
17
+ import { GraphWatch } from "./watch.js";
18
+ import { GraphAgents } from "./agents.js";
19
+ /** Nodes drawn at once. Terminals have far fewer pixels than a browser tab. */
20
+ export const TUI_NODE_LIMIT = 350;
21
+ const ALL_TYPES = { project: true, finding: true, task: true, entity: true, reference: true };
22
+ export const FILTER_PRESETS = [
23
+ { name: "all", types: ALL_TYPES, health: "all" },
24
+ { name: "findings", types: { project: true, finding: true }, health: "all" },
25
+ { name: "tasks", types: { project: true, task: true }, health: "all" },
26
+ { name: "fragments", types: { project: true, entity: true, reference: true }, health: "all" },
27
+ { name: "aging", types: ALL_TYPES, health: "aging" },
28
+ ];
29
+ /** How far the x and y scales may diverge when filling the canvas. */
30
+ const MAX_STRETCH = 2.2;
31
+ const DIRECTIONS = {
32
+ up: { x: 0, y: -1 },
33
+ down: { x: 0, y: 1 },
34
+ left: { x: -1, y: 0 },
35
+ right: { x: 1, y: 0 },
36
+ };
37
+ function normalizeArrow(rawKey) {
38
+ return /^\x1bO[A-D]$/.test(rawKey) ? `\x1b[${rawKey[2]}` : rawKey;
39
+ }
40
+ const ARROW_DIRECTION = {
41
+ "\x1b[A": "up",
42
+ "\x1b[B": "down",
43
+ "\x1b[D": "left",
44
+ "\x1b[C": "right",
45
+ };
46
+ /** Shift+arrow in the CSI 1;2 form most terminals emit. */
47
+ const SHIFT_ARROW_DIRECTION = {
48
+ "\x1b[1;2A": "up",
49
+ "\x1b[1;2B": "down",
50
+ "\x1b[1;2D": "left",
51
+ "\x1b[1;2C": "right",
52
+ };
53
+ const PAN_LETTER_DIRECTION = { K: "up", J: "down", H: "left", L: "right" };
54
+ export class GraphController {
55
+ phrenPath;
56
+ profile;
57
+ status = "idle";
58
+ errorText = "";
59
+ /** A rebuild is running while the previous picture stays on screen. */
60
+ get refreshing() { return this.building !== null && this.payload !== null; }
61
+ payload = null;
62
+ model = { rawNodes: [], rawLinks: [], nodeById: new Map(), fullAdjacency: new Map(), visibleAdjacency: new Map(), scores: {} };
63
+ filters = {
64
+ filterTypes: { ...ALL_TYPES },
65
+ filterTopics: {},
66
+ filterHealth: "all",
67
+ filterProject: "all",
68
+ filterStore: "all",
69
+ searchQuery: "",
70
+ nodeLimit: TUI_NODE_LIMIT,
71
+ };
72
+ visible = { nodes: [], links: [], visibleAdjacency: new Map() };
73
+ /** Project nodes in display order for `[`/`]`. */
74
+ projects = [];
75
+ presetIndex = 0;
76
+ selectedId = null;
77
+ search = { query: "", matchIds: new Set(), results: [], index: -1 };
78
+ camera = { cx: 0, cy: 0, scaleX: 2, scaleY: 2 };
79
+ sim = null;
80
+ lastPositions = new Map();
81
+ viewport = { width: 160, height: 80 };
82
+ dataToken = "";
83
+ building = null;
84
+ repaintHook = null;
85
+ timer = null;
86
+ cameraTarget = null;
87
+ /** Re-frame once the intro settle finishes so the whole map is in view. */
88
+ fitOnSettle = false;
89
+ /** Set by pan/zoom; until then a resize re-fits the whole map. */
90
+ userMoved = false;
91
+ builder;
92
+ tokenOf;
93
+ frameMs;
94
+ /** Live tail of what phren is landing on, in this or any other terminal. */
95
+ watch;
96
+ /** Coding agents running on this machine, joined onto their projects. */
97
+ agents;
98
+ watchEnabled;
99
+ /**
100
+ * Wall-clock ms of the last navigation keypress. While the user is driving,
101
+ * incoming events still pulse and feed but do not steal the camera.
102
+ */
103
+ lastUserInputAt = 0;
104
+ constructor(phrenPath, profile, opts = {}) {
105
+ this.phrenPath = phrenPath;
106
+ this.profile = profile;
107
+ this.builder = opts.builder ?? ((p, prof) => buildGraph(p, prof, undefined, null, { includeFragmentEdges: true, includeLifecycleEdges: true }));
108
+ this.tokenOf = opts.tokenOf ?? computePhrenLiveStateToken;
109
+ this.frameMs = opts.frameMs ?? 50;
110
+ this.watch = opts.watch ?? new GraphWatch(phrenPath);
111
+ this.watchEnabled = opts.watchEnabled !== false;
112
+ this.agents = opts.agents ?? new GraphAgents(phrenPath, profile);
113
+ }
114
+ // ── Watch mode ──────────────────────────────────────────────────────────
115
+ /** Idempotent; called every render so the tail starts with the view. */
116
+ startWatch() {
117
+ if (!this.watchEnabled || this.watch.running)
118
+ return;
119
+ this.watch.start((items) => this.onWatchEvents(items));
120
+ }
121
+ stopWatch() {
122
+ this.watch.stop();
123
+ }
124
+ // ── Agents ──────────────────────────────────────────────────────────────
125
+ /** Idempotent; the poller only runs while the Graph view is open. */
126
+ startAgents() {
127
+ if (!this.agents.enabled || this.agents.running)
128
+ return;
129
+ this.agents.start(() => this.repaintHook?.());
130
+ }
131
+ toggleAgents() {
132
+ if (this.agents.enabled) {
133
+ this.agents.toggle();
134
+ return false;
135
+ }
136
+ this.agents.enabled = true;
137
+ this.agents.start(() => this.repaintHook?.());
138
+ return true;
139
+ }
140
+ toggleWatch() {
141
+ this.watchEnabled = !this.watchEnabled;
142
+ if (this.watchEnabled)
143
+ this.startWatch();
144
+ else
145
+ this.stopWatch();
146
+ return this.watchEnabled;
147
+ }
148
+ /** True while the user is actively driving, so the camera is left alone. */
149
+ get userDriving() {
150
+ return Date.now() - this.lastUserInputAt < 4000;
151
+ }
152
+ /**
153
+ * New events landed. Light every node they touch, then follow the newest
154
+ * one that is actually on screen — unless the user is mid-navigation.
155
+ */
156
+ onWatchEvents(items) {
157
+ let followed = false;
158
+ for (let i = items.length - 1; i >= 0 && !followed; i--) {
159
+ const nodeId = items[i].nodeId;
160
+ if (!nodeId || !this.model.nodeById.has(nodeId))
161
+ continue;
162
+ if (!this.userDriving) {
163
+ this.selectedId = nodeId;
164
+ this.flyTo(nodeId);
165
+ }
166
+ followed = true;
167
+ }
168
+ // Heat decays over several seconds, so keep painting even without a fly.
169
+ this.startAnimation();
170
+ this.repaintHook?.();
171
+ }
172
+ // ── Data ────────────────────────────────────────────────────────────────
173
+ /**
174
+ * Let the shell trigger a repaint on its own (settle animation, fly-to,
175
+ * a build finishing). Without it the controller blocks the first render on
176
+ * the build and snaps every camera move.
177
+ */
178
+ setRepaintHook(hook) {
179
+ this.repaintHook = hook;
180
+ }
181
+ get positions() {
182
+ return this.sim ? this.sim.positions : this.lastPositions;
183
+ }
184
+ lastToken = "";
185
+ lastTokenAt = 0;
186
+ /** The store token, re-read at most every 2s: animation repaints must not stat the whole store. */
187
+ currentToken() {
188
+ const now = Date.now();
189
+ if (now - this.lastTokenAt < 2000 && this.lastToken)
190
+ return this.lastToken;
191
+ try {
192
+ this.lastToken = this.tokenOf(this.phrenPath);
193
+ }
194
+ catch {
195
+ this.lastToken = `err:${now}`;
196
+ }
197
+ this.lastTokenAt = now;
198
+ return this.lastToken;
199
+ }
200
+ /**
201
+ * Make sure a payload matching the store is loaded, or on its way. Blocks
202
+ * only on the very first build when there is no repaint hook to come back
203
+ * through; otherwise the old picture stays up with a refreshing badge.
204
+ */
205
+ async ensureData() {
206
+ this.startWatch();
207
+ this.startAgents();
208
+ const token = this.currentToken();
209
+ if (this.payload && token === this.dataToken)
210
+ return;
211
+ if (!this.building) {
212
+ if (!this.payload)
213
+ this.status = "loading";
214
+ this.building = this.build(token).finally(() => { this.building = null; });
215
+ }
216
+ if (!this.payload && !this.repaintHook)
217
+ await this.building;
218
+ }
219
+ async build(token) {
220
+ try {
221
+ const payload = await this.builder(this.phrenPath, this.profile);
222
+ this.dataToken = token;
223
+ this.adopt(payload);
224
+ }
225
+ catch (err) {
226
+ this.errorText = errorMessage(err);
227
+ this.status = "error";
228
+ logger.debug("shell", `graph build failed: ${this.errorText}`);
229
+ }
230
+ finally {
231
+ this.repaintHook?.();
232
+ }
233
+ }
234
+ /** Load a payload directly (tests, or a host that already has one). */
235
+ adopt(payload) {
236
+ this.payload = payload;
237
+ const scores = payload.scores ?? {};
238
+ const storeColors = new StoreColorAssigner();
239
+ const rawNodes = (payload.nodes ?? []).map((node) => normalizeNode(node, scores, (s) => storeColors.color(s)));
240
+ const rawLinks = payload.links ?? [];
241
+ this.model = {
242
+ rawNodes,
243
+ rawLinks,
244
+ nodeById: new Map(rawNodes.map((node) => [node.id, node])),
245
+ fullAdjacency: buildFullAdjacency(rawNodes, rawLinks),
246
+ visibleAdjacency: new Map(),
247
+ scores,
248
+ };
249
+ this.projects = rawNodes.filter((node) => node.kind === "project").sort((a, b) => a.label.localeCompare(b.label));
250
+ if (this.filters.filterProject !== "all" && !this.projects.some((p) => (p.project || p.id) === this.filters.filterProject)) {
251
+ this.filters.filterProject = "all";
252
+ }
253
+ if (this.selectedId && !this.model.nodeById.has(this.selectedId))
254
+ this.selectedId = null;
255
+ this.status = rawNodes.length ? "ready" : "empty";
256
+ this.applyFilters(true);
257
+ }
258
+ // ── Filters / layout ────────────────────────────────────────────────────
259
+ get preset() {
260
+ return FILTER_PRESETS[this.presetIndex] ?? FILTER_PRESETS[0];
261
+ }
262
+ get focusedProject() {
263
+ return this.filters.filterProject === "all" ? null : this.filters.filterProject;
264
+ }
265
+ applyFilters(warm) {
266
+ this.visible = buildVisibleData(this.model, this.filters, this.selectedId);
267
+ this.model.visibleAdjacency = this.visible.visibleAdjacency;
268
+ const visibleIds = new Set(this.visible.nodes.map((node) => node.id));
269
+ if (this.selectedId && !visibleIds.has(this.selectedId))
270
+ this.selectedId = null;
271
+ this.rebuildLayout(warm);
272
+ this.refreshSearch();
273
+ }
274
+ rebuildLayout(warm) {
275
+ if (this.sim)
276
+ this.lastPositions = new Map([...this.sim.positions].map(([id, p]) => [id, { ...p }]));
277
+ const nodes = this.visible.nodes.map((node) => ({ id: node.id, kind: node.kind, project: node.project, size: node.size }));
278
+ const links = this.visible.links;
279
+ // The layout is shaped to the canvas so it fills a wide terminal.
280
+ this.sim = new ForceSim(nodes, links, undefined, this.viewport.width / Math.max(1, this.viewport.height));
281
+ if (warm && this.lastPositions.size)
282
+ this.sim.warmStart(this.lastPositions);
283
+ const fresh = !warm || !this.lastPositions.size;
284
+ if (this.repaintHook) {
285
+ this.sim.tick(warm ? 12 : 40);
286
+ if (fresh) {
287
+ this.fitAll();
288
+ this.fitOnSettle = true;
289
+ }
290
+ this.startAnimation();
291
+ }
292
+ else {
293
+ this.sim.settle();
294
+ if (fresh)
295
+ this.fitAll();
296
+ }
297
+ }
298
+ /**
299
+ * The view reports its canvas size (in dots) before projecting. The first
300
+ * fit happens before any frame is drawn, so a size change re-fits unless
301
+ * the user has taken the camera over.
302
+ */
303
+ setViewport(width, height) {
304
+ if (width === this.viewport.width && height === this.viewport.height)
305
+ return;
306
+ this.viewport = { width: Math.max(2, width), height: Math.max(4, height) };
307
+ if (!this.userMoved) {
308
+ const keepFlag = this.fitOnSettle;
309
+ this.fitAll();
310
+ this.fitOnSettle = keepFlag;
311
+ }
312
+ else if (this.selectedId)
313
+ this.keepInView(this.selectedId);
314
+ }
315
+ get viewportSize() {
316
+ return this.viewport;
317
+ }
318
+ /** World → dot coordinates for the current camera. */
319
+ project(p) {
320
+ return {
321
+ x: (p.x - this.camera.cx) * this.camera.scaleX + this.viewport.width / 2,
322
+ y: (p.y - this.camera.cy) * this.camera.scaleY + this.viewport.height / 2,
323
+ };
324
+ }
325
+ fitAll() {
326
+ const box = bounds(this.positions.values());
327
+ this.cameraTarget = null;
328
+ this.fitOnSettle = false;
329
+ this.userMoved = false;
330
+ if (!box) {
331
+ this.camera = { cx: 0, cy: 0, scaleX: 2, scaleY: 2 };
332
+ return;
333
+ }
334
+ const w = Math.max(1, box.maxX - box.minX);
335
+ const h = Math.max(1, box.maxY - box.minY);
336
+ const pad = 0.92;
337
+ let sx = (this.viewport.width * pad) / w;
338
+ let sy = (this.viewport.height * pad) / h;
339
+ // Fill both axes rather than letting the shorter one strand the rest of
340
+ // the screen, but pull the looser axis back in once it would distort.
341
+ if (sx > sy * MAX_STRETCH)
342
+ sx = sy * MAX_STRETCH;
343
+ else if (sy > sx * MAX_STRETCH)
344
+ sy = sx * MAX_STRETCH;
345
+ const clamp01 = (v) => Math.max(0.2, Math.min(v, 12));
346
+ this.camera = {
347
+ cx: (box.minX + box.maxX) / 2,
348
+ cy: (box.minY + box.maxY) / 2,
349
+ scaleX: clamp01(sx),
350
+ scaleY: clamp01(sy),
351
+ };
352
+ }
353
+ zoom(factor) {
354
+ this.userMoved = true;
355
+ // Both axes move together, so a zoom never changes the shape on screen.
356
+ const clampZoom = (v) => Math.max(0.2, Math.min(24, v));
357
+ this.camera.scaleX = clampZoom(this.camera.scaleX * factor);
358
+ this.camera.scaleY = clampZoom(this.camera.scaleY * factor);
359
+ }
360
+ pan(direction) {
361
+ const d = DIRECTIONS[direction];
362
+ const stepX = (this.viewport.width * 0.12) / this.camera.scaleX;
363
+ const stepY = (this.viewport.height * 0.12) / this.camera.scaleY;
364
+ this.userMoved = true;
365
+ this.cameraTarget = null;
366
+ this.camera.cx += d.x * stepX;
367
+ this.camera.cy += d.y * stepY;
368
+ }
369
+ /** Centre the camera on a node, eased when animation is available. */
370
+ flyTo(nodeId) {
371
+ const p = this.positions.get(nodeId);
372
+ if (!p)
373
+ return;
374
+ if (this.repaintHook) {
375
+ this.cameraTarget = { x: p.x, y: p.y };
376
+ this.startAnimation();
377
+ }
378
+ else {
379
+ this.camera.cx = p.x;
380
+ this.camera.cy = p.y;
381
+ }
382
+ }
383
+ /** Fly only when the node sits outside the middle band of the viewport. */
384
+ keepInView(nodeId) {
385
+ const p = this.positions.get(nodeId);
386
+ if (!p)
387
+ return;
388
+ const d = this.project(p);
389
+ const { width, height } = this.viewport;
390
+ if (d.x < width * 0.18 || d.x > width * 0.82 || d.y < height * 0.18 || d.y > height * 0.82)
391
+ this.flyTo(nodeId);
392
+ }
393
+ relayout() {
394
+ this.lastPositions = new Map();
395
+ this.cameraTarget = null;
396
+ this.rebuildLayout(false);
397
+ this.fitAll();
398
+ }
399
+ // ── Animation ───────────────────────────────────────────────────────────
400
+ startAnimation() {
401
+ if (this.timer || !this.repaintHook)
402
+ return;
403
+ this.timer = setInterval(() => this.animationFrame(), this.frameMs);
404
+ this.timer.unref?.();
405
+ }
406
+ stopAnimation() {
407
+ if (this.timer) {
408
+ clearInterval(this.timer);
409
+ this.timer = null;
410
+ }
411
+ }
412
+ get animating() {
413
+ return this.timer !== null;
414
+ }
415
+ animationFrame() {
416
+ let busy = this.watch.hot;
417
+ if (this.sim && !this.sim.settled) {
418
+ this.sim.tick(3);
419
+ busy = true;
420
+ if (this.sim.settled && this.fitOnSettle && !this.cameraTarget) {
421
+ this.fitAll();
422
+ this.fitOnSettle = false;
423
+ }
424
+ }
425
+ if (this.cameraTarget) {
426
+ const t = this.cameraTarget;
427
+ this.camera.cx += (t.x - this.camera.cx) * 0.35;
428
+ this.camera.cy += (t.y - this.camera.cy) * 0.35;
429
+ if (Math.abs(t.x - this.camera.cx) < 0.05 && Math.abs(t.y - this.camera.cy) < 0.05) {
430
+ this.camera.cx = t.x;
431
+ this.camera.cy = t.y;
432
+ this.cameraTarget = null;
433
+ }
434
+ else {
435
+ busy = true;
436
+ }
437
+ }
438
+ if (!busy)
439
+ this.stopAnimation();
440
+ this.repaintHook?.();
441
+ }
442
+ /** Called by the shell when the view changes away or the shell closes. */
443
+ dispose() {
444
+ this.stopAnimation();
445
+ this.stopWatch();
446
+ this.agents.stop();
447
+ }
448
+ // ── Selection / search / focus ──────────────────────────────────────────
449
+ detail(nodeId) {
450
+ return nodeDetail(this.model, nodeId);
451
+ }
452
+ /** Visible neighbours of a node, best first — what the pane numbers 1-9. */
453
+ neighborsOf(nodeId) {
454
+ const ids = this.model.visibleAdjacency.get(nodeId);
455
+ if (!ids)
456
+ return [];
457
+ const nodes = [];
458
+ ids.forEach((id) => { const node = this.model.nodeById.get(id); if (node)
459
+ nodes.push(node); });
460
+ return nodes.sort((a, b) => nodeRank(b, this.filters, this.model.scores) - nodeRank(a, this.filters, this.model.scores));
461
+ }
462
+ select(nodeId, opts = {}) {
463
+ this.selectedId = nodeId;
464
+ if (nodeId) {
465
+ if (opts.fly)
466
+ this.flyTo(nodeId);
467
+ else
468
+ this.keepInView(nodeId);
469
+ }
470
+ }
471
+ nearestToCenter() {
472
+ let best = null;
473
+ let bestDist = Infinity;
474
+ const center = { x: this.viewport.width / 2, y: this.viewport.height / 2 };
475
+ for (const node of this.visible.nodes) {
476
+ const p = this.positions.get(node.id);
477
+ if (!p)
478
+ continue;
479
+ const d = this.project(p);
480
+ const dist = (d.x - center.x) ** 2 + (d.y - center.y) ** 2;
481
+ if (dist < bestDist) {
482
+ bestDist = dist;
483
+ best = node;
484
+ }
485
+ }
486
+ return best;
487
+ }
488
+ /**
489
+ * Arrow-key traversal: prefer a connected neighbour in that direction; if
490
+ * there is none, take the nearest visible node in that half-plane so the
491
+ * walk never dead-ends on a leaf.
492
+ */
493
+ walk(direction) {
494
+ if (!this.selectedId) {
495
+ const start = this.nearestToCenter();
496
+ if (start)
497
+ this.select(start.id);
498
+ return start;
499
+ }
500
+ const from = this.positions.get(this.selectedId);
501
+ if (!from)
502
+ return null;
503
+ const dir = DIRECTIONS[direction];
504
+ const pick = (candidates, minCos) => {
505
+ let best = null;
506
+ for (const id of candidates) {
507
+ if (id === this.selectedId)
508
+ continue;
509
+ const p = this.positions.get(id);
510
+ if (!p)
511
+ continue;
512
+ const dx = p.x - from.x;
513
+ const dy = p.y - from.y;
514
+ const len = Math.sqrt(dx * dx + dy * dy);
515
+ if (len === 0)
516
+ continue;
517
+ const cos = (dx * dir.x + dy * dir.y) / len;
518
+ if (cos <= minCos)
519
+ continue;
520
+ const score = len / Math.max(cos, 0.15);
521
+ if (!best || score < best.score)
522
+ best = { id, score };
523
+ }
524
+ return best;
525
+ };
526
+ const neighbors = this.model.visibleAdjacency.get(this.selectedId) ?? new Set();
527
+ const target = pick(neighbors, 0.1) ?? pick(this.visible.nodes.map((node) => node.id), 0.3);
528
+ if (!target)
529
+ return null;
530
+ this.select(target.id);
531
+ return this.model.nodeById.get(target.id) ?? null;
532
+ }
533
+ refreshSearch() {
534
+ const matches = recomputeSearchMatches(this.visible.nodes, this.search.query, this.filters, this.model.scores);
535
+ this.search.matchIds = matches.matchIds;
536
+ this.search.results = matches.results;
537
+ if (this.search.index >= matches.results.length)
538
+ this.search.index = matches.results.length ? 0 : -1;
539
+ }
540
+ /** Set the query, light up matches, and fly to the best one. */
541
+ applySearch(query) {
542
+ this.search.query = query.trim();
543
+ this.filters.searchQuery = this.search.query;
544
+ this.refreshSearch();
545
+ if (!this.search.query) {
546
+ this.search.index = -1;
547
+ return null;
548
+ }
549
+ const best = bestSearchMatch(this.search.results);
550
+ this.search.index = best ? 0 : -1;
551
+ if (best)
552
+ this.select(best.id, { fly: true });
553
+ return best;
554
+ }
555
+ clearSearch() {
556
+ this.applySearch("");
557
+ }
558
+ stepSearch(delta) {
559
+ const results = this.search.results;
560
+ if (!results.length)
561
+ return null;
562
+ this.search.index = ((this.search.index + delta) % results.length + results.length) % results.length;
563
+ const node = results[this.search.index];
564
+ this.select(node.id, { fly: true });
565
+ return node;
566
+ }
567
+ cyclePreset(delta = 1) {
568
+ this.presetIndex = ((this.presetIndex + delta) % FILTER_PRESETS.length + FILTER_PRESETS.length) % FILTER_PRESETS.length;
569
+ const preset = this.preset;
570
+ this.filters.filterTypes = { ...preset.types };
571
+ this.filters.filterHealth = preset.health;
572
+ this.applyFilters(true);
573
+ return preset;
574
+ }
575
+ /** Focus one project (name) or all (null). */
576
+ focusProject(name) {
577
+ this.filters.filterProject = name ?? "all";
578
+ this.applyFilters(true);
579
+ // Either way the visible set just changed shape: frame it, then keep the
580
+ // project selected so its neighbours are numbered.
581
+ this.cameraTarget = null;
582
+ this.fitAll();
583
+ if (name) {
584
+ const node = this.projects.find((p) => (p.project || p.id) === name);
585
+ if (node)
586
+ this.selectedId = node.id;
587
+ }
588
+ }
589
+ cycleProject(delta) {
590
+ if (!this.projects.length)
591
+ return null;
592
+ const names = this.projects.map((p) => p.project || p.id);
593
+ const current = this.focusedProject ? names.indexOf(this.focusedProject) : -1;
594
+ // Slot -1 is "all projects"; the cycle runs all → first … last → all.
595
+ const slots = names.length + 1;
596
+ const next = (((current + 1 + delta) % slots) + slots) % slots - 1;
597
+ const name = next < 0 ? null : names[next];
598
+ this.focusProject(name);
599
+ return name;
600
+ }
601
+ jumpToNeighbor(n) {
602
+ if (!this.selectedId)
603
+ return null;
604
+ const node = this.neighborsOf(this.selectedId)[n - 1];
605
+ if (!node)
606
+ return null;
607
+ this.select(node.id);
608
+ return node;
609
+ }
610
+ // ── Keys ────────────────────────────────────────────────────────────────
611
+ /**
612
+ * Returns true when the key was consumed, undefined to let the shell's
613
+ * generic handler have it (q, :, ?, view shortcuts, final Esc).
614
+ */
615
+ handleKey(rawKey, host) {
616
+ const key = normalizeArrow(rawKey);
617
+ if (key !== "w" && key !== "W")
618
+ this.lastUserInputAt = Date.now();
619
+ if (this.status !== "ready") {
620
+ if (key === "r") {
621
+ this.dataToken = "";
622
+ host.setMessage(" Rebuilding graph…");
623
+ return true;
624
+ }
625
+ return undefined;
626
+ }
627
+ const arrow = ARROW_DIRECTION[key];
628
+ if (arrow) {
629
+ const node = this.walk(arrow);
630
+ host.setMessage(node ? this.describe(node) : ` ${style.dim("nothing further that way")}`);
631
+ return true;
632
+ }
633
+ const shifted = SHIFT_ARROW_DIRECTION[key] ?? PAN_LETTER_DIRECTION[key];
634
+ if (shifted) {
635
+ this.pan(shifted);
636
+ return true;
637
+ }
638
+ if (key === "+" || key === "=") {
639
+ this.zoom(1.25);
640
+ return true;
641
+ }
642
+ if (key === "-" || key === "_") {
643
+ this.zoom(1 / 1.25);
644
+ return true;
645
+ }
646
+ if (key === "0") {
647
+ this.fitAll();
648
+ host.setMessage(` ${style.dim("fit to screen")}`);
649
+ return true;
650
+ }
651
+ if (key === "r") {
652
+ this.relayout();
653
+ host.setMessage(` ${style.dim("re-laid out")}`);
654
+ return true;
655
+ }
656
+ if (key === "\r" || key === "\n") {
657
+ // A highlighted agent takes the Enter: bring it to the front.
658
+ const highlighted = this.agents.current;
659
+ if (highlighted) {
660
+ const focused = this.agents.focusCurrent();
661
+ host.setMessage(focused
662
+ ? ` ${style.boldCyan("→")} ${focused.label}`
663
+ : ` ${style.dim(highlighted.focus?.length ? "could not focus that agent" : "this agent's host cannot be focused")}`);
664
+ return true;
665
+ }
666
+ if (!this.selectedId) {
667
+ const node = this.nearestToCenter();
668
+ if (node) {
669
+ this.select(node.id);
670
+ host.setMessage(this.describe(node));
671
+ }
672
+ return true;
673
+ }
674
+ const node = this.model.nodeById.get(this.selectedId);
675
+ if (node?.kind === "project") {
676
+ const name = node.project || node.id;
677
+ const next = this.focusedProject === name ? null : name;
678
+ this.focusProject(next);
679
+ host.setMessage(next ? ` ${style.boldCyan("❖")} ${style.boldCyan(next)} ${style.dim("focused — ↵ again to release")}` : ` ${style.dim("all projects")}`);
680
+ }
681
+ else if (node) {
682
+ this.flyTo(node.id);
683
+ host.setMessage(this.describe(node));
684
+ }
685
+ return true;
686
+ }
687
+ if (/^[1-9]$/.test(key)) {
688
+ const node = this.jumpToNeighbor(Number(key));
689
+ if (node)
690
+ host.setMessage(this.describe(node));
691
+ else
692
+ host.setMessage(` ${style.dim(this.selectedId ? "no such neighbour" : "select a node first (↵)")}`);
693
+ return true;
694
+ }
695
+ if (key === "/") {
696
+ host.startInput("graph-search", this.search.query);
697
+ return true;
698
+ }
699
+ if (key === "n" || key === "N") {
700
+ const node = this.stepSearch(key === "n" ? 1 : -1);
701
+ host.setMessage(node
702
+ ? ` ${style.yellow(`${this.search.index + 1}/${this.search.results.length}`)} ${this.describe(node).trimStart()}`
703
+ : ` ${style.dim("no search — press / first")}`);
704
+ return true;
705
+ }
706
+ if (key === "f") {
707
+ const preset = this.cyclePreset(1);
708
+ host.setMessage(` ${style.boldCyan("filter")} ${preset.name} ${style.dim(`${this.visible.nodes.length} nodes`)}`);
709
+ return true;
710
+ }
711
+ if (key === "F") {
712
+ const preset = this.cyclePreset(-1);
713
+ host.setMessage(` ${style.boldCyan("filter")} ${preset.name} ${style.dim(`${this.visible.nodes.length} nodes`)}`);
714
+ return true;
715
+ }
716
+ if (key === "]" || key === "[") {
717
+ const name = this.cycleProject(key === "]" ? 1 : -1);
718
+ host.setMessage(name ? ` ${style.boldCyan("❖")} ${style.boldCyan(name)}` : ` ${style.dim("all projects")}`);
719
+ return true;
720
+ }
721
+ if (key === "a" || key === "A") {
722
+ const on = this.toggleAgents();
723
+ host.setMessage(on
724
+ ? ` ${style.boldCyan("◉ agents")} ${style.dim(`— ${this.agents.agents.length} running · tab to cycle, ↵ to focus`)}`
725
+ : ` ${style.dim("agents off")}`);
726
+ return true;
727
+ }
728
+ if (key === "\t" || key === "\x1b[Z") {
729
+ if (!this.agents.enabled || !this.agents.agents.length)
730
+ return undefined;
731
+ const agent = this.agents.cycle(key === "\t" ? 1 : -1);
732
+ if (agent) {
733
+ if (agent.project && this.model.nodeById.has(agent.project))
734
+ this.select(agent.project, { fly: true });
735
+ host.setMessage(` ${style.boldCyan(agent.label)} ${style.dim(`${agent.status}${agent.project ? ` · ${agent.project}` : " · outside phren"}`)}`);
736
+ }
737
+ return true;
738
+ }
739
+ if (key === "w" || key === "W") {
740
+ const on = this.toggleWatch();
741
+ host.setMessage(on
742
+ ? ` ${style.boldCyan("◉ watching")} ${style.dim("— lighting up what phren touches, anywhere on this machine")}`
743
+ : ` ${style.dim("watch off")}`);
744
+ return true;
745
+ }
746
+ if (key === "o") {
747
+ host.setMessage(` ${style.dim("open the 3D viewer in a browser:")} ${style.boldCyan("phren web-ui")}`);
748
+ return true;
749
+ }
750
+ if (key === "\x1b") {
751
+ if (this.agents.current) {
752
+ this.agents.clearHighlight();
753
+ host.setMessage(` ${style.dim("agent released")}`);
754
+ return true;
755
+ }
756
+ if (this.search.query) {
757
+ this.clearSearch();
758
+ host.setMessage(` ${style.dim("search cleared")}`);
759
+ return true;
760
+ }
761
+ if (this.selectedId) {
762
+ this.select(null);
763
+ host.setMessage(` ${style.dim("selection cleared")}`);
764
+ return true;
765
+ }
766
+ if (this.focusedProject) {
767
+ this.focusProject(null);
768
+ host.setMessage(` ${style.dim("all projects")}`);
769
+ return true;
770
+ }
771
+ return undefined;
772
+ }
773
+ return undefined;
774
+ }
775
+ /** One-line description for the message bar. */
776
+ describe(node) {
777
+ const label = node.fullLabel || node.label;
778
+ const short = label.length > 70 ? `${label.slice(0, 68)}…` : label;
779
+ const where = node.project && node.kind !== "project" ? ` ${style.dim("·")} ${style.cyan(node.project)}` : "";
780
+ return ` ${style.dim(node.kind)} ${short}${where}`;
781
+ }
782
+ }