@phren/cli 0.1.45 → 0.1.47

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 (52) 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/namespaces-utils.d.ts +5 -0
  10. package/dist/cli/namespaces-utils.js +12 -12
  11. package/dist/cli/search.js +29 -0
  12. package/dist/cli-registry.d.ts +1 -1
  13. package/dist/cli-registry.js +1 -0
  14. package/dist/content/learning.js +24 -1
  15. package/dist/editor/buffer.d.ts +48 -0
  16. package/dist/editor/buffer.js +312 -0
  17. package/dist/editor/launch.d.ts +41 -0
  18. package/dist/editor/launch.js +92 -0
  19. package/dist/editor/save.d.ts +15 -0
  20. package/dist/editor/save.js +70 -0
  21. package/dist/generated/memory-ui-graph.browser.js +69 -69
  22. package/dist/graph-core/model.js +99 -9
  23. package/dist/memory-ui-graph.runtime.js +69 -69
  24. package/dist/phren-art.d.ts +7 -0
  25. package/dist/phren-art.js +6 -41
  26. package/dist/shared/lookup-tail.d.ts +35 -0
  27. package/dist/shared/lookup-tail.js +100 -0
  28. package/dist/shell/editor-view.d.ts +8 -0
  29. package/dist/shell/editor-view.js +67 -0
  30. package/dist/shell/entry.js +31 -4
  31. package/dist/shell/graph/agents.d.ts +48 -0
  32. package/dist/shell/graph/agents.js +152 -0
  33. package/dist/shell/graph/controller.d.ts +40 -2
  34. package/dist/shell/graph/controller.js +149 -12
  35. package/dist/shell/graph/graph-view.d.ts +7 -0
  36. package/dist/shell/graph/graph-view.js +227 -50
  37. package/dist/shell/graph/layout.d.ts +21 -2
  38. package/dist/shell/graph/layout.js +79 -11
  39. package/dist/shell/graph/watch.d.ts +71 -0
  40. package/dist/shell/graph/watch.js +153 -0
  41. package/dist/shell/input.d.ts +24 -0
  42. package/dist/shell/input.js +76 -7
  43. package/dist/shell/render-api.js +1 -0
  44. package/dist/shell/render.js +12 -2
  45. package/dist/shell/shell.d.ts +25 -1
  46. package/dist/shell/shell.js +134 -5
  47. package/dist/shell/startup.d.ts +3 -0
  48. package/dist/shell/startup.js +8 -0
  49. package/dist/shell/view.d.ts +5 -1
  50. package/dist/shell/view.js +80 -75
  51. package/dist/ui/server.js +6 -56
  52. package/package.json +1 -1
@@ -7,9 +7,26 @@ import { logger } from "../logger.js";
7
7
  import { resultMsg, defaultRunHooks, defaultRunUpdate, defaultRunRelink, } from "./palette.js";
8
8
  import { runDoctor } from "../link/link.js";
9
9
  import { renderShell, } from "./view.js";
10
+ import { renderWidth } from "./render.js";
10
11
  import { executePalette, completeInput as completeInputFn, getListItems, handleNavigateKey, applyViewShortcut, } from "./input.js";
11
12
  import { errorMessage } from "../utils.js";
12
13
  import { GraphController } from "./graph/controller.js";
14
+ import { applyEditorKey, createEditorState, editorText } from "../editor/buffer.js";
15
+ import { saveEditedFile } from "../editor/save.js";
16
+ import { renderEditor } from "./editor-view.js";
17
+ import { syncSkillLinksForScope } from "../skill/files.js";
18
+ /** How far the help should scroll for a key, or 0 when it should close instead. */
19
+ function helpScrollDelta(key) {
20
+ switch (key) {
21
+ case "\x1b[B":
22
+ case "j": return 1;
23
+ case "\x1b[A":
24
+ case "k": return -1;
25
+ case "\x1b[6~": return 10;
26
+ case "\x1b[5~": return -10;
27
+ default: return 0;
28
+ }
29
+ }
13
30
  /** Remove the final character, keeping surrogate pairs and combining marks intact. */
14
31
  function dropLastCharacter(s) {
15
32
  if (!s)
@@ -33,16 +50,22 @@ export class PhrenShell {
33
50
  pendingConfirm;
34
51
  undoStack = [];
35
52
  navMode = "navigate";
53
+ editor;
36
54
  inputBuf = "";
37
55
  inputCtx = "";
38
56
  inputMqId = "";
39
57
  cursorMap = {};
40
58
  viewScrollMap = {};
41
59
  healthLineCount = 0;
60
+ helpScroll = 0;
42
61
  _subsectionsCache = null;
43
62
  _graph;
44
63
  repaintHandler = null;
64
+ suspendHandler = null;
65
+ /** `--live` / `--no-live`; undefined leaves watch mode at its default. */
66
+ graphLive;
45
67
  get mode() { return this.navMode; }
68
+ get editorState() { return this.editor?.state; }
46
69
  get inputBuffer() { return this.inputBuf; }
47
70
  get filter() { return this.state.filter; }
48
71
  constructor(phrenPath, profile, deps = {
@@ -59,12 +82,15 @@ export class PhrenShell {
59
82
  // last session happened to leave behind; without one we always land home.
60
83
  if (startup.project)
61
84
  this.state.project = startup.project;
85
+ this.graphLive = startup.live;
62
86
  this.state.view = startup.view ?? "Projects";
63
87
  this.message = startup.notice
64
88
  ? ` ${style.yellow("⚠")} ${startup.notice}`
65
- : this.state.project
66
- ? ` Dashboard ready — active context ${style.boldCyan(this.state.project)}`
67
- : ` Dashboard ready — choose a project with ${style.boldCyan("↵")} or stay global`;
89
+ : this.state.view === "Graph"
90
+ ? ""
91
+ : this.state.project
92
+ ? ` Dashboard ready — active context ${style.boldCyan(this.state.project)}`
93
+ : ` Dashboard ready — choose a project with ${style.boldCyan("↵")} or stay global`;
68
94
  }
69
95
  close() { this._graph?.dispose(); saveShellState(this.phrenPath, this.state); }
70
96
  setMessage(msg) { this.message = msg; }
@@ -77,9 +103,26 @@ export class PhrenShell {
77
103
  this.repaintHandler = handler;
78
104
  this._graph?.setRepaintHook(handler);
79
105
  }
106
+ /**
107
+ * Let the host lend the terminal to a child process. Without one — a non-TTY
108
+ * host, or an embedder — callers fall back to telling the user the path.
109
+ */
110
+ setSuspendHandler(handler) {
111
+ this.suspendHandler = handler;
112
+ }
113
+ get canSuspend() {
114
+ return this.suspendHandler !== null;
115
+ }
116
+ /** Run `fn` with the terminal released. Resolves false when that is impossible. */
117
+ async suspend(fn) {
118
+ if (!this.suspendHandler)
119
+ return false;
120
+ await this.suspendHandler(fn);
121
+ return true;
122
+ }
80
123
  graph() {
81
124
  if (!this._graph) {
82
- this._graph = new GraphController(this.phrenPath, this.profile);
125
+ this._graph = new GraphController(this.phrenPath, this.profile, { watchEnabled: this.graphLive });
83
126
  this._graph.setRepaintHook(this.repaintHandler);
84
127
  }
85
128
  return this._graph;
@@ -210,6 +253,71 @@ export class PhrenShell {
210
253
  }
211
254
  }
212
255
  }
256
+ // ── Modal editor ───────────────────────────────────────────────────────
257
+ /** Open a file in the built-in editor. Returns false if it cannot be read. */
258
+ openEditor(filePath, label, kind, scope) {
259
+ let content = "";
260
+ try {
261
+ content = fs.existsSync(filePath) ? fs.readFileSync(filePath, "utf8") : "";
262
+ }
263
+ catch (err) {
264
+ this.setMessage(` Could not open ${label}: ${errorMessage(err)}`);
265
+ return false;
266
+ }
267
+ this.editor = { state: createEditorState(filePath, label, content), kind, scope };
268
+ this.navMode = "editor";
269
+ return true;
270
+ }
271
+ closeEditor(message) {
272
+ this.editor = undefined;
273
+ this.navMode = "navigate";
274
+ this.invalidateSubsectionsCache();
275
+ this.setMessage(message);
276
+ }
277
+ saveEditor() {
278
+ const open = this.editor;
279
+ if (!open)
280
+ return false;
281
+ // The same undo stack :undo uses, so a bad save is recoverable.
282
+ this.snapshotForUndo(`edit ${open.state.label}`, open.state.path);
283
+ const result = saveEditedFile(open.state.path, editorText(open.state), open.kind);
284
+ if (!result.ok) {
285
+ open.state = { ...open.state, message: result.error ?? "could not save" };
286
+ return false;
287
+ }
288
+ // Only a frontmatter change moves what the manifests contain.
289
+ if (result.frontmatterChanged && open.scope) {
290
+ try {
291
+ syncSkillLinksForScope(this.phrenPath, open.scope);
292
+ }
293
+ catch (err) {
294
+ logger.debug("shell", `skill re-sync: ${errorMessage(err)}`);
295
+ }
296
+ }
297
+ open.state = { ...open.state, dirty: false, message: `written ${open.state.label}` };
298
+ return true;
299
+ }
300
+ async handleEditorKey(key) {
301
+ const open = this.editor;
302
+ if (!open) {
303
+ this.navMode = "navigate";
304
+ return true;
305
+ }
306
+ open.state = applyEditorKey(open.state, key);
307
+ if (open.state.wantSave) {
308
+ open.state = { ...open.state, wantSave: false };
309
+ const saved = this.saveEditor();
310
+ // A failed save cancels a :wq — you do not want to lose the buffer.
311
+ if (!saved && this.editor)
312
+ this.editor.state = { ...this.editor.state, wantClose: false };
313
+ }
314
+ if (this.editor?.state.wantClose) {
315
+ const label = this.editor.state.label;
316
+ const wasDirty = this.editor.state.dirty;
317
+ this.closeEditor(wasDirty ? ` Closed ${label} without saving` : ` ${style.green("✓")} ${label}`);
318
+ }
319
+ return true;
320
+ }
213
321
  // ── Raw key handling ───────────────────────────────────────────────────
214
322
  async handleRawKey(key) {
215
323
  if (key === "\x03" || key === "\x04")
@@ -226,10 +334,20 @@ export class PhrenShell {
226
334
  return true;
227
335
  }
228
336
  if (this.showHelp) {
337
+ // Scroll rather than dismiss, so the half of the help that does not fit
338
+ // on a small terminal is reachable at all.
339
+ const scroll = helpScrollDelta(key);
340
+ if (scroll !== 0) {
341
+ this.helpScroll = Math.max(0, this.helpScroll + scroll);
342
+ return true;
343
+ }
229
344
  this.showHelp = false;
345
+ this.helpScroll = 0;
230
346
  this.setMessage(` ${style.boldCyan("←→")} ${style.dim("tabs")} ${style.boldCyan("↑↓")} ${style.dim("move")} ${style.boldCyan("↵")} ${style.dim("activate")} ${style.boldCyan("?")} ${style.dim("help")}`);
231
347
  return true;
232
348
  }
349
+ if (this.navMode === "editor")
350
+ return this.handleEditorKey(key);
233
351
  return this.navMode === "input" ? this.handleInputKey(key) : handleNavigateKey(this.asNavigationHost(), key);
234
352
  }
235
353
  async handleInputKey(key) {
@@ -268,13 +386,21 @@ export class PhrenShell {
268
386
  }
269
387
  // ── Render (delegates to shell-view.ts) ────────────────────────────────
270
388
  async render() {
389
+ // The editor takes the whole frame: it is a mode, not a view.
390
+ if (this.navMode === "editor" && this.editor) {
391
+ const rows = Math.max(4, process.stdout.rows || 24);
392
+ const lines = renderEditor(this.editor.state, renderWidth(), rows);
393
+ return lines.map((line) => `${line}\x1b[K`).join("\n");
394
+ }
271
395
  const ctx = {
272
396
  phrenPath: this.phrenPath, profile: this.profile, state: this.state,
273
397
  currentCursor: () => this.currentCursor(), currentScroll: () => this.currentScroll(),
274
398
  setScroll: (n) => this.setScroll(n),
275
399
  graph: () => this.graph(),
276
400
  };
277
- return renderShell(ctx, this.navMode, this.inputCtx, this.inputBuf, this.showHelp, this.message, () => this.doctorSnapshot(), this._subsectionsCache, (n) => { this.healthLineCount = n; }, (c) => { this._subsectionsCache = c; });
401
+ // The editor path returned above, so this is only ever navigate or input.
402
+ const viewMode = this.navMode === "input" ? "input" : "navigate";
403
+ return renderShell(ctx, viewMode, this.inputCtx, this.inputBuf, this.showHelp, this.helpScroll, this.message, () => this.doctorSnapshot(), this._subsectionsCache, (n) => { this.healthLineCount = n; }, (c) => { this._subsectionsCache = c; });
278
404
  }
279
405
  // ── Navigation host adapter ────────────────────────────────────────────
280
406
  asNavigationHost() {
@@ -299,6 +425,8 @@ export class PhrenShell {
299
425
  getListItems: () => this.getListItems(),
300
426
  startInput: (ctx, initial) => this.startInput(ctx, initial),
301
427
  graph: () => this.graph(),
428
+ suspend: (fn) => this.suspend(fn),
429
+ openEditor: (filePath, label, kind, scope) => this.openEditor(filePath, label, kind, scope),
302
430
  };
303
431
  }
304
432
  // ── Palette (delegates to shell-input.ts) ──────────────────────────────
@@ -320,6 +448,7 @@ export class PhrenShell {
320
448
  }
321
449
  if (this.showHelp) {
322
450
  this.showHelp = false;
451
+ this.helpScroll = 0;
323
452
  this.setMessage(` ${style.boldCyan("←→")} ${style.dim("tabs")} ${style.boldCyan("↑↓")} ${style.dim("move")} ${style.boldCyan("↵")} ${style.dim("activate")} ${style.boldCyan("?")} ${style.dim("help")}`);
324
453
  if (!input)
325
454
  return true;
@@ -9,6 +9,8 @@ import type { ShellView } from "./types.js";
9
9
  export interface ShellStartup {
10
10
  view?: ShellView;
11
11
  project?: string;
12
+ /** Graph watch mode. Undefined leaves the default (on). */
13
+ live?: boolean;
12
14
  /** Shown on the shell's message line — fullscreen mode eats anything printed before launch. */
13
15
  notice?: string;
14
16
  }
@@ -16,6 +18,7 @@ export interface ShellStartupArgs {
16
18
  view?: string;
17
19
  project?: string;
18
20
  here?: boolean;
21
+ live?: boolean;
19
22
  unknown?: string;
20
23
  }
21
24
  export declare function normalizeShellView(raw: string | undefined): ShellView | undefined;
@@ -62,6 +62,12 @@ export function parseShellArgs(args) {
62
62
  case "--here":
63
63
  parsed.here = true;
64
64
  break;
65
+ case "--live":
66
+ parsed.live = true;
67
+ break;
68
+ case "--no-live":
69
+ parsed.live = false;
70
+ break;
65
71
  default:
66
72
  if (flag.startsWith("-") && parsed.unknown === undefined)
67
73
  parsed.unknown = flag;
@@ -77,6 +83,8 @@ export function parseShellArgs(args) {
77
83
  export function resolveShellStartup(parsed, opts) {
78
84
  const warnings = [];
79
85
  const startup = {};
86
+ if (parsed.live !== undefined)
87
+ startup.live = parsed.live;
80
88
  if (parsed.unknown)
81
89
  warnings.push(`Unknown flag ${parsed.unknown} — ignored.`);
82
90
  if (parsed.view) {
@@ -25,6 +25,10 @@ export interface SkillEntry {
25
25
  name: string;
26
26
  path: string;
27
27
  enabled: boolean;
28
+ /** "global" or "project" — the scope key enable/disable is recorded under. */
29
+ scopeType?: string;
30
+ /** The store this skill was read from, which may be a team store. */
31
+ storePath?: string;
28
32
  }
29
33
  export declare function getProjectSkills(phrenPath: string, project: string): SkillEntry[];
30
34
  export interface HookEntry {
@@ -34,4 +38,4 @@ export interface HookEntry {
34
38
  }
35
39
  export declare function getHookEntries(phrenPath: string, project?: string | null): HookEntry[];
36
40
  export { writeInstallPreferences } from "../init/preferences.js";
37
- export declare function renderShell(ctx: ViewContext, navMode: "navigate" | "input", inputCtx: string, inputBuf: string, showHelp: boolean, message: string, doctorSnapshot: () => Promise<DoctorResultLike>, subsectionsCache: SubsectionsCache | null, setHealthLineCount: (n: number) => void, setSubsectionsCache: (c: SubsectionsCache | null) => void): Promise<string>;
41
+ export declare function renderShell(ctx: ViewContext, navMode: "navigate" | "input", inputCtx: string, inputBuf: string, showHelp: boolean, helpScroll: number, message: string, doctorSnapshot: () => Promise<DoctorResultLike>, subsectionsCache: SubsectionsCache | null, setHealthLineCount: (n: number) => void, setSubsectionsCache: (c: SubsectionsCache | null) => void): Promise<string>;
@@ -6,7 +6,7 @@ import * as fs from "fs";
6
6
  import * as path from "path";
7
7
  import { canonicalTaskFilePath, listProjectCards, readTasks, readFindings, readReviewQueue, readRuntimeHealth, resolveTaskFilePath, } from "../data/access.js";
8
8
  import { getNonPrimaryStores } from "../store-registry.js";
9
- import { style, badge, separator, stripAnsi, truncateLine, renderWidth, wrapSegments, lineViewport, shellHelpText, gradient, } from "./render.js";
9
+ import { style, badge, separator, stripAnsi, truncateLine, displayWidth, renderWidth, wrapSegments, lineViewport, shellHelpText, gradient, } from "./render.js";
10
10
  import { formatSelectableLine, viewportWithStatus, } from "./view-list.js";
11
11
  import { SUB_VIEWS, TAB_ICONS, } from "./types.js";
12
12
  import { tasksByFilter, queueByFilter, } from "./palette.js";
@@ -16,7 +16,7 @@ import { isProjectHookEnabled, readProjectConfig } from "../project-config.js";
16
16
  import { getScopedSkills } from "../skill/registry.js";
17
17
  import { errorMessage } from "../utils.js";
18
18
  import { logger } from "../logger.js";
19
- import { renderGraphView } from "./graph/graph-view.js";
19
+ import { renderGraphView, graphSummary } from "./graph/graph-view.js";
20
20
  /** Resolve which store (primary or team) contains a project */
21
21
  function resolveProjectStorePath(phrenPath, project) {
22
22
  if (fs.existsSync(path.join(phrenPath, project)))
@@ -31,38 +31,35 @@ function resolveProjectStorePath(phrenPath, project) {
31
31
  return phrenPath;
32
32
  }
33
33
  // ── Tab bar ────────────────────────────────────────────────────────────────
34
- function renderTabBar(state) {
34
+ /**
35
+ * The whole top of the frame in as few rows as possible: brand, current view,
36
+ * project and filter on one line, then a rule. On a 24-row terminal the old
37
+ * three-row header cost more than a tenth of the screen.
38
+ */
39
+ function renderTopBar(state, summary = "") {
35
40
  const cols = renderWidth();
36
- if (state.view === "Health") {
37
- const label = `${TAB_ICONS.Health} Health`;
38
- return ` ${style.boldMagenta(label)}\n${separator(cols)}`;
39
- }
40
- if (state.view === "Graph") {
41
- const label = `${TAB_ICONS.Graph} Graph`;
42
- return ` ${style.boldMagenta(label)}\n${separator(cols)}`;
43
- }
44
- if (state.view === "Projects") {
45
- const label = `${TAB_ICONS.Projects} Projects`;
46
- const tabLine = ` ${style.boldMagenta(label)} `;
47
- return `${tabLine}\n${separator(cols)}`;
48
- }
49
- const projectTag = state.project
50
- ? `${style.cyan(state.project)} ${style.dim("›")}`
51
- : "";
52
- const tabs = SUB_VIEWS.map((v) => {
53
- const icon = TAB_ICONS[v] || "";
54
- const label = `${icon} ${v}`;
55
- return v === state.view
56
- ? ` ${style.boldMagenta(label)} `
57
- : ` ${style.dim(label)} `;
58
- });
59
- const segments = projectTag ? [projectTag, ...tabs] : tabs;
60
- const tabLine = wrapSegments(segments, cols, {
61
- indent: " ",
62
- maxLines: 2,
63
- separator: style.dim("│"),
64
- });
65
- return `${tabLine}\n${separator(cols)}`;
41
+ const brand = gradient("◆ phren");
42
+ const dot = style.dim("·");
43
+ const project = state.project ? `${dot} ${style.cyan(state.project)}` : "";
44
+ const filter = state.filter ? `${dot} ${style.yellow("/" + state.filter)}` : "";
45
+ const isSub = SUB_VIEWS.includes(state.view);
46
+ if (!isSub) {
47
+ const label = style.boldMagenta(`${TAB_ICONS[state.view] ?? "◆"} ${state.view}`);
48
+ const line = [" " + brand, label, project, filter, summary ? `${dot} ${summary}` : ""].filter(Boolean).join(" ");
49
+ return `${truncateLine(line, cols)}\n${separator(cols)}`;
50
+ }
51
+ // Sub-views carry a tab strip. Try full labels, then icons for the inactive
52
+ // tabs, before giving up and taking a second row.
53
+ const head = ` ${brand}${project ? ` ${project}` : ""}${filter ? ` ${filter}` : ""}`;
54
+ const full = SUB_VIEWS.map((v) => (v === state.view ? style.boldMagenta(`${TAB_ICONS[v]} ${v}`) : style.dim(`${TAB_ICONS[v]} ${v}`)));
55
+ const terse = SUB_VIEWS.map((v) => (v === state.view ? style.boldMagenta(`${TAB_ICONS[v]} ${v}`) : style.dim(TAB_ICONS[v] ?? "")));
56
+ for (const tabs of [full, terse]) {
57
+ const merged = `${head} ${style.dim("│")} ${tabs.join(style.dim(" │ "))}`;
58
+ if (displayWidth(merged) <= cols)
59
+ return `${merged}\n${separator(cols)}`;
60
+ }
61
+ const tabLine = wrapSegments(full, cols, { indent: " ", maxLines: 2, separator: style.dim("│") });
62
+ return `${head}\n${tabLine}\n${separator(cols)}`;
66
63
  }
67
64
  // ── Bottom bar ─────────────────────────────────────────────────────────────
68
65
  function renderBottomBar(state, navMode, inputCtx, inputBuf) {
@@ -83,42 +80,38 @@ function renderBottomBar(state, navMode, inputCtx, inputBuf) {
83
80
  const label = labels[inputCtx] || inputCtx;
84
81
  return `${sep}\n ${style.boldCyan(label + " ›")} ${inputBuf}${style.cyan("█")}`;
85
82
  }
86
- const viewHints = {
87
- Projects: [`${k("↵")} ${d("open project")}`, `${k("i")} ${d("intro mode")}`],
88
- Tasks: [`${k("a")} ${d("add")}`, `${k("↵")} ${d("mark done")}`, `${k("d")} ${d("toggle active")}`],
89
- Findings: [`${k("a")} ${d("add")}`, `${k("d")} ${d("remove")}`],
90
- "Review Queue": [`${k("↵")} ${d("inspect")}`],
91
- Skills: [`${k("a")} ${d("add")}`, `${k("t")} ${d("toggle")}`, `${k("d")} ${d("remove")}`],
92
- Hooks: [`${k("a")} ${d("enable")}`, `${k("d")} ${d("disable")}`],
93
- Health: [`${k("↑↓")} ${d("scroll")}`, `${k("esc")} ${d("back")}`],
94
- Graph: [`${k("↑↓←→")} ${d("walk")}`, `${k("↵")} ${d("select")}`, `${k("f")} ${d("filter")}`, `${k("[ ]")} ${d("project")}`, `${k("esc")} ${d("back")}`],
83
+ // Only what you reach for constantly. Everything else is one `?` away, so
84
+ // the bar never costs more than a single row.
85
+ const essentials = {
86
+ Projects: [`${k("↑↓")} ${d("move")}`, `${k("↵")} ${d("open")}`, `${k("e")} ${d("edit CLAUDE.md")}`],
87
+ Tasks: [`${k("↑↓")} ${d("move")}`, `${k("a")} ${d("add")}`, `${k("↵")} ${d("done")}`],
88
+ Findings: [`${k("↑↓")} ${d("move")}`, `${k("a")} ${d("add")}`],
89
+ "Review Queue": [`${k("↑↓")} ${d("move")}`, `${k("↵")} ${d("inspect")}`],
90
+ Skills: [`${k("↑↓")} ${d("move")}`, `${k("e")} ${d("edit")}`, `${k("t")} ${d("toggle")}`],
91
+ Hooks: [`${k("↑↓")} ${d("move")}`, `${k("a")} ${d("enable")}`],
92
+ Health: [`${k("↑↓")} ${d("scroll")}`],
93
+ Graph: [`${k("↑↓←→")} ${d("walk")}`, `${k("↵")} ${d("select")}`, `${k("w")} ${d("watch")}`, `${k("a")} ${d("agents")}`],
95
94
  };
96
- const extra = viewHints[state.view] ?? [];
97
- const isSubView = state.view !== "Projects" && state.view !== "Health" && state.view !== "Graph";
98
- const nav = isSubView
99
- ? [`${k("←→")} ${d("tabs")}`, `${k("↑↓")} ${d("move")}`, `${k("esc")} ${d("back")}`]
100
- : state.view === "Health" || state.view === "Graph"
101
- ? []
102
- : [`${k("↑↓")} ${d("move")}`];
103
- const tail = [
104
- state.view === "Graph" ? `${k("h")} ${d("health")}` : `${k("g")} ${d("graph")}`,
105
- `${k("/")} ${d(state.view === "Graph" ? "search" : "filter")}`,
106
- `${k(":")} ${d("cmd")}`, `${k("?")} ${d("help")}`, `${k("q")} ${d("quit")}`,
107
- ];
108
- const hints = [...nav, ...extra, ...tail];
109
- return `${sep}\n${wrapSegments(hints, cols, {
110
- indent: " ",
111
- maxLines: 3,
112
- separator: dot,
113
- })}`;
95
+ const search = state.view === "Graph" ? `${k("/")} ${d("search")}` : `${k("/")} ${d("filter")}`;
96
+ // `? keys` and `q quit` are the two you cannot afford to lose, so a narrow
97
+ // terminal drops view hints off the end instead of truncating those away.
98
+ const always = [`${k("?")} ${d("keys")}`, `${k("q")} ${d("quit")}`];
99
+ const optional = [...(essentials[state.view] ?? []), search];
100
+ let line = "";
101
+ for (let take = optional.length; take >= 0; take--) {
102
+ line = wrapSegments([...optional.slice(0, take), ...always], cols, { indent: " ", maxLines: 1, separator: dot });
103
+ if (!stripAnsi(line).trimEnd().endsWith("…"))
104
+ break;
105
+ }
106
+ return `${sep}\n${line}`;
114
107
  }
115
108
  // ── Content height ─────────────────────────────────────────────────────────
116
109
  function countRenderedLines(block) {
117
110
  return block.split("\n").length;
118
111
  }
119
- function contentHeight(tabBar, bottomBar) {
112
+ function contentHeight(topBar, bottomBar, hasMessage) {
120
113
  const rows = process.stdout.rows || 24;
121
- const reserved = 1 + countRenderedLines(tabBar) + 1 + countRenderedLines(bottomBar);
114
+ const reserved = countRenderedLines(topBar) + countRenderedLines(bottomBar) + (hasMessage ? 1 : 0);
122
115
  return Math.max(4, rows - reserved);
123
116
  }
124
117
  function collectProjectDashboardEntries(ctx) {
@@ -474,6 +467,11 @@ export function getProjectSkills(phrenPath, project) {
474
467
  name: skill.name,
475
468
  path: skill.path,
476
469
  enabled: skill.enabled,
470
+ // Carried so actions do not have to guess: a global skill toggled with the
471
+ // project as its scope writes a key nothing reads, and a path recovered by
472
+ // splitting a display string breaks on any path containing the separator.
473
+ scopeType: skill.scopeType,
474
+ storePath,
477
475
  }));
478
476
  }
479
477
  /** Max lines of skill content to show inline when selected. */
@@ -671,21 +669,29 @@ function renderHealthView(phrenPath, doctor, cursor, height, currentScroll, setS
671
669
  return { lines: vp.lines, lineCount };
672
670
  }
673
671
  // ── Main render ────────────────────────────────────────────────────────────
674
- export async function renderShell(ctx, navMode, inputCtx, inputBuf, showHelp, message, doctorSnapshot, subsectionsCache, setHealthLineCount, setSubsectionsCache) {
675
- const projectLabel = ctx.state.project
676
- ? ` ${style.dim("·")} ${style.cyan(ctx.state.project)}`
677
- : "";
678
- const filterLabel = ctx.state.filter
679
- ? ` ${style.dim("·")} ${style.yellow("/" + ctx.state.filter)}`
680
- : "";
681
- const header = ` ${gradient("◆ phren")}${projectLabel}${filterLabel}`;
682
- const tabBar = renderTabBar(ctx.state);
672
+ export async function renderShell(ctx, navMode, inputCtx, inputBuf, showHelp, helpScroll, message, doctorSnapshot, subsectionsCache, setHealthLineCount, setSubsectionsCache) {
673
+ const graphSummaryLine = ctx.state.view === "Graph" && ctx.graph ? graphSummary(ctx.graph()) : "";
674
+ const topBar = renderTopBar(ctx.state, graphSummaryLine);
683
675
  const bottomBar = renderBottomBar(ctx.state, navMode, inputCtx, inputBuf);
684
676
  const cursor = ctx.currentCursor();
685
- const height = contentHeight(tabBar, bottomBar);
677
+ // An empty message line used to hold a row open on every frame.
678
+ const hasMessage = Boolean(stripAnsi(message).trim());
679
+ const height = contentHeight(topBar, bottomBar, hasMessage);
686
680
  let contentLines;
687
681
  if (showHelp) {
688
- contentLines = shellHelpText().split("\n");
682
+ // The help is longer than a small terminal, and used to be clipped in
683
+ // silence — on 24 rows more than half of it simply was not there.
684
+ const all = shellHelpText().split("\n");
685
+ if (all.length <= height) {
686
+ contentLines = all;
687
+ }
688
+ else {
689
+ const maxScroll = all.length - (height - 1);
690
+ const start = Math.max(0, Math.min(helpScroll, maxScroll));
691
+ contentLines = all.slice(start, start + height - 1);
692
+ const atEnd = start >= maxScroll;
693
+ contentLines.push(style.dim(` ━━━ ${start + 1}-${start + height - 1} of ${all.length} ${atEnd ? "↑ back" : "↑↓ scroll"}`));
694
+ }
689
695
  }
690
696
  else {
691
697
  switch (ctx.state.view) {
@@ -737,9 +743,8 @@ export async function renderShell(ctx, navMode, inputCtx, inputBuf, showHelp, me
737
743
  const displayed = contentLines.slice(0, height);
738
744
  while (displayed.length < height)
739
745
  displayed.push("");
740
- const msgLine = ` ${style.dimItalic(stripAnsi(message).trimStart() ? message : "")}`;
741
746
  const cols = renderWidth();
742
- const parts = [header, tabBar, ...displayed, msgLine, bottomBar];
747
+ const parts = [topBar, ...displayed, ...(hasMessage ? [` ${style.dimItalic(message.trimStart())}`] : []), bottomBar];
743
748
  return parts.map(line => {
744
749
  if (line.includes("\n")) {
745
750
  return line.split("\n").map(sub => truncateLine(sub, cols) + "\x1b[K").join("\n");
package/dist/ui/server.js CHANGED
@@ -13,6 +13,7 @@ import { isValidProjectName, errorMessage, safeProjectPath } from "../utils.js";
13
13
  import { readInstallPreferences, writeInstallPreferences, writeGovernanceInstallPreferences } from "../init/preferences.js";
14
14
  import { buildGraph, collectProjectsForUI, collectSkillsForUI, getHooksData, isAllowedHookConfigPath, isAllowedSkillPath, readSyncSnapshot, recentAccepted, recentLookups, recentUsage, } from "./data.js";
15
15
  import { lookupEventsLogFile } from "../shared.js";
16
+ import { LookupTail } from "../shared/lookup-tail.js";
16
17
  import { CONSOLIDATION_ENTRY_THRESHOLD } from "../content/validate.js";
17
18
  import { ensureTopicReferenceDoc, getProjectTopicsResponse, listProjectReferenceDocs, pinProjectTopicSuggestion, readReferenceContent, reclassifyLegacyTopicDocs, unpinProjectTopicSuggestion, writeProjectTopics, } from "../project-topics.js";
18
19
  import { getWorkflowPolicy, updateWorkflowPolicy, updateRetentionPolicy, mergeConfig, getRetentionPolicy, getProjectConfigOverrides, getIndexPolicy, updateIndexPolicy, VALID_TASK_MODES } from "../governance/policy.js";
@@ -398,63 +399,12 @@ function handleLookupStream(req, res, ctx) {
398
399
  "X-Accel-Buffering": "no",
399
400
  });
400
401
  res.write("retry: 3000\n\n");
401
- const logPath = lookupEventsLogFile(ctx.phrenPath);
402
- // Start from the current end of the file so we only stream events that happen
403
- // after the client connects (the initial snapshot comes from /api/lookups).
404
- let offset = 0;
405
- try {
406
- offset = fs.existsSync(logPath) ? fs.statSync(logPath).size : 0;
407
- }
408
- catch {
409
- offset = 0;
410
- }
411
- let carry = "";
402
+ // Only stream events appended after the client connects; the initial
403
+ // snapshot comes from /api/lookups.
404
+ const tail = new LookupTail(lookupEventsLogFile(ctx.phrenPath));
412
405
  const flushNew = () => {
413
- let size;
414
- try {
415
- if (!fs.existsSync(logPath))
416
- return;
417
- size = fs.statSync(logPath).size;
418
- }
419
- catch {
420
- return;
421
- }
422
- if (size < offset) {
423
- offset = 0;
424
- carry = "";
425
- } // file rotated/truncated
426
- if (size <= offset)
427
- return;
428
- let chunk = "";
429
- try {
430
- const fd = fs.openSync(logPath, "r");
431
- try {
432
- const buf = Buffer.alloc(size - offset);
433
- fs.readSync(fd, buf, 0, buf.length, offset);
434
- chunk = buf.toString("utf8");
435
- }
436
- finally {
437
- fs.closeSync(fd);
438
- }
439
- }
440
- catch {
441
- return;
442
- }
443
- offset = size;
444
- const lines = (carry + chunk).split("\n");
445
- carry = lines.pop() ?? "";
446
- for (const line of lines) {
447
- const trimmed = line.trim();
448
- if (!trimmed)
449
- continue;
450
- try {
451
- JSON.parse(trimmed); // validate before forwarding
452
- res.write(`data: ${trimmed}\n\n`);
453
- }
454
- catch {
455
- // skip malformed lines
456
- }
457
- }
406
+ for (const line of tail.pollLines())
407
+ res.write(`data: ${line}\n\n`);
458
408
  };
459
409
  const pollTimer = setInterval(flushNew, 1000);
460
410
  const heartbeat = setInterval(() => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phren/cli",
3
- "version": "0.1.45",
3
+ "version": "0.1.47",
4
4
  "description": "Knowledge layer for AI agents — CLI, MCP server, and data layer",
5
5
  "type": "module",
6
6
  "bin": {