@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,87 @@
1
+ /**
2
+ * Deterministic 2D force layout for the terminal graph view.
3
+ *
4
+ * The web viewer leans on 3d-force-graph; in the terminal we want something
5
+ * dependency-free, fast enough for a few hundred nodes, and — above all —
6
+ * deterministic, so the same store draws the same map every time the view
7
+ * opens. All jitter is derived from node ids via `seeded()`; nothing here
8
+ * calls Math.random.
9
+ *
10
+ * The store's topology is a star (project → findings/tasks/fragments/refs),
11
+ * so the simulation adds a gentle pull toward each node's home project. That
12
+ * keeps clusters readable instead of letting repulsion smear everything into
13
+ * one ring.
14
+ */
15
+ import type { NodeKind, RawLink } from "../../graph-core/types.js";
16
+ export interface LayoutNode {
17
+ id: string;
18
+ kind: NodeKind;
19
+ /** Owning project name, for the cluster pull. Projects own themselves. */
20
+ project?: string;
21
+ /** Visual size from `sizeForNode`; drives repulsion mass. */
22
+ size: number;
23
+ }
24
+ export interface Point {
25
+ x: number;
26
+ y: number;
27
+ }
28
+ /** Ideal edge length in world units. Everything else is scaled off this. */
29
+ export declare const IDEAL_DISTANCE = 12;
30
+ /**
31
+ * A terminal canvas is far wider than it is tall. A layout that settles into a
32
+ * circle therefore strands most of the screen, so the simulation is told the
33
+ * canvas aspect and lays the graph out as a matching ellipse: the project ring
34
+ * is stretched horizontally and vertical drift is damped by the same factor.
35
+ */
36
+ export declare const DEFAULT_ASPECT = 2.4;
37
+ export declare function normalizeAspect(aspect: number | undefined): number;
38
+ /**
39
+ * Starting positions: projects on a ring, leaves in a jittered blob around
40
+ * their home project, multi-home fragments at the centroid of their homes,
41
+ * orphans on an outer ring.
42
+ */
43
+ export declare function seedPositions(nodes: LayoutNode[], links: RawLink[], aspect?: number): Map<string, Point>;
44
+ export declare class ForceSim {
45
+ readonly positions: Map<string, Point>;
46
+ private readonly ids;
47
+ private readonly index;
48
+ private readonly mass;
49
+ private readonly anchors;
50
+ private readonly isProject;
51
+ private readonly links;
52
+ private temperature;
53
+ private readonly startTemperature;
54
+ private readonly aspect;
55
+ /** How far apart projects push each other; scaled to the clusters they carry. */
56
+ private readonly projectCutoff;
57
+ /**
58
+ * The ring radius each project should sit at, measured in aspect-corrected
59
+ * space. Seeding a packed ring is not enough on its own: mutual repulsion
60
+ * between many projects expands it again, which is how a forty-project store
61
+ * ended up sprawling to nearly twice its seeded size. A radial spring holds
62
+ * each project at the radius the packing chose.
63
+ */
64
+ private readonly targetRadius;
65
+ constructor(nodes: LayoutNode[], links: RawLink[], seed?: Map<string, Point>, aspect?: number);
66
+ /** 1 at the start, 0 when settled; mirrors d3's `alpha` for hosts that animate. */
67
+ get alpha(): number;
68
+ get settled(): boolean;
69
+ /**
70
+ * Reuse a previous layout's positions for nodes that survived a data
71
+ * refresh, and reheat only mildly so the map shifts instead of scrambling.
72
+ */
73
+ warmStart(previous: Map<string, Point>): void;
74
+ /** Reheat to the initial temperature (e.g. the `r` relayout key). */
75
+ reheat(): void;
76
+ tick(count?: number): void;
77
+ /** Run until settled or the tick budget is spent. */
78
+ settle(maxTicks?: number): void;
79
+ private step;
80
+ }
81
+ /** Axis-aligned bounds of a position set; null when empty. */
82
+ export declare function bounds(positions: Iterable<Point>): {
83
+ minX: number;
84
+ minY: number;
85
+ maxX: number;
86
+ maxY: number;
87
+ } | null;
@@ -0,0 +1,335 @@
1
+ /**
2
+ * Deterministic 2D force layout for the terminal graph view.
3
+ *
4
+ * The web viewer leans on 3d-force-graph; in the terminal we want something
5
+ * dependency-free, fast enough for a few hundred nodes, and — above all —
6
+ * deterministic, so the same store draws the same map every time the view
7
+ * opens. All jitter is derived from node ids via `seeded()`; nothing here
8
+ * calls Math.random.
9
+ *
10
+ * The store's topology is a star (project → findings/tasks/fragments/refs),
11
+ * so the simulation adds a gentle pull toward each node's home project. That
12
+ * keeps clusters readable instead of letting repulsion smear everything into
13
+ * one ring.
14
+ */
15
+ import { seeded } from "../../graph-core/model.js";
16
+ /** Ideal edge length in world units. Everything else is scaled off this. */
17
+ export const IDEAL_DISTANCE = 12;
18
+ /**
19
+ * A terminal canvas is far wider than it is tall. A layout that settles into a
20
+ * circle therefore strands most of the screen, so the simulation is told the
21
+ * canvas aspect and lays the graph out as a matching ellipse: the project ring
22
+ * is stretched horizontally and vertical drift is damped by the same factor.
23
+ */
24
+ export const DEFAULT_ASPECT = 2.4;
25
+ const MAX_ASPECT = 3.5;
26
+ export function normalizeAspect(aspect) {
27
+ if (!aspect || !Number.isFinite(aspect) || aspect <= 0)
28
+ return DEFAULT_ASPECT;
29
+ return Math.max(1, Math.min(aspect, MAX_ASPECT));
30
+ }
31
+ /** Spring strength by edge flavour: spokes hold the clusters, enrichment edges just nudge. */
32
+ const LINK_STRENGTH = {
33
+ star: 1,
34
+ fragment: 0.25,
35
+ supersedes: 0.6,
36
+ contradicts: 0.4,
37
+ };
38
+ /**
39
+ * How far a project's own nodes sprawl from it, estimated from how many it has.
40
+ * The ring is sized from this so clusters end up close to touching; sizing the
41
+ * ring by project count alone left the same gap at every scale and the graph
42
+ * never filled more than about a seventh of its own bounds.
43
+ */
44
+ function clusterRadius(leafCount) {
45
+ return IDEAL_DISTANCE * (0.9 + 0.42 * Math.sqrt(Math.max(0, leafCount)));
46
+ }
47
+ /** Project ids in stable order plus, for every node, the project(s) it hangs off. */
48
+ function homes(nodes, links) {
49
+ const byId = new Map(nodes.map((node) => [node.id, node]));
50
+ const projects = nodes.filter((node) => node.kind === "project").sort((a, b) => a.id.localeCompare(b.id));
51
+ const projectByName = new Map(projects.map((node) => [node.project ?? node.id, node.id]));
52
+ const homeOf = new Map();
53
+ for (const node of nodes) {
54
+ if (node.kind === "project") {
55
+ homeOf.set(node.id, [node.id]);
56
+ continue;
57
+ }
58
+ const own = node.project ? projectByName.get(node.project) : undefined;
59
+ homeOf.set(node.id, own ? [own] : []);
60
+ }
61
+ for (const link of links) {
62
+ if (link.kind && link.kind !== "star")
63
+ continue;
64
+ const a = byId.get(link.source);
65
+ const b = byId.get(link.target);
66
+ if (!a || !b)
67
+ continue;
68
+ if (a.kind === "project" && b.kind !== "project")
69
+ pushUnique(homeOf.get(b.id), a.id);
70
+ else if (b.kind === "project" && a.kind !== "project")
71
+ pushUnique(homeOf.get(a.id), b.id);
72
+ }
73
+ return { projects, homeOf };
74
+ }
75
+ function pushUnique(list, value) {
76
+ if (!list.includes(value))
77
+ list.push(value);
78
+ }
79
+ /**
80
+ * Starting positions: projects on a ring, leaves in a jittered blob around
81
+ * their home project, multi-home fragments at the centroid of their homes,
82
+ * orphans on an outer ring.
83
+ */
84
+ export function seedPositions(nodes, links, aspect = DEFAULT_ASPECT) {
85
+ const positions = new Map();
86
+ const ratio = normalizeAspect(aspect);
87
+ const { projects, homeOf } = homes(nodes, links);
88
+ // Pack the ring so neighbouring clusters nearly touch: the circumference has
89
+ // to carry one cluster diameter per project, with a little air between.
90
+ const leavesPer = new Map();
91
+ for (const [id, hosts] of homeOf) {
92
+ if (hosts.length === 0)
93
+ continue;
94
+ const owner = hosts[0];
95
+ if (owner === id)
96
+ continue;
97
+ leavesPer.set(owner, (leavesPer.get(owner) ?? 0) + 1);
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);
102
+ 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 });
107
+ });
108
+ if (projects.length === 1)
109
+ positions.set(projects[0].id, { x: 0, y: 0 });
110
+ const outer = ring + IDEAL_DISTANCE * 3;
111
+ for (const node of nodes) {
112
+ if (node.kind === "project")
113
+ continue;
114
+ const home = (homeOf.get(node.id) ?? []).map((id) => positions.get(id)).filter((p) => Boolean(p));
115
+ const angle = seeded(node.id, "angle") * Math.PI * 2;
116
+ if (home.length === 0) {
117
+ positions.set(node.id, { x: Math.cos(angle) * outer * ratio, y: Math.sin(angle) * outer });
118
+ continue;
119
+ }
120
+ const cx = home.reduce((sum, p) => sum + p.x, 0) / home.length;
121
+ const cy = home.reduce((sum, p) => sum + p.y, 0) / home.length;
122
+ const radius = home.length > 1 ? IDEAL_DISTANCE * 0.4 : IDEAL_DISTANCE * (0.6 + seeded(node.id, "radius") * 1.2);
123
+ positions.set(node.id, { x: cx + Math.cos(angle) * radius, y: cy + Math.sin(angle) * radius });
124
+ }
125
+ return positions;
126
+ }
127
+ export class ForceSim {
128
+ positions;
129
+ ids;
130
+ index;
131
+ mass;
132
+ anchors;
133
+ isProject;
134
+ links;
135
+ temperature;
136
+ startTemperature;
137
+ aspect;
138
+ /** How far apart projects push each other; scaled to the clusters they carry. */
139
+ projectCutoff;
140
+ /**
141
+ * The ring radius each project should sit at, measured in aspect-corrected
142
+ * space. Seeding a packed ring is not enough on its own: mutual repulsion
143
+ * between many projects expands it again, which is how a forty-project store
144
+ * ended up sprawling to nearly twice its seeded size. A radial spring holds
145
+ * each project at the radius the packing chose.
146
+ */
147
+ targetRadius;
148
+ constructor(nodes, links, seed, aspect = DEFAULT_ASPECT) {
149
+ this.aspect = normalizeAspect(aspect);
150
+ const leaves = nodes.filter((node) => node.kind !== "project").length;
151
+ const projectCount = Math.max(1, nodes.length - leaves);
152
+ this.projectCutoff = clusterRadius(leaves / projectCount) * 2.4;
153
+ this.ids = nodes.map((node) => node.id);
154
+ this.index = new Map(this.ids.map((id, i) => [id, i]));
155
+ this.mass = nodes.map((node) => (node.kind === "project" ? 4 : 1) * Math.max(0.6, node.size / 12));
156
+ this.isProject = nodes.map((node) => node.kind === "project");
157
+ const { homeOf } = homes(nodes, links);
158
+ this.anchors = nodes.map((node) => (homeOf.get(node.id) ?? []).map((id) => this.index.get(id)).filter((i) => i !== undefined));
159
+ this.links = [];
160
+ for (const link of links) {
161
+ const a = this.index.get(link.source);
162
+ const b = this.index.get(link.target);
163
+ if (a === undefined || b === undefined || a === b)
164
+ continue;
165
+ this.links.push({ a, b, strength: LINK_STRENGTH[link.kind ?? "star"] });
166
+ }
167
+ const seeded = seedPositions(nodes, links, this.aspect);
168
+ this.positions = new Map();
169
+ for (const id of this.ids)
170
+ this.positions.set(id, { ...(seed?.get(id) ?? seeded.get(id)) });
171
+ this.targetRadius = this.ids.map((id, i) => {
172
+ if (!this.isProject[i])
173
+ return 0;
174
+ const p = seeded.get(id);
175
+ return Math.hypot(p.x / this.aspect, p.y);
176
+ });
177
+ this.startTemperature = IDEAL_DISTANCE * Math.max(1, Math.sqrt(nodes.length) / 4);
178
+ this.temperature = this.startTemperature;
179
+ }
180
+ /** 1 at the start, 0 when settled; mirrors d3's `alpha` for hosts that animate. */
181
+ get alpha() {
182
+ return this.startTemperature > 0 ? this.temperature / this.startTemperature : 0;
183
+ }
184
+ get settled() {
185
+ return this.temperature < 0.15;
186
+ }
187
+ /**
188
+ * Reuse a previous layout's positions for nodes that survived a data
189
+ * refresh, and reheat only mildly so the map shifts instead of scrambling.
190
+ */
191
+ warmStart(previous) {
192
+ let reused = 0;
193
+ for (const id of this.ids) {
194
+ const prev = previous.get(id);
195
+ if (!prev)
196
+ continue;
197
+ this.positions.set(id, { ...prev });
198
+ reused++;
199
+ }
200
+ if (reused > 0)
201
+ this.temperature = Math.max(0.15, this.startTemperature * (reused === this.ids.length ? 0.15 : 0.4));
202
+ }
203
+ /** Reheat to the initial temperature (e.g. the `r` relayout key). */
204
+ reheat() {
205
+ this.temperature = this.startTemperature;
206
+ }
207
+ tick(count = 1) {
208
+ for (let n = 0; n < count; n++) {
209
+ if (this.settled)
210
+ return;
211
+ this.step();
212
+ }
213
+ }
214
+ /** Run until settled or the tick budget is spent. */
215
+ settle(maxTicks = 400) {
216
+ for (let n = 0; n < maxTicks && !this.settled; n++)
217
+ this.step();
218
+ }
219
+ step() {
220
+ const count = this.ids.length;
221
+ if (count === 0) {
222
+ this.temperature = 0;
223
+ return;
224
+ }
225
+ const xs = new Float64Array(count);
226
+ const ys = new Float64Array(count);
227
+ const dx = new Float64Array(count);
228
+ const dy = new Float64Array(count);
229
+ for (let i = 0; i < count; i++) {
230
+ const p = this.positions.get(this.ids[i]);
231
+ xs[i] = p.x;
232
+ ys[i] = p.y;
233
+ }
234
+ const k = IDEAL_DISTANCE;
235
+ const k2 = k * k;
236
+ // Repulsion: k² / d, weighted by mass so projects carve out room.
237
+ for (let i = 0; i < count; i++) {
238
+ for (let j = i + 1; j < count; j++) {
239
+ let ddx = xs[i] - xs[j];
240
+ let ddy = ys[i] - ys[j];
241
+ let dist2 = ddx * ddx + ddy * ddy;
242
+ if (dist2 < 0.01) {
243
+ // Coincident nodes: split them deterministically by index.
244
+ ddx = ((i * 7919 + j * 104729) % 17) / 17 - 0.5;
245
+ ddy = ((i * 15485863 + j * 32452843) % 13) / 13 - 0.5;
246
+ dist2 = ddx * ddx + ddy * ddy || 0.01;
247
+ }
248
+ const dist = Math.sqrt(dist2);
249
+ const cutoff = this.isProject[i] || this.isProject[j] ? this.projectCutoff : k * 6;
250
+ if (dist > cutoff)
251
+ continue;
252
+ const force = (k2 / dist) * Math.sqrt(this.mass[i] * this.mass[j]);
253
+ const fx = (ddx / dist) * force;
254
+ const fy = (ddy / dist) * force;
255
+ dx[i] += fx;
256
+ dy[i] += fy;
257
+ dx[j] -= fx;
258
+ dy[j] -= fy;
259
+ }
260
+ }
261
+ // Attraction along links: d² / k, scaled by the edge flavour.
262
+ for (const link of this.links) {
263
+ const ddx = xs[link.a] - xs[link.b];
264
+ const ddy = ys[link.a] - ys[link.b];
265
+ const dist = Math.sqrt(ddx * ddx + ddy * ddy) || 0.01;
266
+ const force = ((dist * dist) / k) * link.strength;
267
+ const fx = (ddx / dist) * force;
268
+ const fy = (ddy / dist) * force;
269
+ dx[link.a] -= fx;
270
+ dy[link.a] -= fy;
271
+ dx[link.b] += fx;
272
+ dy[link.b] += fy;
273
+ }
274
+ // Cluster pull toward the home project(s); projects drift gently to the origin.
275
+ for (let i = 0; i < count; i++) {
276
+ if (this.isProject[i]) {
277
+ // Hold the project on its ring. The error is measured in
278
+ // aspect-corrected space so the restoring force preserves the wide
279
+ // ellipse rather than pulling the layout back into a circle.
280
+ const nx = xs[i] / this.aspect;
281
+ const ny = ys[i];
282
+ const radius = Math.hypot(nx, ny);
283
+ if (radius > 0.01) {
284
+ const pull = (this.targetRadius[i] - radius) * 0.18;
285
+ dx[i] += (nx / radius) * pull * this.aspect;
286
+ dy[i] += (ny / radius) * pull;
287
+ }
288
+ continue;
289
+ }
290
+ const anchors = this.anchors[i];
291
+ if (!anchors.length)
292
+ continue;
293
+ let ax = 0;
294
+ let ay = 0;
295
+ for (const a of anchors) {
296
+ ax += xs[a];
297
+ ay += ys[a];
298
+ }
299
+ ax /= anchors.length;
300
+ ay /= anchors.length;
301
+ dx[i] += (ax - xs[i]) * 0.08;
302
+ dy[i] += (ay - ys[i]) * 0.08 * Math.sqrt(this.aspect);
303
+ }
304
+ // Apply, capped by the current temperature.
305
+ const cap = this.temperature;
306
+ for (let i = 0; i < count; i++) {
307
+ const len = Math.sqrt(dx[i] * dx[i] + dy[i] * dy[i]);
308
+ if (len === 0)
309
+ continue;
310
+ const scale = Math.min(len, cap) / len;
311
+ const p = this.positions.get(this.ids[i]);
312
+ p.x = xs[i] + dx[i] * scale;
313
+ p.y = ys[i] + dy[i] * scale;
314
+ }
315
+ this.temperature *= 0.94;
316
+ }
317
+ }
318
+ /** Axis-aligned bounds of a position set; null when empty. */
319
+ export function bounds(positions) {
320
+ let minX = Infinity;
321
+ let minY = Infinity;
322
+ let maxX = -Infinity;
323
+ let maxY = -Infinity;
324
+ for (const p of positions) {
325
+ if (p.x < minX)
326
+ minX = p.x;
327
+ if (p.y < minY)
328
+ minY = p.y;
329
+ if (p.x > maxX)
330
+ maxX = p.x;
331
+ if (p.y > maxY)
332
+ maxY = p.y;
333
+ }
334
+ return Number.isFinite(minX) ? { minX, minY, maxX, maxY } : null;
335
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Watch mode for the terminal graph.
3
+ *
4
+ * Every memory phren lands on — an MCP `search_knowledge` hit, a memory a
5
+ * hook injected before a prompt, a finding just written — is appended to
6
+ * `.runtime/lookup-events.jsonl`. Watch mode tails that log so a graph open
7
+ * in one terminal lights up as an agent works in another: the node pulses,
8
+ * the camera flies to it, and the finding's full text lands in the pane.
9
+ *
10
+ * This module owns the event plumbing only. Drawing lives in graph-view.ts
11
+ * and camera/selection in controller.ts.
12
+ */
13
+ import { type LookupEvent } from "../../governance/activity.js";
14
+ /** How long a touched node stays lit, in ms. */
15
+ export declare const HEAT_MS = 6000;
16
+ /** Events kept for the activity feed. */
17
+ export declare const ACTIVITY_LIMIT = 60;
18
+ export interface ActivityItem {
19
+ event: LookupEvent;
20
+ /** Wall-clock ms when this arrived; drives heat decay and the feed's age column. */
21
+ seenAt: number;
22
+ /** Graph node this event points at, when resolvable. */
23
+ nodeId?: string;
24
+ /** True for rows loaded as history rather than seen live. */
25
+ historical: boolean;
26
+ }
27
+ export interface GraphWatchOptions {
28
+ pollMs?: number;
29
+ /** Injected in tests so no real file or timer is needed. */
30
+ tail?: {
31
+ poll: () => LookupEvent[];
32
+ };
33
+ backfill?: (phrenPath: string, limit: number) => LookupEvent[];
34
+ now?: () => number;
35
+ }
36
+ export declare class GraphWatch {
37
+ readonly phrenPath: string;
38
+ /** Newest first. */
39
+ activity: ActivityItem[];
40
+ private heat;
41
+ private tail;
42
+ private timer;
43
+ private onEvents;
44
+ private readonly pollMs;
45
+ private readonly injectedTail?;
46
+ private readonly backfillFn;
47
+ private readonly now;
48
+ constructor(phrenPath: string, opts?: GraphWatchOptions);
49
+ get running(): boolean;
50
+ /**
51
+ * Begin tailing. Recent history is loaded into the feed immediately but is
52
+ * never treated as live: it does not pulse and never moves the camera.
53
+ */
54
+ start(onEvents: (items: ActivityItem[]) => void): void;
55
+ stop(): void;
56
+ /** Drain the log. Returns the new items, newest last, and lights their nodes. */
57
+ poll(): ActivityItem[];
58
+ /** 1 right after a node was touched, easing to 0 over HEAT_MS. */
59
+ heatOf(nodeId: string): number;
60
+ /** True while any node is still lit, so the host keeps animating. */
61
+ get hot(): boolean;
62
+ clearActivity(): void;
63
+ }
64
+ /**
65
+ * The graph node an event points at. Findings carry a precomputed `nodeId`
66
+ * (the same id `buildGraph` assigns); everything else falls back to the
67
+ * project node, whose id is the project name.
68
+ */
69
+ export declare function targetNodeId(event: LookupEvent): string | undefined;
70
+ /** "just now", "4s", "2m" — the feed's age column. */
71
+ export declare function formatAge(ms: number): string;
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Watch mode for the terminal graph.
3
+ *
4
+ * Every memory phren lands on — an MCP `search_knowledge` hit, a memory a
5
+ * hook injected before a prompt, a finding just written — is appended to
6
+ * `.runtime/lookup-events.jsonl`. Watch mode tails that log so a graph open
7
+ * in one terminal lights up as an agent works in another: the node pulses,
8
+ * the camera flies to it, and the finding's full text lands in the pane.
9
+ *
10
+ * This module owns the event plumbing only. Drawing lives in graph-view.ts
11
+ * and camera/selection in controller.ts.
12
+ */
13
+ import { lookupEventsLogFile } from "../../shared.js";
14
+ import { readRecentLookups } from "../../governance/activity.js";
15
+ import { LookupTail } from "../../shared/lookup-tail.js";
16
+ /** How long a touched node stays lit, in ms. */
17
+ export const HEAT_MS = 6000;
18
+ /** Events kept for the activity feed. */
19
+ export const ACTIVITY_LIMIT = 60;
20
+ const DEFAULT_POLL_MS = 700;
21
+ /** Backfilled rows shown when watch mode starts, so the feed is never empty. */
22
+ const BACKFILL = 12;
23
+ export class GraphWatch {
24
+ phrenPath;
25
+ /** Newest first. */
26
+ activity = [];
27
+ heat = new Map();
28
+ tail = null;
29
+ timer = null;
30
+ onEvents = null;
31
+ pollMs;
32
+ injectedTail;
33
+ backfillFn;
34
+ now;
35
+ constructor(phrenPath, opts = {}) {
36
+ this.phrenPath = phrenPath;
37
+ this.pollMs = opts.pollMs ?? DEFAULT_POLL_MS;
38
+ this.injectedTail = opts.tail;
39
+ this.backfillFn = opts.backfill ?? readRecentLookups;
40
+ this.now = opts.now ?? (() => Date.now());
41
+ }
42
+ get running() {
43
+ return this.tail !== null;
44
+ }
45
+ /**
46
+ * Begin tailing. Recent history is loaded into the feed immediately but is
47
+ * never treated as live: it does not pulse and never moves the camera.
48
+ */
49
+ start(onEvents) {
50
+ if (this.tail)
51
+ return;
52
+ this.onEvents = onEvents;
53
+ this.tail = this.injectedTail ?? new LookupTail(lookupEventsLogFile(this.phrenPath));
54
+ if (!this.activity.length) {
55
+ try {
56
+ const seenAt = this.now();
57
+ this.activity = this.backfillFn(this.phrenPath, BACKFILL).map((event) => ({
58
+ event,
59
+ seenAt,
60
+ nodeId: targetNodeId(event),
61
+ historical: true,
62
+ }));
63
+ }
64
+ catch {
65
+ this.activity = [];
66
+ }
67
+ }
68
+ if (!this.injectedTail) {
69
+ this.timer = setInterval(() => this.poll(), this.pollMs);
70
+ this.timer.unref?.();
71
+ }
72
+ }
73
+ stop() {
74
+ if (this.timer) {
75
+ clearInterval(this.timer);
76
+ this.timer = null;
77
+ }
78
+ this.tail = null;
79
+ this.onEvents = null;
80
+ this.heat.clear();
81
+ }
82
+ /** Drain the log. Returns the new items, newest last, and lights their nodes. */
83
+ poll() {
84
+ if (!this.tail)
85
+ return [];
86
+ let events;
87
+ try {
88
+ events = this.tail.poll();
89
+ }
90
+ catch {
91
+ return [];
92
+ }
93
+ if (!events.length)
94
+ return [];
95
+ const seenAt = this.now();
96
+ const items = events.map((event) => ({ event, seenAt, nodeId: targetNodeId(event), historical: false }));
97
+ for (const item of items) {
98
+ if (item.nodeId)
99
+ this.heat.set(item.nodeId, seenAt);
100
+ }
101
+ this.activity = [...items].reverse().concat(this.activity).slice(0, ACTIVITY_LIMIT);
102
+ this.onEvents?.(items);
103
+ return items;
104
+ }
105
+ /** 1 right after a node was touched, easing to 0 over HEAT_MS. */
106
+ heatOf(nodeId) {
107
+ const at = this.heat.get(nodeId);
108
+ if (at === undefined)
109
+ return 0;
110
+ const age = this.now() - at;
111
+ if (age >= HEAT_MS) {
112
+ this.heat.delete(nodeId);
113
+ return 0;
114
+ }
115
+ return 1 - age / HEAT_MS;
116
+ }
117
+ /** True while any node is still lit, so the host keeps animating. */
118
+ get hot() {
119
+ if (!this.heat.size)
120
+ return false;
121
+ const now = this.now();
122
+ for (const at of this.heat.values()) {
123
+ if (now - at < HEAT_MS)
124
+ return true;
125
+ }
126
+ this.heat.clear();
127
+ return false;
128
+ }
129
+ clearActivity() {
130
+ this.activity = [];
131
+ this.heat.clear();
132
+ }
133
+ }
134
+ /**
135
+ * The graph node an event points at. Findings carry a precomputed `nodeId`
136
+ * (the same id `buildGraph` assigns); everything else falls back to the
137
+ * project node, whose id is the project name.
138
+ */
139
+ export function targetNodeId(event) {
140
+ if (event.nodeId)
141
+ return event.nodeId;
142
+ return event.project || undefined;
143
+ }
144
+ /** "just now", "4s", "2m" — the feed's age column. */
145
+ export function formatAge(ms) {
146
+ if (ms < 1500)
147
+ return "now";
148
+ if (ms < 60_000)
149
+ return `${Math.round(ms / 1000)}s`;
150
+ if (ms < 3_600_000)
151
+ return `${Math.round(ms / 60_000)}m`;
152
+ return `${Math.round(ms / 3_600_000)}h`;
153
+ }
@@ -4,6 +4,7 @@
4
4
  */
5
5
  import { ShellState } from "../data/access.js";
6
6
  import { type DoctorResultLike, type ShellDeps, type ShellView } from "./types.js";
7
+ import type { GraphController } from "./graph/controller.js";
7
8
  /** Interface for the shell methods that executePalette needs */
8
9
  interface PaletteHost {
9
10
  phrenPath: string;
@@ -39,6 +40,8 @@ export interface NavigationHost extends PaletteHost {
39
40
  prevHealthView: ShellView | undefined;
40
41
  filter: string | undefined;
41
42
  setFilter(value: string): void;
43
+ /** The knowledge-graph view's controller (created on first use). */
44
+ graph(): GraphController;
42
45
  }
43
46
  export declare function executePalette(host: PaletteHost, input: string): Promise<void>;
44
47
  export declare function completeInput(line: string, phrenPath: string, profile: string, state: ShellState): string[];