@phren/cli 0.1.46 → 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.
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Drawing for the shell's modal editor.
3
+ *
4
+ * The frame is painted whole on every key, so there is no real terminal cursor
5
+ * to move: the character under the cursor is drawn inverted instead.
6
+ */
7
+ import { displayWidth, lineViewport, padToWidth, style, truncateLine } from "./render.js";
8
+ const GUTTER = 5;
9
+ function modeBadge(state) {
10
+ switch (state.mode) {
11
+ case "insert": return style.boldGreen(" INSERT ");
12
+ case "command": return style.boldYellow(" COMMAND ");
13
+ default: return style.boldCyan(" NORMAL ");
14
+ }
15
+ }
16
+ /** The line with the cursor drawn on it, as inverse video. */
17
+ function withCursor(text, col, active) {
18
+ if (!active)
19
+ return text;
20
+ const chars = [...text];
21
+ const at = Math.min(col, chars.length);
22
+ const before = chars.slice(0, at).join("");
23
+ const under = chars[at] ?? " ";
24
+ const after = chars.slice(at + 1).join("");
25
+ return `${before}${style.invert(under)}${after}`;
26
+ }
27
+ export function renderEditor(state, width, height) {
28
+ const out = [];
29
+ const bodyHeight = Math.max(1, height - 2);
30
+ // Header: what is open, which mode, and whether it is unsaved.
31
+ const dirty = state.dirty ? style.boldYellow(" ●") : "";
32
+ const header = ` ${style.bold(state.label)}${dirty} ${modeBadge(state)}`;
33
+ out.push(padToWidth(truncateLine(header, width), width));
34
+ // Body, scrolled to keep the cursor in view.
35
+ const numbered = state.lines.map((text, i) => {
36
+ const active = i === state.cursor.line;
37
+ const gutter = active
38
+ ? style.boldCyan(String(i + 1).padStart(GUTTER - 1) + " ")
39
+ : style.dim(String(i + 1).padStart(GUTTER - 1) + " ");
40
+ const shown = withCursor(text, state.cursor.col, active && state.mode !== "command");
41
+ return `${gutter}${shown}`;
42
+ });
43
+ const vp = lineViewport(numbered, state.cursor.line, state.cursor.line, bodyHeight, 0);
44
+ for (const line of vp.lines)
45
+ out.push(padToWidth(truncateLine(line, width), width));
46
+ while (out.length < height - 1)
47
+ out.push(padToWidth("", width));
48
+ // Status: the command being typed wins, then a message, then position.
49
+ const position = `${state.cursor.line + 1},${state.cursor.col + 1}`;
50
+ let status;
51
+ if (state.mode === "command") {
52
+ status = ` ${style.boldCyan(state.command)}${style.cyan("█")}`;
53
+ }
54
+ else if (state.message) {
55
+ status = ` ${style.yellow(state.message)}`;
56
+ }
57
+ else {
58
+ const hint = state.mode === "insert"
59
+ ? style.dim("esc normal mode")
60
+ : style.dim(":w write · :q quit · i insert · / search");
61
+ status = ` ${hint}`;
62
+ }
63
+ const right = style.dim(position);
64
+ const pad = Math.max(1, width - displayWidth(status) - displayWidth(right) - 2);
65
+ out.push(padToWidth(truncateLine(`${status}${" ".repeat(pad)}${right}`, width), width));
66
+ return out.slice(0, height);
67
+ }
@@ -107,10 +107,16 @@ export async function startShell(phrenPath, profile, startup = {}) {
107
107
  await new Promise((resolve) => { rl.on("close", () => { shell.close(); resolve(); }); });
108
108
  return;
109
109
  }
110
- process.stdin.setRawMode(true);
111
- process.stdin.resume();
112
- process.stdin.setEncoding("utf8");
113
- enterFullscreen();
110
+ // Taking and releasing the terminal is written once and used twice: at
111
+ // startup and shutdown, and again either side of handing the terminal to an
112
+ // editor. Two copies of this would drift.
113
+ const grabTerminal = () => {
114
+ process.stdin.setRawMode(true);
115
+ process.stdin.resume();
116
+ process.stdin.setEncoding("utf8");
117
+ enterFullscreen();
118
+ };
119
+ grabTerminal();
114
120
  let exiting = false;
115
121
  let cleanedUp = false;
116
122
  // ── Painting ────────────────────────────────────────────────────────────
@@ -268,6 +274,27 @@ export async function startShell(phrenPath, profile, startup = {}) {
268
274
  process.once("SIGINT", onSignal);
269
275
  process.once("SIGTERM", onSignal);
270
276
  process.once("exit", onProcessExit);
277
+ // Hand the terminal to a child process (an editor) and take it back. The
278
+ // shell owns raw mode, the alternate screen and the stdin listener, so all
279
+ // three have to be unwound or the child and the key pump fight over input.
280
+ shell.setSuspendHandler(async (run) => {
281
+ if (exiting)
282
+ return;
283
+ process.stdin.removeListener("data", onData);
284
+ restoreTerminal();
285
+ try {
286
+ await run();
287
+ }
288
+ finally {
289
+ if (!exiting) {
290
+ grabTerminal();
291
+ process.stdin.on("data", onData);
292
+ // Anything typed at the child after it exited is not for us.
293
+ decoder.flush();
294
+ await repaint();
295
+ }
296
+ }
297
+ });
271
298
  try {
272
299
  await playStartupIntro(phrenPath, resolveStartupIntroPlan(phrenPath), waitForIntroKeypress);
273
300
  introKeyWaiter = undefined;
@@ -34,6 +34,9 @@ export interface NavigationHost extends PaletteHost {
34
34
  name?: string;
35
35
  text?: string;
36
36
  line?: string;
37
+ path?: string;
38
+ scopeType?: string;
39
+ storePath?: string;
37
40
  }[];
38
41
  startInput(ctx: string, initial: string): void;
39
42
  inputMqId: string;
@@ -42,7 +45,25 @@ export interface NavigationHost extends PaletteHost {
42
45
  setFilter(value: string): void;
43
46
  /** The knowledge-graph view's controller (created on first use). */
44
47
  graph(): GraphController;
48
+ /** Run something with the terminal released; false when the host cannot. */
49
+ suspend(fn: () => Promise<void> | void): Promise<boolean>;
50
+ /** Open a file in the shell's own modal editor. */
51
+ openEditor(filePath: string, label: string, kind: "skill" | "claude", scope?: string): boolean;
45
52
  }
53
+ /**
54
+ * The file `e` and `E` edit for the current view. Skills edit their own
55
+ * markdown; a project edits the CLAUDE.md the store owns and symlinks into the
56
+ * repo, so editing here reaches every linked checkout.
57
+ */
58
+ export declare function editTargetFor(host: NavigationHost, item: {
59
+ name?: string;
60
+ path?: string;
61
+ storePath?: string;
62
+ } | undefined): {
63
+ path: string;
64
+ label: string;
65
+ kind: "skill" | "claude";
66
+ } | null;
46
67
  export declare function executePalette(host: PaletteHost, input: string): Promise<void>;
47
68
  export declare function completeInput(line: string, phrenPath: string, profile: string, state: ShellState): string[];
48
69
  export declare function getListItems(phrenPath: string, profile: string, state: ShellState, healthLineCount: number): {
@@ -50,6 +71,9 @@ export declare function getListItems(phrenPath: string, profile: string, state:
50
71
  name?: string;
51
72
  text?: string;
52
73
  line?: string;
74
+ path?: string;
75
+ scopeType?: string;
76
+ storePath?: string;
53
77
  }[];
54
78
  /**
55
79
  * Handle p/b/l/m/s/k/h shortcut keys that switch the active view.
@@ -13,10 +13,32 @@ import { consolidateProjectFindings } from "../governance/policy.js";
13
13
  import { style } from "./render.js";
14
14
  import { SUB_VIEWS, TAB_ICONS } from "./types.js";
15
15
  import { getProjectSkills, getHookEntries, writeInstallPreferences } from "./view.js";
16
+ import { resolveProjectStorePath } from "../cli/namespaces-utils.js";
17
+ import { openInEditor } from "../editor/launch.js";
16
18
  import { removeSkillPath, setSkillEnabledAndSync } from "../skill/files.js";
17
19
  import { resultMsg, editDistance, tokenize, expandIds, normalizeSection, tasksByFilter, queueByFilter, } from "./palette.js";
18
20
  import { errorMessage } from "../utils.js";
19
21
  import { logger } from "../logger.js";
22
+ /**
23
+ * The file `e` and `E` edit for the current view. Skills edit their own
24
+ * markdown; a project edits the CLAUDE.md the store owns and symlinks into the
25
+ * repo, so editing here reaches every linked checkout.
26
+ */
27
+ export function editTargetFor(host, item) {
28
+ if (host.state.view === "Skills") {
29
+ if (!item?.path)
30
+ return null;
31
+ return { path: item.path, label: item.name ?? path.basename(item.path), kind: "skill" };
32
+ }
33
+ if (host.state.view === "Projects") {
34
+ const project = item?.name ?? host.state.project;
35
+ if (!project)
36
+ return null;
37
+ const store = resolveProjectStorePath(host.phrenPath, project);
38
+ return { path: path.join(store, project, "CLAUDE.md"), label: `${project}/CLAUDE.md`, kind: "claude" };
39
+ }
40
+ return null;
41
+ }
20
42
  function taskFileForProject(phrenPath, project) {
21
43
  return resolveTaskFilePath(phrenPath, project)
22
44
  ?? canonicalTaskFilePath(phrenPath, project)
@@ -30,7 +52,7 @@ export async function executePalette(host, input) {
30
52
  const command = (parts[0] || "").toLowerCase();
31
53
  if (command === "help") {
32
54
  host.showHelp = true;
33
- host.setMessage(" Showing help — press any key to dismiss");
55
+ host.setMessage(" Showing help — ↑↓ to scroll, any other key to dismiss");
34
56
  return;
35
57
  }
36
58
  if (command === "projects") {
@@ -575,7 +597,13 @@ export function getListItems(phrenPath, profile, state, healthLineCount) {
575
597
  case "Skills": {
576
598
  if (!state.project)
577
599
  return [];
578
- const allSkills = getProjectSkills(phrenPath, state.project).map((s) => ({ name: s.name, text: `${s.enabled ? "enabled" : "disabled"} · ${s.path}` }));
600
+ const allSkills = getProjectSkills(phrenPath, state.project).map((s) => ({
601
+ name: s.name,
602
+ text: `${s.enabled ? "enabled" : "disabled"} · ${s.path}`,
603
+ path: s.path,
604
+ scopeType: s.scopeType,
605
+ storePath: s.storePath,
606
+ }));
579
607
  return state.filter
580
608
  ? allSkills.filter((s) => `${s.name} ${s.text}`.toLowerCase().includes(state.filter.toLowerCase()))
581
609
  : allSkills;
@@ -650,6 +678,24 @@ async function doViewAction(host, key) {
650
678
  const cursor = host.currentCursor();
651
679
  const items = host.getListItems();
652
680
  const item = items[cursor];
681
+ // `e` hands the file to the user's own editor, whatever that is.
682
+ if (key === "e") {
683
+ const target = editTargetFor(host, item);
684
+ if (!target) {
685
+ host.setMessage(` ${style.dim("nothing to edit here")}`);
686
+ return;
687
+ }
688
+ const handed = await host.suspend(() => {
689
+ const result = openInEditor(target.path);
690
+ host.setMessage(result.ok
691
+ ? ` ${style.green("✓")} ${target.label}`
692
+ : ` Editor "${result.command}" failed — ${result.error ?? "could not start"}. Set $EDITOR.`);
693
+ });
694
+ if (!handed)
695
+ host.setMessage(` ${style.dim("edit it at")} ${target.path}`);
696
+ host.invalidateSubsectionsCache();
697
+ return;
698
+ }
653
699
  const project = host.state.project;
654
700
  switch (host.state.view) {
655
701
  case "Tasks":
@@ -698,10 +744,14 @@ async function doViewAction(host, key) {
698
744
  host.setMessage("Select a project first.");
699
745
  return;
700
746
  }
701
- const skillPath = item.text;
747
+ const skillPath = item.path;
748
+ if (!skillPath) {
749
+ host.setMessage(" Could not resolve that skill's path.");
750
+ return;
751
+ }
702
752
  host.confirmThen(`Remove skill "${item.name}"?`, () => {
703
753
  try {
704
- removeSkillPath(skillPath.split("·").slice(-1)[0].trim());
754
+ removeSkillPath(skillPath);
705
755
  host.setMessage(` Removed ${item.name}`);
706
756
  host.setCursor(Math.max(0, cursor - 1));
707
757
  }
@@ -716,7 +766,10 @@ async function doViewAction(host, key) {
716
766
  return;
717
767
  }
718
768
  const isEnabled = !item.text?.startsWith("disabled");
719
- setSkillEnabledAndSync(host.phrenPath, project, item.name, !isEnabled);
769
+ // A global skill's enabled flag is recorded under the "global" scope;
770
+ // passing the project wrote a key that nothing ever reads back.
771
+ const scope = item.scopeType === "global" ? "global" : project;
772
+ setSkillEnabledAndSync(item.storePath ?? host.phrenPath, scope, item.name, !isEnabled);
720
773
  host.setMessage(` ${!isEnabled ? "Enabled" : "Disabled"} ${item.name}`);
721
774
  }
722
775
  else if (key === "a") {
@@ -892,7 +945,7 @@ export async function handleNavigateKey(host, rawKey) {
892
945
  }
893
946
  if (key === "?") {
894
947
  host.showHelp = !host.showHelp;
895
- host.setMessage(host.showHelp ? " Showing help — press any key to dismiss" : ` ${style.boldCyan("←→")} ${style.dim("tabs")} ${style.boldCyan("↑↓")} ${style.dim("move")} ${style.boldCyan("↵")} ${style.dim("activate")} ${style.boldCyan("?")} ${style.dim("help")}`);
948
+ host.setMessage(host.showHelp ? " Showing help — ↑↓ to scroll, any other key to dismiss" : ` ${style.boldCyan("←→")} ${style.dim("tabs")} ${style.boldCyan("↑↓")} ${style.dim("move")} ${style.boldCyan("↵")} ${style.dim("activate")} ${style.boldCyan("?")} ${style.dim("help")}`);
896
949
  return true;
897
950
  }
898
951
  if (key === "/") {
@@ -931,6 +984,20 @@ export async function handleNavigateKey(host, rawKey) {
931
984
  host.setMessage(` Intro mode: ${style.boldCyan(next)}`);
932
985
  return true;
933
986
  }
987
+ if (key === "E") {
988
+ const items = host.getListItems();
989
+ const item = items[host.currentCursor()];
990
+ const target = editTargetFor(host, item);
991
+ if (!target) {
992
+ host.setMessage(` ${style.dim("nothing to edit here")}`);
993
+ return true;
994
+ }
995
+ const scope = target.kind === "skill" ? (item?.scopeType === "global" ? "global" : host.state.project) : undefined;
996
+ if (host.openEditor(target.path, target.label, target.kind, scope)) {
997
+ host.setMessage(` ${style.dim("i insert · :w write · :q quit")}`);
998
+ }
999
+ return true;
1000
+ }
934
1001
  if (["a", "d", "e", "t", "\x7f"].includes(key)) {
935
1002
  await doViewAction(host, key);
936
1003
  return true;
@@ -30,6 +30,7 @@ export async function renderMenuFrame(phrenPath, profile, state) {
30
30
  "", // no inputCtx
31
31
  "", // no inputBuf
32
32
  false, // no help
33
+ 0, // help scroll (unused: no help)
33
34
  "Tab: Chat ←→: Views ↑↓: Navigate Enter: Select /: Filter Esc: Back", stubDoctor, null, // subsectionsCache
34
35
  () => { }, // setHealthLineCount
35
36
  () => { });
@@ -246,14 +246,21 @@ export function shellHelpText() {
246
246
  ` ${k("/")} ${d("filter")} ${k(":")} ${d("command palette")} ${k("Esc")} ${d("cancel / clear filter")} ${k("?")} ${d("toggle this help")}`,
247
247
  "",
248
248
  hdr("View-specific keys"),
249
- ` ${style.bold("Projects")} ${k("↵")} ${d("open project tasks")} ${k("i")} ${d("cycle intro mode")}`,
249
+ ` ${style.bold("Projects")} ${k("↵")} ${d("open project tasks")} ${k("e")}${d("/")}${k("E")} ${d("edit CLAUDE.md")} ${k("i")} ${d("cycle intro mode")}`,
250
250
  ` ${style.bold("Tasks")} ${k("a")} ${d("add task")} ${k("d")} ${d("toggle active/queue")} ${k("↵")} ${d("mark complete")}`,
251
251
  ` ${style.bold("Findings")} ${k("a")} ${d("tell phren")} ${k("d")} ${d("delete selected")}`,
252
252
  ` ${style.bold("Review Queue")} ${k("↵")} ${d("inspect selected item")} ${d("(read-only)")}`,
253
253
  ` ${style.bold("Graph")} ${k("↑↓←→")} ${d("walk")} ${k("1-9")} ${d("neighbour")} ${k("↵")} ${d("select / focus")} ${k("w")} ${d("watch")}`,
254
254
  ` ${" ".repeat(13)}${k("/")} ${d("search")} ${k("n N")} ${d("next / prev hit")} ${k("f")} ${d("filter")} ${k("[ ]")} ${d("project")}`,
255
255
  ` ${" ".repeat(13)}${k("+ -")} ${d("zoom")} ${k("0")} ${d("fit")} ${k("r")} ${d("re-lay out")} ${k("⇧↑↓←→")} ${d("pan")} ${k("o")} ${d("3D viewer")}`,
256
- ` ${style.bold("Skills")} ${k("t")} ${d("toggle enabled")} ${k("d")} ${d("remove")}`,
256
+ ` ${style.bold("Skills")} ${k("e")} ${d("edit in $EDITOR")} ${k("E")} ${d("edit here")} ${k("t")} ${d("toggle enabled")} ${k("d")} ${d("remove")}`,
257
+ "",
258
+ "",
259
+ hdr("Editor (E, or e for $EDITOR)"),
260
+ ` ${k("h j k l")} ${d("move")} ${k("w b")} ${d("word")} ${k("0 $")} ${d("line")} ${k("gg G")} ${d("file")}`,
261
+ ` ${k("i a I A")} ${d("insert")} ${k("o O")} ${d("open line")} ${k("x")} ${d("delete char")} ${k("dd")} ${d("delete line")}`,
262
+ ` ${k("yy")} ${d("yank")} ${k("p P")} ${d("paste")} ${k("u")} ${d("undo")} ${k("/")} ${d("search")} ${k("n N")} ${d("next / prev")}`,
263
+ ` ${k(":w")} ${d("write")} ${k(":q")} ${d("quit")} ${k(":wq")} ${d("write and quit")} ${k(":q!")} ${d("discard")}`,
257
264
  "",
258
265
  hdr("Palette commands (:cmd)"),
259
266
  ` ${cmd(":open <project>")} ${d("set active project context")}`,
@@ -2,6 +2,8 @@ import { type ShellView, type ShellDeps, type DoctorResultLike } from "./types.j
2
2
  export type { ShellView, ShellDeps } from "./types.js";
3
3
  import type { ShellStartup } from "./startup.js";
4
4
  import { GraphController } from "./graph/controller.js";
5
+ import { type EditorState } from "../editor/buffer.js";
6
+ import { type EditKind } from "../editor/save.js";
5
7
  export declare class PhrenShell {
6
8
  readonly phrenPath: string;
7
9
  readonly profile: string;
@@ -17,18 +19,22 @@ export declare class PhrenShell {
17
19
  private pendingConfirm?;
18
20
  private undoStack;
19
21
  private navMode;
22
+ private editor?;
20
23
  private inputBuf;
21
24
  private inputCtx;
22
25
  inputMqId: string;
23
26
  private cursorMap;
24
27
  private viewScrollMap;
25
28
  private healthLineCount;
29
+ private helpScroll;
26
30
  private _subsectionsCache;
27
31
  private _graph?;
28
32
  private repaintHandler;
33
+ private suspendHandler;
29
34
  /** `--live` / `--no-live`; undefined leaves watch mode at its default. */
30
35
  private graphLive?;
31
- get mode(): "navigate" | "input";
36
+ get mode(): "navigate" | "input" | "editor";
37
+ get editorState(): EditorState | undefined;
32
38
  get inputBuffer(): string;
33
39
  get filter(): string | undefined;
34
40
  constructor(phrenPath: string, profile: string, deps?: ShellDeps, startup?: ShellStartup);
@@ -40,6 +46,14 @@ export declare class PhrenShell {
40
46
  * to show a build that finished while nothing was typed.
41
47
  */
42
48
  setRepaintHandler(handler: (() => void) | null): void;
49
+ /**
50
+ * Let the host lend the terminal to a child process. Without one — a non-TTY
51
+ * host, or an embedder — callers fall back to telling the user the path.
52
+ */
53
+ setSuspendHandler(handler: ((run: () => Promise<void> | void) => Promise<void>) | null): void;
54
+ get canSuspend(): boolean;
55
+ /** Run `fn` with the terminal released. Resolves false when that is impossible. */
56
+ suspend(fn: () => Promise<void> | void): Promise<boolean>;
43
57
  graph(): GraphController;
44
58
  confirmThen(label: string, action: () => void): void;
45
59
  setView(view: ShellView): void;
@@ -58,10 +72,18 @@ export declare class PhrenShell {
58
72
  name?: string;
59
73
  text?: string;
60
74
  line?: string;
75
+ path?: string;
76
+ scopeType?: string;
77
+ storePath?: string;
61
78
  }[];
62
79
  startInput(ctx: string, initial: string): void;
63
80
  private cancelInput;
64
81
  private submitInput;
82
+ /** Open a file in the built-in editor. Returns false if it cannot be read. */
83
+ openEditor(filePath: string, label: string, kind: EditKind, scope?: string): boolean;
84
+ private closeEditor;
85
+ private saveEditor;
86
+ private handleEditorKey;
65
87
  handleRawKey(key: string): Promise<boolean>;
66
88
  private handleInputKey;
67
89
  private doctorSnapshot;
@@ -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,18 +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;
45
65
  /** `--live` / `--no-live`; undefined leaves watch mode at its default. */
46
66
  graphLive;
47
67
  get mode() { return this.navMode; }
68
+ get editorState() { return this.editor?.state; }
48
69
  get inputBuffer() { return this.inputBuf; }
49
70
  get filter() { return this.state.filter; }
50
71
  constructor(phrenPath, profile, deps = {
@@ -82,6 +103,23 @@ export class PhrenShell {
82
103
  this.repaintHandler = handler;
83
104
  this._graph?.setRepaintHook(handler);
84
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
+ }
85
123
  graph() {
86
124
  if (!this._graph) {
87
125
  this._graph = new GraphController(this.phrenPath, this.profile, { watchEnabled: this.graphLive });
@@ -215,6 +253,71 @@ export class PhrenShell {
215
253
  }
216
254
  }
217
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
+ }
218
321
  // ── Raw key handling ───────────────────────────────────────────────────
219
322
  async handleRawKey(key) {
220
323
  if (key === "\x03" || key === "\x04")
@@ -231,10 +334,20 @@ export class PhrenShell {
231
334
  return true;
232
335
  }
233
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
+ }
234
344
  this.showHelp = false;
345
+ this.helpScroll = 0;
235
346
  this.setMessage(` ${style.boldCyan("←→")} ${style.dim("tabs")} ${style.boldCyan("↑↓")} ${style.dim("move")} ${style.boldCyan("↵")} ${style.dim("activate")} ${style.boldCyan("?")} ${style.dim("help")}`);
236
347
  return true;
237
348
  }
349
+ if (this.navMode === "editor")
350
+ return this.handleEditorKey(key);
238
351
  return this.navMode === "input" ? this.handleInputKey(key) : handleNavigateKey(this.asNavigationHost(), key);
239
352
  }
240
353
  async handleInputKey(key) {
@@ -273,13 +386,21 @@ export class PhrenShell {
273
386
  }
274
387
  // ── Render (delegates to shell-view.ts) ────────────────────────────────
275
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
+ }
276
395
  const ctx = {
277
396
  phrenPath: this.phrenPath, profile: this.profile, state: this.state,
278
397
  currentCursor: () => this.currentCursor(), currentScroll: () => this.currentScroll(),
279
398
  setScroll: (n) => this.setScroll(n),
280
399
  graph: () => this.graph(),
281
400
  };
282
- 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; });
283
404
  }
284
405
  // ── Navigation host adapter ────────────────────────────────────────────
285
406
  asNavigationHost() {
@@ -304,6 +425,8 @@ export class PhrenShell {
304
425
  getListItems: () => this.getListItems(),
305
426
  startInput: (ctx, initial) => this.startInput(ctx, initial),
306
427
  graph: () => this.graph(),
428
+ suspend: (fn) => this.suspend(fn),
429
+ openEditor: (filePath, label, kind, scope) => this.openEditor(filePath, label, kind, scope),
307
430
  };
308
431
  }
309
432
  // ── Palette (delegates to shell-input.ts) ──────────────────────────────
@@ -325,6 +448,7 @@ export class PhrenShell {
325
448
  }
326
449
  if (this.showHelp) {
327
450
  this.showHelp = false;
451
+ this.helpScroll = 0;
328
452
  this.setMessage(` ${style.boldCyan("←→")} ${style.dim("tabs")} ${style.boldCyan("↑↓")} ${style.dim("move")} ${style.boldCyan("↵")} ${style.dim("activate")} ${style.boldCyan("?")} ${style.dim("help")}`);
329
453
  if (!input)
330
454
  return true;
@@ -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>;