@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,12 @@
1
+ /**
2
+ * Node glyphs for the terminal graph view.
3
+ *
4
+ * The default set is plain Unicode that every monospace font carries. With
5
+ * `PHREN_ICONS=nerd` the view switches to Nerd Font icons (the Font Awesome
6
+ * block, U+F000–U+F2E0, which has been stable across Nerd Font releases), for
7
+ * terminals running a patched font such as JetBrainsMono Nerd Font.
8
+ */
9
+ import type { NodeKind } from "../../graph-core/types.js";
10
+ export type GlyphSet = Record<NodeKind, string>;
11
+ export declare function iconMode(env?: NodeJS.ProcessEnv): "unicode" | "nerd";
12
+ export declare function graphGlyphs(env?: NodeJS.ProcessEnv): GlyphSet;
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Node glyphs for the terminal graph view.
3
+ *
4
+ * The default set is plain Unicode that every monospace font carries. With
5
+ * `PHREN_ICONS=nerd` the view switches to Nerd Font icons (the Font Awesome
6
+ * block, U+F000–U+F2E0, which has been stable across Nerd Font releases), for
7
+ * terminals running a patched font such as JetBrainsMono Nerd Font.
8
+ */
9
+ const UNICODE = {
10
+ project: "◉",
11
+ finding: "✦",
12
+ task: "▤",
13
+ entity: "❖",
14
+ reference: "▣",
15
+ other: "·",
16
+ };
17
+ const NERD = {
18
+ project: "", // nf-fa-folder
19
+ finding: "", // nf-fa-lightbulb_o
20
+ task: "", // nf-fa-check_square_o
21
+ entity: "", // nf-fa-share_alt (node graph)
22
+ reference: "", // nf-fa-book
23
+ other: "", // nf-fa-circle
24
+ };
25
+ export function iconMode(env = process.env) {
26
+ const raw = (env.PHREN_ICONS || "").trim().toLowerCase();
27
+ return raw === "nerd" || raw === "nerdfont" || raw === "nf" ? "nerd" : "unicode";
28
+ }
29
+ export function graphGlyphs(env = process.env) {
30
+ return iconMode(env) === "nerd" ? NERD : UNICODE;
31
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Renders the terminal graph view: a braille force-graph canvas with a
3
+ * details pane beside it (or a strip beneath it on narrow terminals).
4
+ *
5
+ * Mirrors the web viewer's layout — canvas left, contents pane right — and
6
+ * its colour language: nodes take their topic/kind colour, the selection is
7
+ * amber, search dims everything that does not match.
8
+ */
9
+ import type { GraphController } from "./controller.js";
10
+ /** Word-wrap plain text to `width` cells, at most `maxLines` lines, ellipsised. */
11
+ export declare function wrapText(text: string, width: number, maxLines: number): string[];
12
+ export declare function renderGraphView(controller: GraphController, width: number, height: number): string[];
13
+ /**
14
+ * The one line of graph state worth spending characters on, rendered into the
15
+ * shell header rather than a row of its own. A legend of kind counts told you
16
+ * nothing the colours on screen did not, but whether you are looking at your
17
+ * whole store or a sample of it changes how you read the picture.
18
+ */
19
+ export declare function graphSummary(controller: GraphController): string;
@@ -0,0 +1,585 @@
1
+ /**
2
+ * Renders the terminal graph view: a braille force-graph canvas with a
3
+ * details pane beside it (or a strip beneath it on narrow terminals).
4
+ *
5
+ * Mirrors the web viewer's layout — canvas left, contents pane right — and
6
+ * its colour language: nodes take their topic/kind colour, the selection is
7
+ * amber, search dims everything that does not match.
8
+ */
9
+ import { ACCENT_AMBER, ACCENT_CYAN, BG_COLOR, KIND_COLORS } from "../../graph-core/types.js";
10
+ import { nodeRank } from "../../graph-core/model.js";
11
+ import { displayWidth, padToWidth, style } from "../render.js";
12
+ import { BrailleCanvas, blendHex, hexToSgr } from "./canvas.js";
13
+ import { graphGlyphs } from "./glyphs.js";
14
+ import { formatAge } from "./watch.js";
15
+ const PANE_WIDTH = 34;
16
+ const WIDE_BREAKPOINT = 100;
17
+ /** Ceiling for the narrow-terminal detail strip; it only takes what it fills. */
18
+ const NARROW_STRIP_MAX = 6;
19
+ const DIM_TARGET = "#3a3f55";
20
+ /** Resolved per frame so PHREN_ICONS is honoured without a restart. */
21
+ let KIND_GLYPH = graphGlyphs();
22
+ const KIND_LABEL = {
23
+ project: "project",
24
+ finding: "finding",
25
+ task: "task",
26
+ entity: "fragment",
27
+ reference: "reference",
28
+ other: "node",
29
+ };
30
+ const HEALTH_COLOR = {
31
+ healthy: "#3ae374",
32
+ decaying: "#ffb648",
33
+ stale: "#ff5470",
34
+ };
35
+ function sgr(hex, extra = "") {
36
+ return `${hexToSgr(hex)}${extra}`;
37
+ }
38
+ function colored(hex, text) {
39
+ return `${hexToSgr(hex)}${text}\x1b[0m`;
40
+ }
41
+ /** Word-wrap plain text to `width` cells, at most `maxLines` lines, ellipsised. */
42
+ export function wrapText(text, width, maxLines) {
43
+ const words = text.split(/\s+/).filter(Boolean);
44
+ const lines = [];
45
+ let current = "";
46
+ for (const word of words) {
47
+ const candidate = current ? `${current} ${word}` : word;
48
+ if (displayWidth(candidate) <= width) {
49
+ current = candidate;
50
+ continue;
51
+ }
52
+ if (current)
53
+ lines.push(current);
54
+ current = displayWidth(word) > width ? `${sliceWidth(word, width - 1)}…` : word;
55
+ if (lines.length >= maxLines)
56
+ break;
57
+ }
58
+ if (current && lines.length < maxLines)
59
+ lines.push(current);
60
+ if (lines.length > maxLines)
61
+ lines.length = maxLines;
62
+ const complete = lines.join(" ") === words.join(" ");
63
+ if (lines.length === maxLines && !complete && !lines[maxLines - 1].endsWith("…")) {
64
+ const last = lines[maxLines - 1];
65
+ lines[maxLines - 1] = displayWidth(last) >= width ? `${sliceWidth(last, width - 1)}…` : `${last}…`;
66
+ }
67
+ return lines;
68
+ }
69
+ function sliceWidth(text, width) {
70
+ let out = "";
71
+ let used = 0;
72
+ for (const ch of text) {
73
+ const w = displayWidth(ch);
74
+ if (used + w > width)
75
+ break;
76
+ out += ch;
77
+ used += w;
78
+ }
79
+ return out;
80
+ }
81
+ /** Braille radius for a node from its viewer size. */
82
+ function dotRadius(node, selected) {
83
+ const base = node.kind === "project" ? 3 : node.size >= 16 ? 2 : node.size >= 10 ? 1 : 0;
84
+ return selected ? base + 1 : base;
85
+ }
86
+ export function renderGraphView(controller, width, height) {
87
+ KIND_GLYPH = graphGlyphs();
88
+ if (controller.status === "loading" || controller.status === "idle")
89
+ return centered(width, height, [
90
+ colored(ACCENT_CYAN, "⠿ building your knowledge graph…"),
91
+ style.dim("scanning findings, tasks, fragments and references"),
92
+ ]);
93
+ if (controller.status === "error")
94
+ return centered(width, height, [
95
+ style.boldRed("graph build failed"),
96
+ style.dim(controller.errorText || "unknown error"),
97
+ style.dim("press r to retry"),
98
+ ]);
99
+ if (controller.status === "empty")
100
+ return centered(width, height, [
101
+ style.bold("nothing to draw yet"),
102
+ style.dim("add a project and some findings, then come back"),
103
+ ]);
104
+ const wide = width >= WIDE_BREAKPOINT;
105
+ const selected = controller.selectedId ? controller.model.nodeById.get(controller.selectedId) ?? null : null;
106
+ // Build the strip first so it takes only the rows it fills; every row it
107
+ // gives back goes to the graph, which is the part worth the space.
108
+ const strip = !wide && selected ? renderStrip(controller, selected, width, NARROW_STRIP_MAX) : [];
109
+ const canvasCols = wide ? width - PANE_WIDTH - 1 : width;
110
+ const canvasRows = Math.max(4, height - strip.length);
111
+ const canvasLines = drawCanvas(controller, canvasCols, canvasRows, selected);
112
+ if (wide) {
113
+ const pane = renderPane(controller, selected, PANE_WIDTH, canvasRows);
114
+ const divider = style.dim("│");
115
+ return canvasLines.map((line, i) => `${line}${divider}${padToWidth(pane[i] ?? "", PANE_WIDTH)}`);
116
+ }
117
+ return [...canvasLines, ...strip.map((line) => padToWidth(line, width))];
118
+ }
119
+ function centered(width, height, lines) {
120
+ const out = [];
121
+ const top = Math.max(0, Math.floor((height - lines.length) / 2));
122
+ for (let i = 0; i < height; i++) {
123
+ const line = lines[i - top];
124
+ if (!line) {
125
+ out.push(" ".repeat(width));
126
+ continue;
127
+ }
128
+ const pad = Math.max(0, Math.floor((width - displayWidth(line)) / 2));
129
+ out.push(padToWidth(" ".repeat(pad) + line, width));
130
+ }
131
+ return out;
132
+ }
133
+ function drawCanvas(controller, cols, rows, selected) {
134
+ const canvas = new BrailleCanvas(cols, rows);
135
+ controller.setViewport(canvas.dotWidth, canvas.dotHeight);
136
+ const positions = controller.positions;
137
+ const searching = Boolean(controller.search.query);
138
+ const matches = controller.search.matchIds;
139
+ const placed = [];
140
+ const projected = new Map();
141
+ for (const node of controller.visible.nodes) {
142
+ const p = positions.get(node.id);
143
+ if (!p)
144
+ continue;
145
+ const d = controller.project(p);
146
+ projected.set(node.id, d);
147
+ placed.push({ node, x: d.x, y: d.y });
148
+ }
149
+ const isLit = (id) => !searching || matches.has(id);
150
+ // Edges first so node dots win the cell colour.
151
+ for (const link of controller.visible.links) {
152
+ const a = projected.get(link.source);
153
+ const b = projected.get(link.target);
154
+ if (!a || !b)
155
+ continue;
156
+ const touchesSelected = selected !== null && (link.source === selected.id || link.target === selected.id);
157
+ const color = edgeColor(controller, link, touchesSelected, isLit(link.source) && isLit(link.target));
158
+ canvas.line(a.x, a.y, b.x, b.y, color, { z: touchesSelected ? 2 : 0, dotted: link.kind === "contradicts" });
159
+ }
160
+ const watching = controller.watchEnabled && controller.watch.running;
161
+ const heatOf = (id) => (watching ? controller.watch.heatOf(id) : 0);
162
+ for (const { node, x, y } of placed) {
163
+ const isSelected = selected?.id === node.id;
164
+ const heat = heatOf(node.id);
165
+ let color = node.baseColor;
166
+ if (isSelected)
167
+ color = ACCENT_AMBER;
168
+ else if (searching && !matches.has(node.id))
169
+ color = blendHex(node.baseColor, DIM_TARGET, 0.7);
170
+ // A just-touched node pulses toward the live cyan and swells a little.
171
+ if (heat > 0)
172
+ color = blendHex(color, ACCENT_CYAN, 0.3 + heat * 0.55);
173
+ const radius = dotRadius(node, isSelected) + (heat > 0.35 ? 1 : 0);
174
+ canvas.disc(x, y, radius, color, isSelected ? 4 : heat > 0 ? 3 : node.kind === "project" ? 3 : 1);
175
+ // A ring around the hottest nodes, so a hit reads at a glance.
176
+ if (heat > 0.55) {
177
+ const r = radius + 2;
178
+ for (let a = 0; a < 16; a++) {
179
+ const t = (a / 16) * Math.PI * 2;
180
+ canvas.setDot(x + Math.cos(t) * r, y + Math.sin(t) * r * 0.9, blendHex(ACCENT_CYAN, BG_COLOR, 1 - heat), 2);
181
+ }
182
+ }
183
+ }
184
+ // Glyphs and labels are drawn in two separate passes, and the order matters.
185
+ // Drawing a glyph and its label per node let a later node's glyph land inside
186
+ // an earlier node's label, which is what produced `sear◉hweb` on a busy
187
+ // canvas. Every glyph goes down first; labels then treat those cells as
188
+ // occupied and route around them.
189
+ const neighborIndex = new Map();
190
+ if (selected)
191
+ controller.neighborsOf(selected.id).slice(0, 9).forEach((node, i) => neighborIndex.set(node.id, i + 1));
192
+ const currentHit = searching ? controller.search.results[controller.search.index]?.id : undefined;
193
+ const zoomedIn = Math.min(controller.camera.scaleX, controller.camera.scaleY) >= 5;
194
+ const ranked = placed.slice().sort((a, b) => labelPriority(controller, b.node, selected, neighborIndex) - labelPriority(controller, a.node, selected, neighborIndex));
195
+ const onCanvas = ({ x, y }) => {
196
+ const col = Math.floor(x / 2);
197
+ const row = Math.floor(y / 4);
198
+ return col < 0 || col >= cols || row < 0 || row >= rows ? null : { col, row };
199
+ };
200
+ // Pass 1 — glyphs.
201
+ for (const item of ranked) {
202
+ const at = onCanvas(item);
203
+ if (!at)
204
+ continue;
205
+ const { node } = item;
206
+ const isSelected = selected?.id === node.id;
207
+ const lit = isLit(node.id);
208
+ const glyphColor = isSelected ? ACCENT_AMBER : lit ? node.baseColor : blendHex(node.baseColor, DIM_TARGET, 0.7);
209
+ const number = neighborIndex.get(node.id);
210
+ if (isSelected)
211
+ canvas.putText(at.col, at.row, "◆", sgr(ACCENT_AMBER, "\x1b[1m"));
212
+ else if (node.kind === "project")
213
+ canvas.putText(at.col, at.row, KIND_GLYPH.project, sgr(glyphColor, "\x1b[1m"));
214
+ else if (number !== undefined)
215
+ canvas.putText(at.col, at.row, String(number), sgr(ACCENT_CYAN, "\x1b[1m"));
216
+ }
217
+ // Every project used to force a label, so forty of them piled into one
218
+ // unreadable heap. Only as many as the canvas can carry get named, largest
219
+ // first; the rest still show their glyph.
220
+ const projectLabelBudget = Math.max(4, Math.floor((cols * rows) / 120));
221
+ const namedProjects = new Set(placed
222
+ .filter(({ node }) => node.kind === "project")
223
+ .sort((a, b) => projectWeight(b.node) - projectWeight(a.node))
224
+ .slice(0, projectLabelBudget)
225
+ .map(({ node }) => node.id));
226
+ /** A label needs a clear cell either side, or two labels read as one word. */
227
+ const hasRoom = (col, row, w, avoidDots) => {
228
+ if (col < 0 || col + w > cols)
229
+ return false;
230
+ const start = Math.max(0, col - 1);
231
+ const end = Math.min(cols, col + w + 1);
232
+ return canvas.isFree(start, row, end - start, avoidDots);
233
+ };
234
+ // Pass 2 — labels.
235
+ const labelBudget = searching ? 14 : zoomedIn ? Math.max(8, Math.floor((cols * rows) / 60)) : Math.max(4, Math.floor((cols * rows) / 220));
236
+ let labels = 0;
237
+ for (const item of ranked) {
238
+ const at = onCanvas(item);
239
+ if (!at)
240
+ continue;
241
+ const { node } = item;
242
+ const { col, row } = at;
243
+ const isSelected = selected?.id === node.id;
244
+ const lit = isLit(node.id);
245
+ const glyphColor = isSelected ? ACCENT_AMBER : lit ? node.baseColor : blendHex(node.baseColor, DIM_TARGET, 0.7);
246
+ const number = neighborIndex.get(node.id);
247
+ const forced = isSelected
248
+ || node.id === currentHit
249
+ || heatOf(node.id) > 0
250
+ || (node.kind === "project" ? namedProjects.has(node.id) : node.forceLabel);
251
+ const wanted = forced || number !== undefined || (lit && labels < labelBudget && (zoomedIn || searching));
252
+ if (!wanted)
253
+ continue;
254
+ const maxLabel = node.kind === "project" ? 20 : number !== undefined ? 14 : 18;
255
+ const text = sliceWidth(node.label, maxLabel);
256
+ const w = displayWidth(text);
257
+ const labelSgr = isSelected
258
+ ? `${hexToSgr(BG_COLOR)}\x1b[48;2;255;209;102m\x1b[1m`
259
+ : node.kind === "project"
260
+ ? sgr(glyphColor, "\x1b[1m")
261
+ : number !== undefined
262
+ ? sgr(lit ? blendHex(node.baseColor, "#ffffff", 0.35) : blendHex(node.baseColor, DIM_TARGET, 0.6))
263
+ : sgr(lit ? blendHex(node.baseColor, "#ffffff", 0.2) : blendHex(node.baseColor, DIM_TARGET, 0.6));
264
+ const slots = [[col + 2, row], [col - w - 1, row], [col + 2, row - 1], [col + 2, row + 1], [col - w - 1, row - 1], [col - w - 1, row + 1]];
265
+ // Clean slots first (no text, no dots); forced labels may cover dots as a
266
+ // last resort, but never another label.
267
+ const placedAt = slots.find(([c, r]) => hasRoom(c, r, w, true)) ?? (forced ? slots.find(([c, r]) => hasRoom(c, r, w, false)) : undefined);
268
+ if (!placedAt)
269
+ continue;
270
+ canvas.putText(placedAt[0], placedAt[1], text, labelSgr);
271
+ if (!forced)
272
+ labels++;
273
+ }
274
+ // Agents sit beside the project they are working in. They are runtime state,
275
+ // not memory, so they decorate a node rather than becoming one.
276
+ if (controller.agents.enabled && controller.agents.agents.length) {
277
+ const highlighted = controller.agents.current;
278
+ for (const [project, agents] of controller.agents.byProject()) {
279
+ const p = positions.get(project);
280
+ if (!p)
281
+ continue;
282
+ const d = controller.project(p);
283
+ const col = Math.floor(d.x / 2);
284
+ const row = Math.floor(d.y / 4) - 1;
285
+ if (col < 0 || col >= cols || row < 0 || row >= rows)
286
+ continue;
287
+ const busiest = agents.find((a) => a.status === "working") ?? agents[0];
288
+ const isHighlighted = agents.some((a) => a.id === highlighted?.id);
289
+ const mark = agents.length > 1 ? `▲${agents.length}` : "▲";
290
+ const color = AGENT_STATUS_COLOR[busiest.status] ?? "#7f8db3";
291
+ const marker = isHighlighted
292
+ ? `${hexToSgr(BG_COLOR)}\x1b[48;2;58;227;116m\x1b[1m`
293
+ : sgr(color, "\x1b[1m");
294
+ canvas.putText(col, row, mark, marker);
295
+ }
296
+ }
297
+ if (controller.refreshing) {
298
+ const badge = " ⟳ refreshing ";
299
+ canvas.putText(cols - displayWidth(badge), 0, badge, sgr(ACCENT_CYAN, "\x1b[2m"));
300
+ }
301
+ return canvas.render();
302
+ }
303
+ function edgeColor(controller, link, touchesSelected, lit) {
304
+ if (touchesSelected)
305
+ return ACCENT_AMBER;
306
+ let base;
307
+ if (link.kind === "fragment")
308
+ base = blendHex(ACCENT_CYAN, BG_COLOR, 0.45);
309
+ else if (link.kind === "contradicts")
310
+ base = "#ff5470";
311
+ else if (link.kind === "supersedes")
312
+ base = "#8a93b8";
313
+ else {
314
+ const leaf = controller.model.nodeById.get(link.target)?.kind === "project" ? link.source : link.target;
315
+ const node = controller.model.nodeById.get(leaf);
316
+ base = blendHex(node?.baseColor ?? KIND_COLORS.other, BG_COLOR, 0.55);
317
+ }
318
+ return lit ? base : blendHex(base, BG_COLOR, 0.6);
319
+ }
320
+ /** How much of the store a project holds; decides which get named when space is short. */
321
+ function projectWeight(node) {
322
+ return (node.findingCount ?? 0) + (node.taskCount ?? 0) + (node.refCount ?? 0);
323
+ }
324
+ function labelPriority(controller, node, selected, neighborIndex) {
325
+ let score = nodeRank(node, controller.filters, controller.model.scores);
326
+ if (selected?.id === node.id)
327
+ score += 100000;
328
+ if (node.kind === "project")
329
+ score += 50000;
330
+ if (neighborIndex.has(node.id))
331
+ score += 30000 - (neighborIndex.get(node.id) ?? 0);
332
+ if (controller.search.matchIds.has(node.id))
333
+ score += 20000;
334
+ return score;
335
+ }
336
+ /**
337
+ * The one line of graph state worth spending characters on, rendered into the
338
+ * shell header rather than a row of its own. A legend of kind counts told you
339
+ * nothing the colours on screen did not, but whether you are looking at your
340
+ * whole store or a sample of it changes how you read the picture.
341
+ */
342
+ export function graphSummary(controller) {
343
+ if (controller.status !== "ready")
344
+ return "";
345
+ const shown = controller.visible.nodes.length;
346
+ const total = controller.model.rawNodes.length;
347
+ const n = (v) => v.toLocaleString("en-US");
348
+ const capped = shown < total ? `${n(shown)} of ${n(total)} nodes` : `${n(shown)} nodes`;
349
+ const parts = [capped, `${n(controller.visible.links.length)} edges`];
350
+ if (controller.watchEnabled && controller.watch.running)
351
+ parts.push(`${colored(ACCENT_CYAN, "◉")}${style.dim(" live")}`);
352
+ return parts.join(style.dim(" · "));
353
+ }
354
+ function healthDot(node) {
355
+ return `${colored(HEALTH_COLOR[node.health], "●")} ${node.health}`;
356
+ }
357
+ function renderPane(controller, selected, width, height) {
358
+ const inner = width - 2;
359
+ const watching = controller.watchEnabled && controller.watch.running;
360
+ const lines = [];
361
+ const push = (line = "") => { if (lines.length < height)
362
+ lines.push(` ${line}`); };
363
+ const row = (label, value) => push(`${style.dim(label.padEnd(9))}${value}`);
364
+ if (selected) {
365
+ const detail = controller.detail(selected.id);
366
+ push(`${colored(selected.kind === "project" ? KIND_COLORS.project : selected.baseColor, KIND_GLYPH[selected.kind])} ${style.bold(KIND_LABEL[selected.kind])}${selected.kind === "task" && selected.section ? style.dim(` ${selected.section.toLowerCase()}`) : ""}`);
367
+ for (const line of wrapText(selected.fullLabel || selected.label, inner, watching ? 7 : 4))
368
+ push(line);
369
+ push();
370
+ if (selected.kind !== "project" && selected.project)
371
+ row("project", style.cyan(selected.project));
372
+ if (selected.kind === "project") {
373
+ row("findings", String(selected.findingCount ?? 0));
374
+ row("tasks", String(selected.taskCount ?? 0));
375
+ if (selected.store && selected.store !== "primary")
376
+ row("store", selected.store);
377
+ }
378
+ if (selected.topicLabel || selected.topicSlug)
379
+ row("topic", colored(selected.baseColor, selected.topicLabel || selected.topicSlug || ""));
380
+ if (selected.entityType)
381
+ row("type", selected.entityType);
382
+ if (selected.priority)
383
+ row("priority", selected.priority);
384
+ if (selected.date)
385
+ row("date", selected.date);
386
+ row("health", healthDot(selected));
387
+ if (detail?.qualityScore != null)
388
+ row("quality", `${Math.round(detail.qualityScore * 100)}%`);
389
+ if (detail?.score?.helpful)
390
+ row("helpful", `${detail.score.helpful}×`);
391
+ if (detail) {
392
+ const c = detail.connections;
393
+ const bits = [
394
+ c.projects ? `${c.projects} proj` : "",
395
+ c.findings ? `${c.findings} find` : "",
396
+ c.tasks ? `${c.tasks} task` : "",
397
+ c.entities ? `${c.entities} frag` : "",
398
+ c.references ? `${c.references} ref` : "",
399
+ ].filter(Boolean);
400
+ row("links", `${c.total}${bits.length ? style.dim(` ${bits.join(" ")}`) : ""}`);
401
+ }
402
+ const docs = (selected.refDocs ?? []).map((ref) => ref.doc);
403
+ if (docs.length && selected.kind !== "finding" && selected.kind !== "task") {
404
+ row("docs", sliceWidth(docs[0], inner - 9));
405
+ for (const doc of docs.slice(1, 3))
406
+ push(`${" ".repeat(9)}${sliceWidth(doc, inner - 9)}`);
407
+ if (docs.length > 3)
408
+ push(`${" ".repeat(9)}${style.dim(`+${docs.length - 3} more`)}`);
409
+ }
410
+ const neighbors = controller.neighborsOf(selected.id);
411
+ if (neighbors.length) {
412
+ push();
413
+ push(style.dim(`neighbours ${style.dim(`(1-9 jump)`)}`));
414
+ const budget = Math.max(0, height - lines.length - 1);
415
+ neighbors.slice(0, Math.min(9, budget)).forEach((node, i) => {
416
+ push(`${style.boldCyan(String(i + 1))} ${colored(node.baseColor, KIND_GLYPH[node.kind])} ${sliceWidth(node.label, inner - 4)}`);
417
+ });
418
+ if (neighbors.length > 9)
419
+ push(style.dim(` +${neighbors.length - 9} more`));
420
+ }
421
+ const agentBudget = height - lines.length - 1;
422
+ if (agentBudget > 3)
423
+ for (const line of agentLines(controller, inner, agentBudget))
424
+ push(line);
425
+ if (watching) {
426
+ const budget = height - lines.length - 1;
427
+ if (budget > 3)
428
+ for (const line of activityLines(controller, inner, budget))
429
+ push(line);
430
+ }
431
+ }
432
+ else {
433
+ const total = controller.model.rawNodes.length;
434
+ const shown = controller.visible.nodes.length;
435
+ push(`${colored(ACCENT_CYAN, "❖")} ${style.bold("knowledge graph")}${controller.refreshing ? style.dim(" ⟳") : ""}${watching ? ` ${colored(ACCENT_CYAN, "◉")}${style.dim(" live")}` : ""}`);
436
+ push(style.dim(shown === total ? `${shown} nodes · ${controller.visible.links.length} edges` : `${shown} of ${total} nodes · ${controller.visible.links.length} edges`));
437
+ push();
438
+ row("filter", `${controller.preset.name}${style.dim(" f")}`);
439
+ row("focus", `${controller.focusedProject ? style.cyan(controller.focusedProject) : style.dim("all projects")}${style.dim(" [ ]")}`);
440
+ row("search", controller.search.query
441
+ ? `${style.yellow(controller.search.query)} ${style.dim(`${controller.search.results.length} hit${controller.search.results.length === 1 ? "" : "s"}`)}`
442
+ : `${style.dim("—")}${style.dim(" /")}`);
443
+ push();
444
+ const projects = controller.projects;
445
+ if (projects.length) {
446
+ push(style.dim("projects"));
447
+ const budget = Math.max(0, height - lines.length - 9);
448
+ for (const project of projects.slice(0, budget)) {
449
+ const name = project.project || project.id;
450
+ const isFocus = controller.focusedProject === name;
451
+ push(`${colored(project.baseColor, KIND_GLYPH.project)} ${isFocus ? style.boldCyan(sliceWidth(name, inner - 12)) : sliceWidth(name, inner - 12)} ${style.dim(`${project.findingCount ?? 0}✦ ${project.taskCount ?? 0}▤`)}`);
452
+ }
453
+ if (projects.length > budget)
454
+ push(style.dim(` +${projects.length - budget} more`));
455
+ push();
456
+ }
457
+ const agentBudget = height - lines.length - 1;
458
+ if (agentBudget > 3)
459
+ for (const line of agentLines(controller, inner, agentBudget))
460
+ push(line);
461
+ if (watching) {
462
+ const budget = height - lines.length - 1;
463
+ if (budget > 3) {
464
+ for (const line of activityLines(controller, inner, budget))
465
+ push(line);
466
+ while (lines.length < height)
467
+ lines.push("");
468
+ return lines.slice(0, height);
469
+ }
470
+ }
471
+ const k = (s) => style.boldCyan(s);
472
+ const d = (s) => style.dim(s);
473
+ push(`${k("↑↓←→")} ${d("walk")} ${k("↵")} ${d("select")}`);
474
+ push(`${k("1-9")} ${d("jump to neighbour")}`);
475
+ push(`${k("/")} ${d("search")} ${k("n")}${d("/")}${k("N")} ${d("next/prev")}`);
476
+ push(`${k("f")} ${d("filter")} ${k("[ ]")} ${d("project")}`);
477
+ push(`${k("+ -")} ${d("zoom")} ${k("0")} ${d("fit")} ${k("r")} ${d("relayout")}`);
478
+ push(`${k("⇧↑↓←→")} ${d("pan")} ${k("o")} ${d("3D viewer")}`);
479
+ }
480
+ while (lines.length < height)
481
+ lines.push("");
482
+ return lines.slice(0, height);
483
+ }
484
+ const AGENT_STATUS_COLOR = {
485
+ working: "#3ae374",
486
+ idle: "#48b2ff",
487
+ done: "#5c6b8a",
488
+ error: "#ff5470",
489
+ };
490
+ const SOURCE_COLOR = {
491
+ search: ACCENT_CYAN,
492
+ inject: ACCENT_AMBER,
493
+ write: "#3ae374",
494
+ };
495
+ /**
496
+ * The live feed: what phren has just landed on, newest first. Each event gets
497
+ * a meta line and as much of the memory's text as the pane can carry, because
498
+ * the point of watching is reading what was found, not just seeing it blink.
499
+ */
500
+ /**
501
+ * Who is working, and where. Rendered above the activity feed so the pane reads
502
+ * top to bottom as: what is selected, who is on it, what phren just touched.
503
+ */
504
+ function agentLines(controller, inner, budget) {
505
+ const agents = controller.agents.agents;
506
+ const out = [];
507
+ if (!controller.agents.enabled)
508
+ return out;
509
+ out.push("");
510
+ out.push(`${colored(agents.length ? "#3ae374" : "#5c6b8a", "▲")} ${style.dim(`agents${agents.length ? "" : " — none running"}`)}`);
511
+ const current = controller.agents.current;
512
+ for (const agent of agents) {
513
+ if (out.length >= budget - 1)
514
+ break;
515
+ const isCurrent = agent.id === current?.id;
516
+ const color = AGENT_STATUS_COLOR[agent.status] ?? "#7f8db3";
517
+ const marker = isCurrent ? style.boldCyan("›") : " ";
518
+ out.push(`${marker}${colored(color, "●")} ${sliceWidth(agent.label, inner - 3)}`);
519
+ if (out.length >= budget - 1)
520
+ break;
521
+ const where = agent.project ?? style.dim("outside phren");
522
+ out.push(` ${style.dim(agent.status)} ${style.dim("·")} ${agent.project ? style.cyan(where) : where}`);
523
+ }
524
+ if (agents.length)
525
+ out.push(style.dim(" tab cycle · ↵ focus"));
526
+ return out.slice(0, budget);
527
+ }
528
+ function activityLines(controller, inner, budget) {
529
+ const out = [];
530
+ const now = Date.now();
531
+ const live = controller.watch.hot;
532
+ out.push("");
533
+ out.push(`${colored(live ? ACCENT_CYAN : "#5c6b8a", live ? "◉" : "○")} ${style.dim("activity")}`);
534
+ if (!controller.watch.activity.length) {
535
+ out.push(style.dim(" nothing yet — run a search"));
536
+ out.push(style.dim(" in another terminal"));
537
+ return out.slice(0, budget);
538
+ }
539
+ for (const item of controller.watch.activity) {
540
+ if (out.length >= budget - 1)
541
+ break;
542
+ const age = item.historical ? "" : formatAge(now - item.seenAt);
543
+ const source = item.event.source || "lookup";
544
+ const color = SOURCE_COLOR[source] ?? "#7f8db3";
545
+ const heat = item.nodeId ? controller.watch.heatOf(item.nodeId) : 0;
546
+ const meta = `${style.dim(age.padEnd(4))}${colored(color, source)} ${style.dim("·")} ${style.cyan(sliceWidth(item.event.project, inner - age.length - source.length - 4))}`;
547
+ out.push(heat > 0.5 ? `${meta}` : meta);
548
+ const text = item.event.snippet || item.event.filename || "";
549
+ if (text && out.length < budget - 1) {
550
+ const wrapped = wrapText(text, inner - 2, heat > 0 ? 3 : 2);
551
+ for (const line of wrapped) {
552
+ if (out.length >= budget - 1)
553
+ break;
554
+ out.push(` ${heat > 0 ? colored(blendHex("#e2e8f0", ACCENT_CYAN, heat * 0.7), line) : style.dim(line)}`);
555
+ }
556
+ }
557
+ }
558
+ return out.slice(0, budget);
559
+ }
560
+ function renderStrip(controller, selected, width, rows) {
561
+ const detail = controller.detail(selected.id);
562
+ const lines = [];
563
+ const head = [
564
+ `${colored(selected.baseColor, KIND_GLYPH[selected.kind])} ${style.bold(KIND_LABEL[selected.kind])}`,
565
+ selected.project && selected.kind !== "project" ? style.cyan(selected.project) : "",
566
+ selected.topicLabel || selected.topicSlug || "",
567
+ healthDot(selected),
568
+ detail ? style.dim(`${detail.connections.total} links`) : "",
569
+ ].filter(Boolean);
570
+ lines.push(` ${head.join(style.dim(" · "))}`);
571
+ for (const line of wrapText(selected.fullLabel || selected.label, width - 2, 2))
572
+ lines.push(` ${line}`);
573
+ const neighbors = controller.neighborsOf(selected.id).slice(0, 9);
574
+ if (neighbors.length) {
575
+ const items = neighbors.map((node, i) => `${style.boldCyan(String(i + 1))} ${colored(node.baseColor, KIND_GLYPH[node.kind])} ${sliceWidth(node.label, 14)}`);
576
+ let line = " ";
577
+ for (const item of items) {
578
+ if (displayWidth(line + item) + 2 > width)
579
+ break;
580
+ line += `${item} `;
581
+ }
582
+ lines.push(line.trimEnd());
583
+ }
584
+ return lines.slice(0, rows);
585
+ }