@phren/cli 0.1.49 → 0.1.51

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.
@@ -3,6 +3,7 @@
3
3
  * Extracted from shell.ts to keep the orchestrator under 300 lines.
4
4
  */
5
5
  import { PhrenShell } from "./shell.js";
6
+ import { MOUSE_OFF, MOUSE_ON } from "./graph/orbit.js";
6
7
  import { style, clearScreen, paintFrame, enterFullscreen, exitFullscreen, } from "./render.js";
7
8
  import { KeyDecoder, ESC_FLUSH_MS } from "./keys.js";
8
9
  import { playSplash } from "./intro.js";
@@ -155,6 +156,10 @@ export async function startShell(phrenPath, profile, startup = {}) {
155
156
  const restoreTerminal = () => {
156
157
  // Shutdown cleanup is intentionally silent: terminal restoration is best-effort
157
158
  // cleanup, not a user-requested write path.
159
+ try {
160
+ process.stdout.write(MOUSE_OFF);
161
+ }
162
+ catch { }
158
163
  try {
159
164
  process.stdin.setRawMode(false);
160
165
  }
@@ -277,6 +282,13 @@ export async function startShell(phrenPath, profile, startup = {}) {
277
282
  // Hand the terminal to a child process (an editor) and take it back. The
278
283
  // shell owns raw mode, the alternate screen and the stdin listener, so all
279
284
  // three have to be unwound or the child and the key pump fight over input.
285
+ // Mouse reporting is switched on only while the Graph view is showing;
286
+ // elsewhere the terminal keeps its own click-and-drag text selection.
287
+ shell.setMouseHandler((on) => { try {
288
+ process.stdout.write(on ? MOUSE_ON : MOUSE_OFF);
289
+ }
290
+ catch { } });
291
+ shell.syncMouse();
280
292
  shell.setSuspendHandler(async (run) => {
281
293
  if (exiting)
282
294
  return;
@@ -288,6 +300,7 @@ export async function startShell(phrenPath, profile, startup = {}) {
288
300
  finally {
289
301
  if (!exiting) {
290
302
  grabTerminal();
303
+ shell.syncMouse();
291
304
  process.stdin.on("data", onData);
292
305
  // Anything typed at the child after it exited is not for us.
293
306
  decoder.flush();
@@ -13,6 +13,7 @@ import { type Point } from "./layout.js";
13
13
  import { GraphWatch, type ActivityItem } from "./watch.js";
14
14
  import { GraphAgents } from "./agents.js";
15
15
  import { GraphMascot } from "./mascot.js";
16
+ import type { OrbitCamera } from "./orbit.js";
16
17
  /** Nodes drawn at once. Terminals have far fewer pixels than a browser tab. */
17
18
  export declare const TUI_NODE_LIMIT = 350;
18
19
  export type GraphStatus = "idle" | "loading" | "ready" | "empty" | "error";
@@ -101,6 +102,22 @@ export declare class GraphController {
101
102
  readonly mascot: GraphMascot;
102
103
  /** Space opens the selected node's full text in a bubble on the canvas. */
103
104
  reader: boolean;
105
+ /**
106
+ * v: the same graph as a sphere. Selection, search, watch mode and the
107
+ * neighbour numbers all keep working; the camera orbits instead of panning.
108
+ */
109
+ orbit: boolean;
110
+ orbitCamera: OrbitCamera;
111
+ private orbitPositions;
112
+ private orbitRadius;
113
+ private orbitYawTarget;
114
+ private lastOrbitTouch;
115
+ private drag;
116
+ /** Where the canvas sits in the terminal, so mouse coordinates can be mapped onto it. */
117
+ canvasOrigin: {
118
+ col: number;
119
+ row: number;
120
+ };
104
121
  watchEnabled: boolean;
105
122
  /**
106
123
  * Wall-clock ms of the last navigation keypress. While the user is driving,
@@ -172,6 +189,24 @@ export declare class GraphController {
172
189
  width: number;
173
190
  height: number;
174
191
  };
192
+ /** The sphere is derived from the settled flat layout, never simulated. */
193
+ private rebuildOrbit;
194
+ /** A node's place on screen, with depth: 0 nearest, 1 farthest, always 0 on the flat map. */
195
+ projectNode(id: string): {
196
+ x: number;
197
+ y: number;
198
+ t: number;
199
+ } | null;
200
+ toggleOrbit(): boolean;
201
+ /** In orbit, the pan keys turn the sphere instead. */
202
+ private turn;
203
+ /** The visible node nearest a dot on the canvas, within a radius. */
204
+ nearestToDot(x: number, y: number, within: number): RuntimeNode | null;
205
+ /**
206
+ * Mouse: wheel zooms in both modes; a left drag turns the sphere or pans
207
+ * the map; a click with no movement selects the node under it.
208
+ */
209
+ private handleMouse;
175
210
  /** World → dot coordinates for the current camera. */
176
211
  project(p: Point): Point;
177
212
  fitAll(): void;
@@ -18,6 +18,9 @@ import { GraphWatch } from "./watch.js";
18
18
  import { GraphAgents } from "./agents.js";
19
19
  import { GraphMascot } from "./mascot.js";
20
20
  import { LIVE_BUBBLE_MS } from "./bubble.js";
21
+ import { DEFAULT_ORBIT, PITCH_LIMIT, buildOrbitLayout, parseMouse, projectOrbit, yawDelta, yawToFace } from "./orbit.js";
22
+ /** Left alone in orbit for this long, the sphere starts turning on its own. */
23
+ const IDLE_SPIN_MS = 6000;
21
24
  /** Nodes drawn at once. Terminals have far fewer pixels than a browser tab. */
22
25
  export const TUI_NODE_LIMIT = 350;
23
26
  const ALL_TYPES = { project: true, finding: true, task: true, entity: true, reference: true };
@@ -100,6 +103,19 @@ export class GraphController {
100
103
  mascot = new GraphMascot();
101
104
  /** Space opens the selected node's full text in a bubble on the canvas. */
102
105
  reader = false;
106
+ /**
107
+ * v: the same graph as a sphere. Selection, search, watch mode and the
108
+ * neighbour numbers all keep working; the camera orbits instead of panning.
109
+ */
110
+ orbit = false;
111
+ orbitCamera = { ...DEFAULT_ORBIT };
112
+ orbitPositions = new Map();
113
+ orbitRadius = 1;
114
+ orbitYawTarget = null;
115
+ lastOrbitTouch = 0;
116
+ drag = null;
117
+ /** Where the canvas sits in the terminal, so mouse coordinates can be mapped onto it. */
118
+ canvasOrigin = { col: 0, row: 2 };
103
119
  watchEnabled;
104
120
  /**
105
121
  * Wall-clock ms of the last navigation keypress. While the user is driving,
@@ -326,6 +342,7 @@ export class GraphController {
326
342
  // is cheap enough not to notice: under 10ms for a couple of hundred nodes,
327
343
  // and the focused subset that [ ] shows is far smaller than that.
328
344
  this.sim.settle();
345
+ this.rebuildOrbit();
329
346
  if (!warm || !this.lastPositions.size)
330
347
  this.fitAll();
331
348
  // One frame through the loop repaints, then it stops itself unless the
@@ -350,6 +367,111 @@ export class GraphController {
350
367
  get viewportSize() {
351
368
  return this.viewport;
352
369
  }
370
+ /** The sphere is derived from the settled flat layout, never simulated. */
371
+ rebuildOrbit() {
372
+ const nodes = this.visible.nodes.map((node) => ({ id: node.id, kind: node.kind, project: node.project, size: node.size }));
373
+ const built = buildOrbitLayout(nodes, this.visible.links, this.positions);
374
+ this.orbitPositions = built.positions;
375
+ this.orbitRadius = built.radius;
376
+ }
377
+ /** A node's place on screen, with depth: 0 nearest, 1 farthest, always 0 on the flat map. */
378
+ projectNode(id) {
379
+ if (this.orbit) {
380
+ const v = this.orbitPositions.get(id);
381
+ return v ? projectOrbit(v, this.orbitCamera, this.viewport, this.orbitRadius) : null;
382
+ }
383
+ const p = this.positions.get(id);
384
+ return p ? { ...this.project(p), t: 0 } : null;
385
+ }
386
+ toggleOrbit() {
387
+ this.orbit = !this.orbit;
388
+ this.drag = null;
389
+ this.orbitYawTarget = null;
390
+ this.lastOrbitTouch = Date.now();
391
+ if (this.orbit) {
392
+ this.orbitCamera = { ...DEFAULT_ORBIT };
393
+ if (this.selectedId)
394
+ this.flyTo(this.selectedId);
395
+ if (this.repaintHook)
396
+ this.startAnimation();
397
+ }
398
+ return this.orbit;
399
+ }
400
+ /** In orbit, the pan keys turn the sphere instead. */
401
+ turn(direction) {
402
+ const d = DIRECTIONS[direction];
403
+ this.orbitCamera.yaw += d.x * 0.12;
404
+ this.orbitCamera.pitch = Math.max(-PITCH_LIMIT, Math.min(PITCH_LIMIT, this.orbitCamera.pitch + d.y * 0.08));
405
+ this.orbitYawTarget = null;
406
+ this.lastOrbitTouch = Date.now();
407
+ }
408
+ /** The visible node nearest a dot on the canvas, within a radius. */
409
+ nearestToDot(x, y, within) {
410
+ let best = null;
411
+ let bestDistance = within;
412
+ for (const node of this.visible.nodes) {
413
+ const d = this.projectNode(node.id);
414
+ if (!d)
415
+ continue;
416
+ // A project marker has findings packed right up against it; a click on
417
+ // the marker means the project, so it wins a few dots of slack.
418
+ const distance = Math.hypot(d.x - x, d.y - y) - (node.kind === "project" ? 4 : 0);
419
+ if (distance < bestDistance) {
420
+ bestDistance = distance;
421
+ best = node;
422
+ }
423
+ }
424
+ return best;
425
+ }
426
+ /**
427
+ * Mouse: wheel zooms in both modes; a left drag turns the sphere or pans
428
+ * the map; a click with no movement selects the node under it.
429
+ */
430
+ handleMouse(m, host) {
431
+ if (m.type === "wheel") {
432
+ this.zoom(m.delta < 0 ? 1.15 : 1 / 1.15);
433
+ return true;
434
+ }
435
+ if (m.type === "press") {
436
+ if (m.button === 0)
437
+ this.drag = { col: m.col, row: m.row, moved: false };
438
+ return true;
439
+ }
440
+ if (m.type === "drag") {
441
+ if (!this.drag)
442
+ return true;
443
+ const dx = m.col - this.drag.col;
444
+ const dy = m.row - this.drag.row;
445
+ if (dx === 0 && dy === 0)
446
+ return true;
447
+ this.drag = { col: m.col, row: m.row, moved: true };
448
+ if (this.orbit) {
449
+ this.orbitCamera.yaw += dx * 0.035;
450
+ this.orbitCamera.pitch = Math.max(-PITCH_LIMIT, Math.min(PITCH_LIMIT, this.orbitCamera.pitch + dy * 0.06));
451
+ this.orbitYawTarget = null;
452
+ this.lastOrbitTouch = Date.now();
453
+ }
454
+ else {
455
+ this.userMoved = true;
456
+ this.cameraTarget = null;
457
+ this.camera.cx -= (dx * 2) / this.camera.scaleX;
458
+ this.camera.cy -= (dy * 4) / this.camera.scaleY;
459
+ }
460
+ return true;
461
+ }
462
+ const wasClick = this.drag !== null && !this.drag.moved;
463
+ this.drag = null;
464
+ if (wasClick) {
465
+ const x = (m.col - this.canvasOrigin.col) * 2 + 1;
466
+ const y = (m.row - this.canvasOrigin.row) * 4 + 2;
467
+ const node = this.nearestToDot(x, y, 12);
468
+ if (node) {
469
+ this.select(node.id);
470
+ host.setMessage(this.describe(node));
471
+ }
472
+ }
473
+ return true;
474
+ }
353
475
  /** World → dot coordinates for the current camera. */
354
476
  project(p) {
355
477
  return {
@@ -358,6 +480,11 @@ export class GraphController {
358
480
  };
359
481
  }
360
482
  fitAll() {
483
+ if (this.orbit) {
484
+ this.orbitCamera.zoom = 1;
485
+ this.orbitCamera.pitch = DEFAULT_ORBIT.pitch;
486
+ this.lastOrbitTouch = Date.now();
487
+ }
361
488
  const box = bounds(this.positions.values());
362
489
  this.cameraTarget = null;
363
490
  this.userMoved = false;
@@ -385,6 +512,11 @@ export class GraphController {
385
512
  };
386
513
  }
387
514
  zoom(factor) {
515
+ if (this.orbit) {
516
+ this.orbitCamera.zoom = Math.max(0.4, Math.min(4, this.orbitCamera.zoom * factor));
517
+ this.lastOrbitTouch = Date.now();
518
+ return;
519
+ }
388
520
  this.userMoved = true;
389
521
  // Both axes move together, so a zoom never changes the shape on screen.
390
522
  const clampZoom = (v) => Math.max(0.2, Math.min(24, v));
@@ -392,6 +524,10 @@ export class GraphController {
392
524
  this.camera.scaleY = clampZoom(this.camera.scaleY * factor);
393
525
  }
394
526
  pan(direction) {
527
+ if (this.orbit) {
528
+ this.turn(direction);
529
+ return;
530
+ }
395
531
  const d = DIRECTIONS[direction];
396
532
  const stepX = (this.viewport.width * 0.12) / this.camera.scaleX;
397
533
  const stepY = (this.viewport.height * 0.12) / this.camera.scaleY;
@@ -402,6 +538,20 @@ export class GraphController {
402
538
  }
403
539
  /** Centre the camera on a node, eased when animation is available. */
404
540
  flyTo(nodeId) {
541
+ if (this.orbit) {
542
+ // Turn the sphere so the node faces you, eased like a flight.
543
+ const v = this.orbitPositions.get(nodeId);
544
+ if (!v)
545
+ return;
546
+ this.orbitYawTarget = yawToFace(v);
547
+ if (this.repaintHook)
548
+ this.startAnimation();
549
+ else {
550
+ this.orbitCamera.yaw = this.orbitYawTarget;
551
+ this.orbitYawTarget = null;
552
+ }
553
+ return;
554
+ }
405
555
  const p = this.positions.get(nodeId);
406
556
  if (!p)
407
557
  return;
@@ -416,6 +566,10 @@ export class GraphController {
416
566
  }
417
567
  /** Fly only when the node sits outside the middle band of the viewport. */
418
568
  keepInView(nodeId) {
569
+ if (this.orbit) {
570
+ this.flyTo(nodeId);
571
+ return;
572
+ }
419
573
  const p = this.positions.get(nodeId);
420
574
  if (!p)
421
575
  return;
@@ -448,6 +602,23 @@ export class GraphController {
448
602
  }
449
603
  animationFrame() {
450
604
  let busy = this.watch.hot;
605
+ if (this.orbit) {
606
+ if (this.orbitYawTarget !== null) {
607
+ const d = yawDelta(this.orbitCamera.yaw, this.orbitYawTarget);
608
+ if (Math.abs(d) < 0.01) {
609
+ this.orbitCamera.yaw = this.orbitYawTarget;
610
+ this.orbitYawTarget = null;
611
+ }
612
+ else
613
+ this.orbitCamera.yaw += d * 0.25;
614
+ }
615
+ else if (!this.drag && Date.now() - this.lastOrbitTouch > IDLE_SPIN_MS) {
616
+ // Left alone, it turns slowly, so the depth is always there to see.
617
+ this.orbitCamera.yaw += 0.005;
618
+ }
619
+ // The loop stays alive in orbit so the idle spin can start on its own.
620
+ busy = true;
621
+ }
451
622
  if (this.liveRecall())
452
623
  busy = true;
453
624
  if (this.mascot.step())
@@ -656,6 +827,11 @@ export class GraphController {
656
827
  * generic handler have it (q, :, ?, view shortcuts, final Esc).
657
828
  */
658
829
  handleKey(rawKey, host) {
830
+ const mouse = parseMouse(rawKey);
831
+ if (mouse) {
832
+ this.lastUserInputAt = Date.now();
833
+ return this.status === "ready" ? this.handleMouse(mouse, host) : true;
834
+ }
659
835
  const key = normalizeArrow(rawKey);
660
836
  if (key !== "w" && key !== "W")
661
837
  this.lastUserInputAt = Date.now();
@@ -786,6 +962,13 @@ export class GraphController {
786
962
  : ` ${style.dim("watch off")}`);
787
963
  return true;
788
964
  }
965
+ if (key === "v") {
966
+ const on = this.toggleOrbit();
967
+ host.setMessage(on
968
+ ? ` ${style.boldCyan("⟲")} ${style.dim("orbit — drag to turn, wheel to zoom,")} ${style.boldCyan("v")} ${style.dim("back to the map")}`
969
+ : ` ${style.dim("flat map")}`);
970
+ return true;
971
+ }
789
972
  if (key === "o") {
790
973
  host.setMessage(` ${style.dim("open the 3D viewer in a browser:")} ${style.boldCyan("phren web-ui")}`);
791
974
  return true;
@@ -143,18 +143,16 @@ function centered(width, height, lines) {
143
143
  function drawCanvas(controller, cols, rows, selected) {
144
144
  const canvas = new BrailleCanvas(cols, rows);
145
145
  controller.setViewport(canvas.dotWidth, canvas.dotHeight);
146
- const positions = controller.positions;
147
146
  const searching = Boolean(controller.search.query);
148
147
  const matches = controller.search.matchIds;
149
148
  const placed = [];
150
149
  const projected = new Map();
151
150
  for (const node of controller.visible.nodes) {
152
- const p = positions.get(node.id);
153
- if (!p)
151
+ const d = controller.projectNode(node.id);
152
+ if (!d)
154
153
  continue;
155
- const d = controller.project(p);
156
154
  projected.set(node.id, d);
157
- placed.push({ node, x: d.x, y: d.y });
155
+ placed.push({ node, x: d.x, y: d.y, t: d.t });
158
156
  }
159
157
  const isLit = (id) => !searching || matches.has(id);
160
158
  // How connected the selection is, so a hub's highlight stays readable.
@@ -167,11 +165,12 @@ function drawCanvas(controller, cols, rows, selected) {
167
165
  continue;
168
166
  const touchesSelected = selected !== null && (link.source === selected.id || link.target === selected.id);
169
167
  const color = edgeColor(controller, link, touchesSelected, isLit(link.source) && isLit(link.target), selectedDegree);
170
- canvas.line(a.x, a.y, b.x, b.y, color, { z: touchesSelected ? 2 : 0, dotted: link.kind === "contradicts" });
168
+ const depth = (a.t + b.t) / 2;
169
+ canvas.line(a.x, a.y, b.x, b.y, depth > 0 ? blendHex(color, BG_COLOR, depth * 0.7) : color, { z: touchesSelected ? 2 : 0, dotted: link.kind === "contradicts" });
171
170
  }
172
171
  const watching = controller.watchEnabled && controller.watch.running;
173
172
  const heatOf = (id) => (watching ? controller.watch.heatOf(id) : 0);
174
- for (const { node, x, y } of placed) {
173
+ for (const { node, x, y, t } of placed) {
175
174
  const isSelected = selected?.id === node.id;
176
175
  const heat = heatOf(node.id);
177
176
  let color = node.baseColor;
@@ -182,7 +181,10 @@ function drawCanvas(controller, cols, rows, selected) {
182
181
  // A just-touched node pulses toward the live cyan and swells a little.
183
182
  if (heat > 0)
184
183
  color = blendHex(color, ACCENT_CYAN, 0.3 + heat * 0.55);
185
- const radius = dotRadius(node, isSelected) + (heat > 0.35 ? 1 : 0);
184
+ // In orbit the far side fades and shrinks; that is what reads as depth.
185
+ if (t > 0)
186
+ color = blendHex(color, BG_COLOR, t * 0.7);
187
+ const radius = Math.max(0, dotRadius(node, isSelected) + (heat > 0.35 ? 1 : 0) - (t > 0.5 ? 1 : 0));
186
188
  canvas.disc(x, y, radius, color, isSelected ? 4 : heat > 0 ? 3 : node.kind === "project" ? 3 : 1);
187
189
  // A ring around the hottest nodes, so a hit reads at a glance.
188
190
  if (heat > 0.55) {
@@ -209,7 +211,9 @@ function drawCanvas(controller, cols, rows, selected) {
209
211
  const bubbles = planBubbles(controller, cols, rows, selected);
210
212
  for (const b of bubbles)
211
213
  paintBubble(canvas, b);
212
- const ranked = placed.slice().sort((a, b) => labelPriority(controller, b.node, selected, neighborIndex) - labelPriority(controller, a.node, selected, neighborIndex));
214
+ // On the sphere only the near half gets glyphs and labels; naming the far
215
+ // side too flattened it straight back into a 2D heap.
216
+ const ranked = placed.filter((item) => item.t < 0.55 || item.node.id === selected?.id).sort((a, b) => labelPriority(controller, b.node, selected, neighborIndex) - labelPriority(controller, a.node, selected, neighborIndex));
213
217
  const onCanvas = ({ x, y }) => {
214
218
  const col = Math.floor(x / 2);
215
219
  const row = Math.floor(y / 4);
@@ -294,10 +298,9 @@ function drawCanvas(controller, cols, rows, selected) {
294
298
  if (controller.agents.enabled && controller.agents.agents.length) {
295
299
  const highlighted = controller.agents.current;
296
300
  for (const [project, agents] of controller.agents.byProject()) {
297
- const p = positions.get(project);
298
- if (!p)
301
+ const d = controller.projectNode(project);
302
+ if (!d || d.t > 0.55)
299
303
  continue;
300
- const d = controller.project(p);
301
304
  const col = Math.floor(d.x / 2);
302
305
  const row = Math.floor(d.y / 4) - 1;
303
306
  if (col < 0 || col >= cols || row < 0 || row >= rows)
@@ -314,9 +317,12 @@ function drawCanvas(controller, cols, rows, selected) {
314
317
  }
315
318
  // phren, wherever he currently is. Drawn after everything else so he is
316
319
  // never lost in the dot field — he is the thing you are meant to follow.
317
- const mascotPos = controller.mascot.pos;
318
- if (mascotPos) {
319
- const d = controller.project(mascotPos);
320
+ // On the sphere he sits at his node's projected place; the flat walk is 2D.
321
+ const mascotAt = controller.orbit
322
+ ? (controller.mascot.targetNodeId ? controller.projectNode(controller.mascot.targetNodeId) : null)
323
+ : (controller.mascot.pos ? controller.project(controller.mascot.pos) : null);
324
+ if (mascotAt) {
325
+ const d = mascotAt;
320
326
  const col = Math.floor(d.x / 2);
321
327
  const row = Math.floor(d.y / 4);
322
328
  if (col >= 0 && col < cols && row >= 0 && row < rows) {
@@ -347,11 +353,11 @@ function drawCanvas(controller, cols, rows, selected) {
347
353
  }
348
354
  function planBubbles(controller, cols, rows, selected) {
349
355
  if (controller.reader && selected) {
350
- const p = controller.positions.get(selected.id);
351
- if (!p)
356
+ const at = controller.projectNode(selected.id);
357
+ if (!at)
352
358
  return [];
353
359
  const text = selected.fullLabel || selected.label;
354
- const anchor = toCell(controller.project(p));
360
+ const anchor = toCell(at);
355
361
  const maxInner = Math.min(64, cols - BUBBLE_CHROME_COLS - 2);
356
362
  const maxRows = rows - BUBBLE_CHROME_ROWS - 1;
357
363
  if (maxInner < 12 || maxRows < 2)
@@ -372,13 +378,13 @@ function planBubbles(controller, cols, rows, selected) {
372
378
  const live = controller.liveRecall();
373
379
  if (!live)
374
380
  return [];
375
- const p = controller.positions.get(live.nodeId);
376
- if (!p)
381
+ const at = controller.projectNode(live.nodeId);
382
+ if (!at)
377
383
  return [];
378
384
  const text = live.item.event.snippet || live.item.event.filename || "";
379
385
  if (!text)
380
386
  return [];
381
- const anchor = toCell(controller.project(p));
387
+ const anchor = toCell(at);
382
388
  const inner = Math.min(40, cols - BUBBLE_CHROME_COLS - 2);
383
389
  if (inner < 12 || rows < 6)
384
390
  return [];
@@ -458,6 +464,8 @@ export function graphSummary(controller) {
458
464
  const n = (v) => v.toLocaleString("en-US");
459
465
  const capped = shown < total ? `${n(shown)} of ${n(total)} nodes` : `${n(shown)} nodes`;
460
466
  const parts = [capped, `${n(controller.visible.links.length)} edges`];
467
+ if (controller.orbit)
468
+ parts.push(`${colored(ACCENT_CYAN, "⟲")}${style.dim(" orbit")}`);
461
469
  if (controller.watchEnabled && controller.watch.running)
462
470
  parts.push(`${colored(ACCENT_CYAN, "◉")}${style.dim(" live")}`);
463
471
  return parts.join(style.dim(" · "));
@@ -548,7 +556,7 @@ function renderPane(controller, selected, width, height) {
548
556
  else {
549
557
  const total = controller.model.rawNodes.length;
550
558
  const shown = controller.visible.nodes.length;
551
- push(`${colored(ACCENT_CYAN, "❖")} ${style.bold("knowledge graph")}${controller.refreshing ? style.dim(" ⟳") : ""}${watching ? ` ${colored(ACCENT_CYAN, "◉")}${style.dim(" live")}` : ""}`);
559
+ push(`${colored(ACCENT_CYAN, "❖")} ${style.bold("knowledge graph")}${controller.refreshing ? style.dim(" ⟳") : ""}${controller.orbit ? ` ${colored(ACCENT_CYAN, "⟲")}${style.dim(" orbit")}` : ""}${watching ? ` ${colored(ACCENT_CYAN, "◉")}${style.dim(" live")}` : ""}`);
552
560
  push(style.dim(shown === total ? `${shown} nodes · ${controller.visible.links.length} edges` : `${shown} of ${total} nodes · ${controller.visible.links.length} edges`));
553
561
  push();
554
562
  row("filter", `${controller.preset.name}${style.dim(" f")}`);
@@ -35,6 +35,11 @@ export declare const IDEAL_DISTANCE = 12;
35
35
  */
36
36
  export declare const DEFAULT_ASPECT = 2.4;
37
37
  export declare function normalizeAspect(aspect: number | undefined): number;
38
+ /** Project ids in stable order plus, for every node, the project(s) it hangs off. */
39
+ export declare function homes(nodes: LayoutNode[], links: RawLink[]): {
40
+ projects: LayoutNode[];
41
+ homeOf: Map<string, string[]>;
42
+ };
38
43
  /**
39
44
  * Starting positions: projects on a ring, leaves in a jittered blob around
40
45
  * their home project, multi-home fragments at the centroid of their homes,
@@ -45,7 +45,7 @@ function clusterRadius(leafCount) {
45
45
  return IDEAL_DISTANCE * (0.9 + 0.42 * Math.sqrt(Math.max(0, leafCount)));
46
46
  }
47
47
  /** Project ids in stable order plus, for every node, the project(s) it hangs off. */
48
- function homes(nodes, links) {
48
+ export function homes(nodes, links) {
49
49
  const byId = new Map(nodes.map((node) => [node.id, node]));
50
50
  const projects = nodes.filter((node) => node.kind === "project").sort((a, b) => a.id.localeCompare(b.id));
51
51
  const projectByName = new Map(projects.map((node) => [node.project ?? node.id, node.id]));
@@ -96,14 +96,27 @@ export function seedPositions(nodes, links, aspect = DEFAULT_ASPECT) {
96
96
  continue;
97
97
  leavesPer.set(owner, (leavesPer.get(owner) ?? 0) + 1);
98
98
  }
99
- const spread = Math.max(...projects.map((p) => clusterRadius(leavesPer.get(p.id) ?? 0)), IDEAL_DISTANCE);
100
- const packed = (projects.length * spread * 2.3) / (2 * Math.PI);
101
- const ring = Math.max(IDEAL_DISTANCE * 2.2, packed);
99
+ // Each project gets a slice of the ring proportional to its cluster, not an
100
+ // equal share. Equal slices gave a one-finding project the same forty
101
+ // degrees as a fifty-finding one, so small and new projects sat alone in
102
+ // empty space at full ring distance while the heavy clusters merged into a
103
+ // blob — "most of it in the middle, a few way out", and the camera fitted
104
+ // to the few. Small clusters also sit a little inside the ring, so their
105
+ // outer edge lines up with their neighbours' rather than their centre.
106
+ const radii = projects.map((p) => clusterRadius(leavesPer.get(p.id) ?? 0));
107
+ const spread = Math.max(...radii, IDEAL_DISTANCE);
108
+ const slices = radii.map((r) => r * 2.3);
109
+ const circumference = slices.reduce((sum, w) => sum + w, 0);
110
+ const ring = Math.max(IDEAL_DISTANCE * 2.2, circumference / (2 * Math.PI));
111
+ // Projects sit at the start of their slice, so equal clusters land exactly
112
+ // where the equal-slice ring put them (two projects side by side, not
113
+ // stacked, which is the worst case on a wide screen).
114
+ let offset = 0;
102
115
  projects.forEach((project, i) => {
103
- // Start a quarter turn in so two projects sit side by side rather than
104
- // stacked, which is the worst case on a wide screen.
105
- const angle = (i / Math.max(1, projects.length)) * Math.PI * 2;
106
- positions.set(project.id, { x: Math.cos(angle) * ring * ratio, y: Math.sin(angle) * ring });
116
+ const angle = (offset / Math.max(circumference, 1)) * Math.PI * 2;
117
+ offset += slices[i];
118
+ const radius = Math.max(IDEAL_DISTANCE * 1.6, ring - (spread - radii[i]) * 0.7);
119
+ positions.set(project.id, { x: Math.cos(angle) * radius * ratio, y: Math.sin(angle) * radius });
107
120
  });
108
121
  if (projects.length === 1)
109
122
  positions.set(projects[0].id, { x: 0, y: 0 });
@@ -276,7 +289,10 @@ export class ForceSim {
276
289
  if (this.isProject[i]) {
277
290
  // Hold the project on its ring. The error is measured in
278
291
  // aspect-corrected space so the restoring force preserves the wide
279
- // ellipse rather than pulling the layout back into a circle.
292
+ // ellipse rather than pulling the layout back into a circle. A soft
293
+ // spring on purpose: pinning the radius outright left the clusters no
294
+ // room to breathe once the node cap made them larger than the seeded
295
+ // ring allowed for, and a forty-project store folded into a fan.
280
296
  const nx = xs[i] / this.aspect;
281
297
  const ny = ys[i];
282
298
  const radius = Math.hypot(nx, ny);
@@ -0,0 +1,81 @@
1
+ /**
2
+ * The graph in three dimensions.
3
+ *
4
+ * Not a second layout: the settled 2D map is lifted into a sphere. Projects
5
+ * sit on a fibonacci sphere in stable order, each cluster keeps the shape the
6
+ * force layout gave it and gains a seeded depth, fragments shared between
7
+ * projects fall to the middle where their homes' centroid is, and orphans go
8
+ * to an outer shell. Then a yaw/pitch camera with a little perspective
9
+ * projects it, and depth comes back as brightness and size.
10
+ *
11
+ * Also here: the SGR mouse protocol, because drag-to-orbit is the whole
12
+ * point. Pure functions throughout; the controller owns the state.
13
+ */
14
+ import type { RawLink } from "../../graph-core/types.js";
15
+ import { type LayoutNode, type Point } from "./layout.js";
16
+ export interface Vec3 {
17
+ x: number;
18
+ y: number;
19
+ z: number;
20
+ }
21
+ export interface OrbitCamera {
22
+ /** Rotation about the vertical axis, radians. */
23
+ yaw: number;
24
+ /** Tilt toward the viewer, radians; clamped so the sphere never flips. */
25
+ pitch: number;
26
+ /** 1 fits the sphere to the viewport. */
27
+ zoom: number;
28
+ }
29
+ export declare const DEFAULT_ORBIT: OrbitCamera;
30
+ export declare const PITCH_LIMIT = 1.25;
31
+ export interface OrbitLayout {
32
+ positions: Map<string, Vec3>;
33
+ /** Radius of the project sphere, in world units. */
34
+ radius: number;
35
+ }
36
+ /** Lift the 2D layout onto a sphere. Deterministic for the same inputs. */
37
+ export declare function buildOrbitLayout(nodes: LayoutNode[], links: RawLink[], flat: Map<string, Point>): OrbitLayout;
38
+ export interface Projected {
39
+ x: number;
40
+ y: number;
41
+ /** 0 nearest the viewer, 1 farthest. */
42
+ t: number;
43
+ }
44
+ /** World point → dot coordinates, with depth. */
45
+ export declare function projectOrbit(v: Vec3, cam: OrbitCamera, viewport: {
46
+ width: number;
47
+ height: number;
48
+ }, radius: number): Projected;
49
+ /** The yaw that brings a point to the front, facing the viewer. */
50
+ export declare function yawToFace(v: Vec3): number;
51
+ /** Shortest signed distance from yaw a to yaw b. */
52
+ export declare function yawDelta(a: number, b: number): number;
53
+ export type MouseEvent = {
54
+ type: "press";
55
+ button: number;
56
+ col: number;
57
+ row: number;
58
+ } | {
59
+ type: "drag";
60
+ button: number;
61
+ col: number;
62
+ row: number;
63
+ } | {
64
+ type: "release";
65
+ button: number;
66
+ col: number;
67
+ row: number;
68
+ } | {
69
+ type: "wheel";
70
+ delta: -1 | 1;
71
+ col: number;
72
+ row: number;
73
+ };
74
+ /**
75
+ * SGR mouse reporting (mode 1006): `ESC [ < b ; x ; y M` for a press or
76
+ * motion, `m` for a release. Bit 5 of b marks motion, bit 6 the wheel.
77
+ * Coordinates are 1-based; returned 0-based.
78
+ */
79
+ export declare function parseMouse(key: string): MouseEvent | null;
80
+ export declare const MOUSE_ON = "\u001B[?1000h\u001B[?1002h\u001B[?1006h";
81
+ export declare const MOUSE_OFF = "\u001B[?1006l\u001B[?1002l\u001B[?1000l";
@@ -0,0 +1,138 @@
1
+ /**
2
+ * The graph in three dimensions.
3
+ *
4
+ * Not a second layout: the settled 2D map is lifted into a sphere. Projects
5
+ * sit on a fibonacci sphere in stable order, each cluster keeps the shape the
6
+ * force layout gave it and gains a seeded depth, fragments shared between
7
+ * projects fall to the middle where their homes' centroid is, and orphans go
8
+ * to an outer shell. Then a yaw/pitch camera with a little perspective
9
+ * projects it, and depth comes back as brightness and size.
10
+ *
11
+ * Also here: the SGR mouse protocol, because drag-to-orbit is the whole
12
+ * point. Pure functions throughout; the controller owns the state.
13
+ */
14
+ import { homes } from "./layout.js";
15
+ export const DEFAULT_ORBIT = { yaw: 0, pitch: 0.32, zoom: 1 };
16
+ export const PITCH_LIMIT = 1.25;
17
+ function seeded(id, salt) {
18
+ let h = 2166136261;
19
+ for (const ch of `${id}:${salt}`) {
20
+ h ^= ch.charCodeAt(0);
21
+ h = Math.imul(h, 16777619);
22
+ }
23
+ return ((h >>> 0) % 10000) / 10000;
24
+ }
25
+ /** Lift the 2D layout onto a sphere. Deterministic for the same inputs. */
26
+ export function buildOrbitLayout(nodes, links, flat) {
27
+ const { projects, homeOf } = homes(nodes, links);
28
+ const positions = new Map();
29
+ const n = projects.length;
30
+ // How far each cluster reaches in the flat layout sets both its depth and
31
+ // how big the sphere has to be for neighbours not to run into each other.
32
+ const reach = new Map();
33
+ for (const node of nodes) {
34
+ if (node.kind === "project")
35
+ continue;
36
+ const hosts = homeOf.get(node.id) ?? [];
37
+ if (hosts.length !== 1)
38
+ continue;
39
+ const home = flat.get(hosts[0]);
40
+ const p = flat.get(node.id);
41
+ if (!home || !p)
42
+ continue;
43
+ reach.set(hosts[0], Math.max(reach.get(hosts[0]) ?? 0, Math.hypot(p.x - home.x, p.y - home.y)));
44
+ }
45
+ const maxReach = Math.max(12, ...reach.values());
46
+ // Enough surface for every cluster: the sphere's area carries n discs.
47
+ const radius = Math.max(maxReach * 1.6, Math.sqrt(n) * maxReach * 0.95);
48
+ const golden = Math.PI * (3 - Math.sqrt(5));
49
+ projects.forEach((project, i) => {
50
+ const y = n === 1 ? 0 : 1 - (i / (n - 1)) * 2;
51
+ const r = Math.sqrt(Math.max(0, 1 - y * y));
52
+ const a = golden * i;
53
+ positions.set(project.id, { x: Math.cos(a) * r * radius, y: y * radius * 0.82, z: Math.sin(a) * r * radius });
54
+ });
55
+ for (const node of nodes) {
56
+ if (node.kind === "project")
57
+ continue;
58
+ const hosts = (homeOf.get(node.id) ?? []).map((id) => positions.get(id)).filter((p) => Boolean(p));
59
+ if (hosts.length === 0) {
60
+ const u = seeded(node.id, "u") * Math.PI * 2;
61
+ const v = Math.acos(2 * seeded(node.id, "v") - 1);
62
+ const rr = radius * 1.28;
63
+ positions.set(node.id, { x: Math.sin(v) * Math.cos(u) * rr, y: Math.cos(v) * rr * 0.82, z: Math.sin(v) * Math.sin(u) * rr });
64
+ continue;
65
+ }
66
+ if (hosts.length > 1) {
67
+ // Shared: the centroid of its homes, which lies inside the sphere.
68
+ const c = hosts.reduce((s, p) => ({ x: s.x + p.x, y: s.y + p.y, z: s.z + p.z }), { x: 0, y: 0, z: 0 });
69
+ positions.set(node.id, { x: (c.x / hosts.length) * 0.55, y: (c.y / hosts.length) * 0.55, z: (c.z / hosts.length) * 0.55 });
70
+ continue;
71
+ }
72
+ const homeId = (homeOf.get(node.id) ?? [])[0];
73
+ const home2 = flat.get(homeId);
74
+ const p2 = flat.get(node.id);
75
+ const home3 = hosts[0];
76
+ const dx = home2 && p2 ? p2.x - home2.x : 0;
77
+ const dy = home2 && p2 ? p2.y - home2.y : 0;
78
+ const depth = (seeded(node.id, "z") * 2 - 1) * (reach.get(homeId) ?? maxReach) * 0.7;
79
+ positions.set(node.id, { x: home3.x + dx * 0.85, y: home3.y + dy * 0.85, z: home3.z + depth });
80
+ }
81
+ return { positions, radius };
82
+ }
83
+ /** World point → dot coordinates, with depth. */
84
+ export function projectOrbit(v, cam, viewport, radius) {
85
+ const cy = Math.cos(cam.yaw);
86
+ const sy = Math.sin(cam.yaw);
87
+ const x1 = v.x * cy - v.z * sy;
88
+ const z1 = v.x * sy + v.z * cy;
89
+ const cp = Math.cos(cam.pitch);
90
+ const sp = Math.sin(cam.pitch);
91
+ const y2 = v.y * cp - z1 * sp;
92
+ const z2 = v.y * sp + z1 * cp;
93
+ // z2 toward the viewer. Depth 0 is the near pole of the outer shell.
94
+ const span = radius * 1.4;
95
+ const t = Math.max(0, Math.min(1, (span - z2) / (2 * span)));
96
+ const focal = radius * 4.5;
97
+ const f = focal / (focal + (span - z2));
98
+ const sx = ((viewport.width * 0.5) / radius) * cam.zoom;
99
+ const sYy = ((viewport.height * 0.5) / radius) * cam.zoom;
100
+ return { x: viewport.width / 2 + x1 * f * sx, y: viewport.height / 2 + y2 * f * sYy, t };
101
+ }
102
+ /** The yaw that brings a point to the front, facing the viewer. */
103
+ export function yawToFace(v) {
104
+ // After the yaw rotation z' = x·sin(yaw) + z·cos(yaw), which peaks at atan2(x, z).
105
+ return Math.atan2(v.x, v.z);
106
+ }
107
+ /** Shortest signed distance from yaw a to yaw b. */
108
+ export function yawDelta(a, b) {
109
+ let d = (b - a) % (Math.PI * 2);
110
+ if (d > Math.PI)
111
+ d -= Math.PI * 2;
112
+ if (d < -Math.PI)
113
+ d += Math.PI * 2;
114
+ return d;
115
+ }
116
+ /**
117
+ * SGR mouse reporting (mode 1006): `ESC [ < b ; x ; y M` for a press or
118
+ * motion, `m` for a release. Bit 5 of b marks motion, bit 6 the wheel.
119
+ * Coordinates are 1-based; returned 0-based.
120
+ */
121
+ export function parseMouse(key) {
122
+ const m = /^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/.exec(key);
123
+ if (!m)
124
+ return null;
125
+ const b = Number(m[1]);
126
+ const col = Number(m[2]) - 1;
127
+ const row = Number(m[3]) - 1;
128
+ if (b & 64)
129
+ return { type: "wheel", delta: (b & 1) === 0 ? -1 : 1, col, row };
130
+ const button = b & 3;
131
+ if (m[4] === "m")
132
+ return { type: "release", button, col, row };
133
+ if (b & 32)
134
+ return { type: "drag", button, col, row };
135
+ return { type: "press", button, col, row };
136
+ }
137
+ export const MOUSE_ON = "\x1b[?1000h\x1b[?1002h\x1b[?1006h";
138
+ export const MOUSE_OFF = "\x1b[?1006l\x1b[?1002l\x1b[?1000l";
@@ -251,6 +251,7 @@ export function shellHelpText() {
251
251
  ` ${style.bold("Findings")} ${k("a")} ${d("tell phren")} ${k("d")} ${d("delete selected")}`,
252
252
  ` ${style.bold("Review Queue")} ${k("↵")} ${d("inspect selected item")} ${d("(read-only)")}`,
253
253
  ` ${style.bold("Graph")} ${k("↑↓←→")} ${d("walk")} ${k("1-9")} ${d("neighbour")} ${k("↵")} ${d("select / focus")} ${k("␣")} ${d("read in a bubble")} ${k("w")} ${d("watch")}`,
254
+ ` ${k("v")} ${d("orbit: the graph as a sphere")} ${k("drag")} ${d("turn")} ${k("wheel")} ${d("zoom")} ${k("click")} ${d("select")} ${k("HJKL")} ${d("turn without a mouse")}`,
254
255
  ` ${" ".repeat(13)}${k("/")} ${d("search")} ${k("n N")} ${d("next / prev hit")} ${k("f")} ${d("filter")} ${k("[ ]")} ${d("project")}`,
255
256
  ` ${" ".repeat(13)}${k("+ -")} ${d("zoom")} ${k("0")} ${d("fit")} ${k("r")} ${d("re-lay out")} ${k("⇧↑↓←→")} ${d("pan")} ${k("o")} ${d("3D viewer")}`,
256
257
  ` ${style.bold("Skills")} ${k("e")} ${d("edit in $EDITOR")} ${k("E")} ${d("edit here")} ${k("t")} ${d("toggle enabled")} ${k("d")} ${d("remove")}`,
@@ -50,6 +50,15 @@ export declare class PhrenShell {
50
50
  * Let the host lend the terminal to a child process. Without one — a non-TTY
51
51
  * host, or an embedder — callers fall back to telling the user the path.
52
52
  */
53
+ /**
54
+ * The Graph view wants the mouse (drag to orbit, wheel to zoom, click to
55
+ * select); every other view wants the terminal's own text selection. The
56
+ * entry point supplies what turning it on and off means for this terminal.
57
+ */
58
+ setMouseHandler(handler: ((on: boolean) => void) | null): void;
59
+ private mouseHandler;
60
+ /** Apply the mouse state for the current view (after grabbing the terminal). */
61
+ syncMouse(): void;
53
62
  setSuspendHandler(handler: ((run: () => Promise<void> | void) => Promise<void>) | null): void;
54
63
  get canSuspend(): boolean;
55
64
  /** Run `fn` with the terminal released. Resolves false when that is impossible. */
@@ -107,6 +107,19 @@ export class PhrenShell {
107
107
  * Let the host lend the terminal to a child process. Without one — a non-TTY
108
108
  * host, or an embedder — callers fall back to telling the user the path.
109
109
  */
110
+ /**
111
+ * The Graph view wants the mouse (drag to orbit, wheel to zoom, click to
112
+ * select); every other view wants the terminal's own text selection. The
113
+ * entry point supplies what turning it on and off means for this terminal.
114
+ */
115
+ setMouseHandler(handler) {
116
+ this.mouseHandler = handler;
117
+ }
118
+ mouseHandler = null;
119
+ /** Apply the mouse state for the current view (after grabbing the terminal). */
120
+ syncMouse() {
121
+ this.mouseHandler?.(this.state.view === "Graph");
122
+ }
110
123
  setSuspendHandler(handler) {
111
124
  this.suspendHandler = handler;
112
125
  }
@@ -134,7 +147,10 @@ export class PhrenShell {
134
147
  setView(view) {
135
148
  if (this.state.view === "Graph" && view !== "Graph")
136
149
  this._graph?.stopAnimation();
150
+ const hadMouse = this.state.view === "Graph";
137
151
  this.state.view = view;
152
+ if (hadMouse !== (view === "Graph"))
153
+ this.mouseHandler?.(view === "Graph");
138
154
  this.viewScrollMap[view] = 0;
139
155
  saveShellState(this.phrenPath, this.state);
140
156
  }
@@ -90,7 +90,7 @@ function renderBottomBar(state, navMode, inputCtx, inputBuf) {
90
90
  Skills: [`${k("↑↓")} ${d("move")}`, `${k("e")} ${d("edit")}`, `${k("t")} ${d("toggle")}`],
91
91
  Hooks: [`${k("↑↓")} ${d("move")}`, `${k("a")} ${d("enable")}`],
92
92
  Health: [`${k("↑↓")} ${d("scroll")}`],
93
- Graph: [`${k("↑↓←→")} ${d("walk")}`, `${k("↵")} ${d("select")}`, `${k("␣")} ${d("read")}`, `${k("w")} ${d("watch")}`, `${k("a")} ${d("agents")}`],
93
+ Graph: [`${k("↑↓←→")} ${d("walk")}`, `${k("↵")} ${d("select")}`, `${k("␣")} ${d("read")}`, `${k("v")} ${d("orbit")}`, `${k("w")} ${d("watch")}`, `${k("a")} ${d("agents")}`],
94
94
  };
95
95
  const search = state.view === "Graph" ? `${k("/")} ${d("search")}` : `${k("/")} ${d("filter")}`;
96
96
  // `? keys` and `q quit` are the two you cannot afford to lose, so a narrow
@@ -737,6 +737,8 @@ export async function renderShell(ctx, navMode, inputCtx, inputBuf, showHelp, he
737
737
  if (offer)
738
738
  message = ` ${style.boldCyan("▲")} ${style.dim(`${offer} — press`)} ${style.boldCyan("a")} ${style.dim("to see them")}`;
739
739
  contentLines = renderGraphView(controller, renderWidth(), height);
740
+ // Mouse reports are terminal coordinates; the canvas starts under the top bar.
741
+ controller.canvasOrigin = { col: 0, row: topBar.split("\n").length };
740
742
  break;
741
743
  }
742
744
  default:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phren/cli",
3
- "version": "0.1.49",
3
+ "version": "0.1.51",
4
4
  "description": "Knowledge layer for AI agents — CLI, MCP server, and data layer",
5
5
  "type": "module",
6
6
  "bin": {