@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
@@ -11,6 +11,13 @@
11
11
  */
12
12
  export declare const PHREN_ART: string[];
13
13
  export declare const PHREN_ART_RIGHT: string[];
14
+ /**
15
+ * The mascot holds still: it sits at a fixed position beside the wordmark and
16
+ * only its eyes and the sparkle above its head change. Whole-body motion (the
17
+ * vertical bob and the sideways lean) shifted the art by a full cell, which
18
+ * reads as blocky jitter at terminal resolution, so it is gone. Every frame has
19
+ * the same line count and the same display width as `PHREN_ART`.
20
+ */
14
21
  export interface PhrenAnimator {
15
22
  getFrame(): string[];
16
23
  start(): void;
package/dist/phren-art.js CHANGED
@@ -83,36 +83,19 @@ function applySparkleToLine(line, frame, active) {
83
83
  }
84
84
  return line.replace(/(\x1b\[38;2;\d+;2\d\d;2\d\dm)[\u2580\u2584](\x1b\[0m)/g, `$1${sparkleChar}$2`);
85
85
  }
86
- function applyLean(line, offset) {
87
- if (offset === 0)
88
- return line;
89
- if (offset > 0) {
90
- return " ".repeat(offset) + line;
91
- }
92
- const trimCount = Math.min(-offset, line.match(/^( *)/)[1].length);
93
- return line.slice(trimCount);
94
- }
95
86
  export function createPhrenAnimator(options) {
96
87
  const facing = options?.facing ?? "left";
97
88
  const baseArt = facing === "right" ? PHREN_ART_RIGHT : PHREN_ART;
98
89
  const state = {
99
- bobUp: false,
100
90
  isBlinking: false,
101
91
  sparkleFrame: 0,
102
92
  sparkleActive: false,
103
- leanOffset: 0,
104
93
  };
105
94
  const timers = [];
106
95
  function scheduleTimer(fn, ms) {
107
96
  const t = setTimeout(fn, ms);
108
97
  timers.push(t);
109
98
  }
110
- function scheduleBob() {
111
- scheduleTimer(() => {
112
- state.bobUp = !state.bobUp;
113
- scheduleBob();
114
- }, 500);
115
- }
116
99
  function scheduleBlink() {
117
100
  const interval = randInt(2000, 8000);
118
101
  scheduleTimer(() => {
@@ -153,41 +136,23 @@ export function createPhrenAnimator(options) {
153
136
  sparkleStep(step + 1);
154
137
  }, 200);
155
138
  }
156
- function scheduleLean() {
157
- const interval = randInt(4000, 10000);
158
- scheduleTimer(() => {
159
- const direction = Math.random() < 0.5 ? -1 : 1;
160
- state.leanOffset = direction;
161
- const holdTime = randInt(1000, 2000);
162
- scheduleTimer(() => {
163
- state.leanOffset = 0;
164
- scheduleLean();
165
- }, holdTime);
166
- }, interval);
167
- }
168
139
  return {
169
140
  getFrame() {
170
- let lines = baseArt.map((line, i) => {
171
- let result = line;
141
+ // In-place substitutions only: the art grid is never shifted or padded,
142
+ // so the frame keeps its line count and its width.
143
+ return baseArt.map((line, i) => {
172
144
  if (state.isBlinking && i === EYE_ROW) {
173
- result = applyBlinkToLine(result);
145
+ return applyBlinkToLine(line);
174
146
  }
175
147
  if (i === SPARKLE_ROW) {
176
- result = applySparkleToLine(result, state.sparkleFrame, state.sparkleActive);
148
+ return applySparkleToLine(line, state.sparkleFrame, state.sparkleActive);
177
149
  }
178
- result = applyLean(result, state.leanOffset);
179
- return result;
150
+ return line;
180
151
  });
181
- if (state.bobUp) {
182
- lines = ["", ...lines.slice(0, -1)];
183
- }
184
- return lines;
185
152
  },
186
153
  start() {
187
- scheduleBob();
188
154
  scheduleBlink();
189
155
  scheduleSparkle();
190
- scheduleLean();
191
156
  },
192
157
  stop() {
193
158
  for (const t of timers) {
@@ -48,6 +48,22 @@ export declare function phrenErr<T>(error: string, code?: PhrenErrorCode): Phren
48
48
  export declare function forwardErr<T>(result: PhrenResult<unknown>): PhrenResult<T>;
49
49
  export declare function parsePhrenErrorCode(msg: string): PhrenErrorCode | undefined;
50
50
  export declare function isRecord(value: unknown): value is Record<string, unknown>;
51
+ /**
52
+ * `yaml.load` with js-yaml 4's empty-document behaviour.
53
+ *
54
+ * js-yaml 5 throws YAMLException("expected a document, but the input is empty")
55
+ * for input that is blank, whitespace, or comments only — where 4 returned
56
+ * `undefined`. phren's config files legitimately look like that: a freshly
57
+ * scaffolded `machines.yaml` is a single header comment, and an untouched
58
+ * profile can be empty. Every caller already handles `undefined`, but a throw
59
+ * is read as a parse failure, which would report those files as malformed —
60
+ * and `stores.yaml` refuses to write back over a file it could not parse, so
61
+ * an empty registry would have become unrepairable by the CLI.
62
+ *
63
+ * Only genuinely empty documents are absorbed. `---`, `null` and real syntax
64
+ * errors reach js-yaml exactly as before.
65
+ */
66
+ export declare function loadYamlDocument<T = unknown>(source: string, load: (source: string) => unknown): T | undefined;
51
67
  /** Shallow-merge data onto defaults so missing keys get filled in. */
52
68
  export declare function withDefaults<T extends object>(data: Partial<T>, defaults: T): T;
53
69
  /**
@@ -70,6 +70,27 @@ export function parsePhrenErrorCode(msg) {
70
70
  export function isRecord(value) {
71
71
  return typeof value === "object" && value !== null && !Array.isArray(value);
72
72
  }
73
+ /**
74
+ * `yaml.load` with js-yaml 4's empty-document behaviour.
75
+ *
76
+ * js-yaml 5 throws YAMLException("expected a document, but the input is empty")
77
+ * for input that is blank, whitespace, or comments only — where 4 returned
78
+ * `undefined`. phren's config files legitimately look like that: a freshly
79
+ * scaffolded `machines.yaml` is a single header comment, and an untouched
80
+ * profile can be empty. Every caller already handles `undefined`, but a throw
81
+ * is read as a parse failure, which would report those files as malformed —
82
+ * and `stores.yaml` refuses to write back over a file it could not parse, so
83
+ * an empty registry would have become unrepairable by the CLI.
84
+ *
85
+ * Only genuinely empty documents are absorbed. `---`, `null` and real syntax
86
+ * errors reach js-yaml exactly as before.
87
+ */
88
+ export function loadYamlDocument(source, load) {
89
+ // Strip blank and comment-only lines; anything left is a document to parse.
90
+ if (!source.replace(/^\s*(#.*)?$/gm, "").trim())
91
+ return undefined;
92
+ return load(source);
93
+ }
73
94
  /** Shallow-merge data onto defaults so missing keys get filled in. */
74
95
  export function withDefaults(data, defaults) {
75
96
  const merged = { ...defaults };
@@ -4,7 +4,7 @@ import * as path from "path";
4
4
  import * as crypto from "crypto";
5
5
  import * as yaml from "js-yaml";
6
6
  import { bootstrapPhrenDotEnv } from "./phren-dotenv.js";
7
- import { PhrenError, isRecord, RESERVED_PROJECT_DIR_NAMES } from "./phren-core.js";
7
+ import { PhrenError, isRecord, loadYamlDocument, RESERVED_PROJECT_DIR_NAMES } from "./phren-core.js";
8
8
  import { errorMessage, isValidProjectName, safeProjectPath } from "./utils.js";
9
9
  import { FINDINGS_FILENAME } from "./data/access.js";
10
10
  bootstrapPhrenDotEnv();
@@ -128,7 +128,7 @@ export function readRootManifest(phrenPath) {
128
128
  if (!fs.existsSync(manifestFile))
129
129
  return null;
130
130
  try {
131
- const parsed = yaml.load(fs.readFileSync(manifestFile, "utf8"), { schema: yaml.CORE_SCHEMA });
131
+ const parsed = loadYamlDocument(fs.readFileSync(manifestFile, "utf8"), (text) => yaml.load(text, { schema: yaml.CORE_SCHEMA }));
132
132
  return normalizeManifest(parsed);
133
133
  }
134
134
  catch (err) {
@@ -176,7 +176,11 @@ export function findNearestPhrenPath(startDir = process.cwd()) {
176
176
  let current = path.resolve(startDir);
177
177
  while (true) {
178
178
  const localCandidate = path.join(current, ".phren");
179
- if (isPhrenRootCandidate(localCandidate))
179
+ // Only a manifest counts on the cwd walk. Loose install markers are
180
+ // enough for the user's own ~/.phren or an explicit PHREN_PATH, but a
181
+ // cloned repo could ship `.phren/global/` and become the store — with
182
+ // its `.env` loaded — just by being cd'd into.
183
+ if (hasRootManifest(localCandidate))
180
184
  return localCandidate;
181
185
  const parent = path.dirname(current);
182
186
  if (parent === current)
@@ -578,7 +582,7 @@ export function getProjectDirs(phrenPath, profile) {
578
582
  return [];
579
583
  }
580
584
  try {
581
- const data = yaml.load(fs.readFileSync(profilePath, "utf-8"), { schema: yaml.CORE_SCHEMA });
585
+ const data = loadYamlDocument(fs.readFileSync(profilePath, "utf-8"), (text) => yaml.load(text, { schema: yaml.CORE_SCHEMA }));
582
586
  const projects = isRecord(data) ? data.projects : undefined;
583
587
  if (!Array.isArray(projects)) {
584
588
  errorLog("getProjectDirs", `${PhrenError.MALFORMED_YAML}: Profile YAML missing valid "projects" array: ${profilePath}`);
@@ -2,6 +2,7 @@ import * as fs from "fs";
2
2
  import * as path from "path";
3
3
  import * as crypto from "crypto";
4
4
  import * as yaml from "js-yaml";
5
+ import { loadYamlDocument } from "./phren-core.js";
5
6
  import { phrenErr, PhrenError, phrenOk, forwardErr, getProjectDirs, readRootManifest, } from "./shared.js";
6
7
  import { defaultMachineName, getMachineName } from "./machine-identity.js";
7
8
  import { errorMessage, isValidProjectName } from "./utils.js";
@@ -54,7 +55,7 @@ export function listMachines(phrenPath) {
54
55
  return phrenErr(`machines.yaml not found. Run 'phren init' to set up your phren.`, PhrenError.FILE_NOT_FOUND);
55
56
  try {
56
57
  const raw = fs.readFileSync(machinesPath, "utf8");
57
- const parsed = yaml.load(raw, { schema: yaml.CORE_SCHEMA });
58
+ const parsed = loadYamlDocument(raw, (text) => yaml.load(text, { schema: yaml.CORE_SCHEMA }));
58
59
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
59
60
  return phrenErr(`machines.yaml is empty or not valid YAML. Check the file format or run 'phren doctor --fix'.`, PhrenError.MALFORMED_YAML);
60
61
  const cleaned = {};
@@ -214,7 +215,7 @@ export function listProfiles(phrenPath) {
214
215
  const full = path.join(profilesDir, file);
215
216
  try {
216
217
  const raw = fs.readFileSync(full, "utf8");
217
- const parsed = yaml.load(raw, { schema: yaml.CORE_SCHEMA });
218
+ const parsed = loadYamlDocument(raw, (text) => yaml.load(text, { schema: yaml.CORE_SCHEMA }));
218
219
  const data = parsed && typeof parsed === "object" && !Array.isArray(parsed)
219
220
  ? parsed
220
221
  : null;
@@ -2,6 +2,7 @@ import * as crypto from "crypto";
2
2
  import * as fs from "fs";
3
3
  import * as path from "path";
4
4
  import * as yaml from "js-yaml";
5
+ import { loadYamlDocument } from "./phren-core.js";
5
6
  import { readInstallPreferences } from "./init/preferences.js";
6
7
  import { debugLog } from "./shared.js";
7
8
  import { errorMessage } from "./utils.js";
@@ -63,7 +64,7 @@ export function readProjectConfig(phrenPath, project) {
63
64
  return cached.config;
64
65
  }
65
66
  try {
66
- const parsed = yaml.load(fs.readFileSync(configPath, "utf8"), { schema: yaml.CORE_SCHEMA });
67
+ const parsed = loadYamlDocument(fs.readFileSync(configPath, "utf8"), (text) => yaml.load(text, { schema: yaml.CORE_SCHEMA }));
67
68
  const config = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
68
69
  _projectConfigCache.set(configPath, { mtimeMs, config });
69
70
  return config;
@@ -671,7 +671,7 @@ function endTopicBuildCache() {
671
671
  function readProjectTopicsForBuild(phrenPath, project) {
672
672
  if (!_buildTopicCacheActive)
673
673
  return readProjectTopics(phrenPath, project);
674
- const key = `${phrenPath}${project}`;
674
+ const key = `${phrenPath}\u0000${project}`;
675
675
  const hit = _buildTopicCache.get(key);
676
676
  if (hit)
677
677
  return hit;
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Tail the live lookup-events log.
3
+ *
4
+ * `.runtime/lookup-events.jsonl` is append-only: every memory phren lands on
5
+ * during a search, and every memory a hook injects, is written as one JSON
6
+ * line. Two hosts follow it live — the web UI's Activity stream and the
7
+ * shell's graph watch mode — so the read-only tailing logic lives here once.
8
+ *
9
+ * Reads only the bytes appended since the last poll, which is far more robust
10
+ * across platforms than fs.watch, and survives the file being rotated or
11
+ * truncated underneath it.
12
+ */
13
+ import type { LookupEvent } from "../governance/activity.js";
14
+ export interface LookupTailOptions {
15
+ /**
16
+ * Start at the current end of the file so only events appended after
17
+ * construction are delivered. Callers wanting history use
18
+ * `readRecentLookups` for the backfill. Default true.
19
+ */
20
+ fromEnd?: boolean;
21
+ }
22
+ export declare class LookupTail {
23
+ private readonly logPath;
24
+ private offset;
25
+ private carry;
26
+ constructor(logPath: string, opts?: LookupTailOptions);
27
+ /**
28
+ * Raw JSON lines appended since the last poll, each already validated as
29
+ * parseable. Never throws: a logging or read failure yields nothing rather
30
+ * than breaking the caller's render or stream.
31
+ */
32
+ pollLines(): string[];
33
+ /** Parsed events appended since the last poll. */
34
+ poll(): LookupEvent[];
35
+ }
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Tail the live lookup-events log.
3
+ *
4
+ * `.runtime/lookup-events.jsonl` is append-only: every memory phren lands on
5
+ * during a search, and every memory a hook injects, is written as one JSON
6
+ * line. Two hosts follow it live — the web UI's Activity stream and the
7
+ * shell's graph watch mode — so the read-only tailing logic lives here once.
8
+ *
9
+ * Reads only the bytes appended since the last poll, which is far more robust
10
+ * across platforms than fs.watch, and survives the file being rotated or
11
+ * truncated underneath it.
12
+ */
13
+ import * as fs from "fs";
14
+ export class LookupTail {
15
+ logPath;
16
+ offset = 0;
17
+ carry = "";
18
+ constructor(logPath, opts = {}) {
19
+ this.logPath = logPath;
20
+ if (opts.fromEnd !== false) {
21
+ try {
22
+ this.offset = fs.existsSync(logPath) ? fs.statSync(logPath).size : 0;
23
+ }
24
+ catch {
25
+ this.offset = 0;
26
+ }
27
+ }
28
+ }
29
+ /**
30
+ * Raw JSON lines appended since the last poll, each already validated as
31
+ * parseable. Never throws: a logging or read failure yields nothing rather
32
+ * than breaking the caller's render or stream.
33
+ */
34
+ pollLines() {
35
+ let size;
36
+ try {
37
+ if (!fs.existsSync(this.logPath))
38
+ return [];
39
+ size = fs.statSync(this.logPath).size;
40
+ }
41
+ catch {
42
+ return [];
43
+ }
44
+ if (size < this.offset) {
45
+ // Rotated or truncated: start over rather than read garbage.
46
+ this.offset = 0;
47
+ this.carry = "";
48
+ }
49
+ if (size <= this.offset)
50
+ return [];
51
+ let chunk = "";
52
+ try {
53
+ const fd = fs.openSync(this.logPath, "r");
54
+ try {
55
+ const buf = Buffer.alloc(size - this.offset);
56
+ fs.readSync(fd, buf, 0, buf.length, this.offset);
57
+ chunk = buf.toString("utf8");
58
+ }
59
+ finally {
60
+ fs.closeSync(fd);
61
+ }
62
+ }
63
+ catch {
64
+ return [];
65
+ }
66
+ this.offset = size;
67
+ const lines = (this.carry + chunk).split("\n");
68
+ // A trailing partial line is kept until the writer finishes it.
69
+ this.carry = lines.pop() ?? "";
70
+ const out = [];
71
+ for (const line of lines) {
72
+ const trimmed = line.trim();
73
+ if (!trimmed)
74
+ continue;
75
+ try {
76
+ JSON.parse(trimmed);
77
+ out.push(trimmed);
78
+ }
79
+ catch {
80
+ // Skip malformed lines rather than failing the whole poll.
81
+ }
82
+ }
83
+ return out;
84
+ }
85
+ /** Parsed events appended since the last poll. */
86
+ poll() {
87
+ const out = [];
88
+ for (const line of this.pollLines()) {
89
+ try {
90
+ const parsed = JSON.parse(line);
91
+ if (parsed && typeof parsed.at === "string")
92
+ out.push(parsed);
93
+ }
94
+ catch {
95
+ // Already validated in pollLines; defensive only.
96
+ }
97
+ }
98
+ return out;
99
+ }
100
+ }
@@ -12,6 +12,13 @@ export type { GitContext } from "../cli/hooks-session.js";
12
12
  * middle snippet that legitimately fit.
13
13
  */
14
14
  export declare const SNIPPET_OVERHEAD_TOKENS = 24;
15
+ /** Query-relevance floor (see applyRelevanceFloor). A doc with no structural
16
+ * signal must clear this query-overlap score to be worth injecting; on the
17
+ * overlapScore scale (matched / max(2, min(tokens, 10))) ~0.12 means "shares at
18
+ * least one query token" — enough to drop priors-only noise without hurting
19
+ * recall. Cross-project docs face a higher bar. Tunable via
20
+ * PHREN_MIN_QUERY_RELEVANCE (0 disables the floor). */
21
+ declare const DEFAULT_MIN_QUERY_RELEVANCE = 0.12;
15
22
  export declare function detectTaskIntent(prompt: string): "debug" | "review" | "build" | "docs" | "skill" | "general";
16
23
  export declare function fileRelevanceBoost(filePath: string, changedFiles: Set<string>): number;
17
24
  export declare function branchMatchBoost(content: string, branch: string | undefined): number;
@@ -108,6 +115,27 @@ export interface SelectedSnippet {
108
115
  /** Mark snippet lines with stale citations (cited file missing or line content changed).
109
116
  * @internal Exported for tests. */
110
117
  export declare function markStaleCitations(snippet: string): string;
118
+ export { DEFAULT_MIN_QUERY_RELEVANCE };
119
+ /**
120
+ * Relevance floor: drop ranked docs that aren't actually relevant to *this*
121
+ * prompt, so the hook injects signal or nothing — never noise to fill a quota.
122
+ *
123
+ * `rankResults` intentionally scores on priors too (intent, recency, project,
124
+ * feedback history), so a doc can rank well with zero query overlap. That's the
125
+ * right call for *ordering*, but the wrong thing to *inject*. This stage keeps a
126
+ * doc only when it has a real connection to the prompt:
127
+ * - a structural signal: it's a changed file, or matches the branch name, or
128
+ * - it's a canonical doc for the project you're actually in, or
129
+ * - its text clears a query-overlap floor (higher for cross-project docs).
130
+ *
131
+ * When there's no usable query signal (no tokens) it is a no-op. Setting the
132
+ * floor to 0 (env PHREN_MIN_QUERY_RELEVANCE=0) disables it and restores the
133
+ * previous always-fill behavior.
134
+ */
135
+ export declare function applyRelevanceFloor(rows: DocRow[], keywords: string, gitCtx: {
136
+ branch?: string;
137
+ changedFiles?: Set<string>;
138
+ } | null, detectedProject: string | null, floor?: number): DocRow[];
111
139
  export declare function selectSnippets(rows: DocRow[], keywords: string, tokenBudget: number, lineBudget: number, charBudget: number): {
112
140
  selected: SelectedSnippet[];
113
141
  usedTokens: number;
@@ -39,6 +39,14 @@ const VERY_LOW_FOCUS_SNIPPET_SCORE = 0.14;
39
39
  export const SNIPPET_OVERHEAD_TOKENS = 24;
40
40
  const LOW_FOCUS_SNIPPET_LINE_CAP = 3;
41
41
  const LOW_FOCUS_SNIPPET_CHAR_FRACTION = 0.55;
42
+ /** Query-relevance floor (see applyRelevanceFloor). A doc with no structural
43
+ * signal must clear this query-overlap score to be worth injecting; on the
44
+ * overlapScore scale (matched / max(2, min(tokens, 10))) ~0.12 means "shares at
45
+ * least one query token" — enough to drop priors-only noise without hurting
46
+ * recall. Cross-project docs face a higher bar. Tunable via
47
+ * PHREN_MIN_QUERY_RELEVANCE (0 disables the floor). */
48
+ const DEFAULT_MIN_QUERY_RELEVANCE = 0.12;
49
+ const CROSS_PROJECT_MIN_QUERY_RELEVANCE = 0.25;
42
50
  const TASK_RESCUE_MIN_OVERLAP = 0.3;
43
51
  const TASK_RESCUE_OVERLAP_MARGIN = 0.12;
44
52
  const TASK_RESCUE_SCORE_MARGIN = 0.6;
@@ -854,6 +862,43 @@ export function markStaleCitations(snippet) {
854
862
  }
855
863
  return result.join("\n");
856
864
  }
865
+ export { DEFAULT_MIN_QUERY_RELEVANCE };
866
+ /**
867
+ * Relevance floor: drop ranked docs that aren't actually relevant to *this*
868
+ * prompt, so the hook injects signal or nothing — never noise to fill a quota.
869
+ *
870
+ * `rankResults` intentionally scores on priors too (intent, recency, project,
871
+ * feedback history), so a doc can rank well with zero query overlap. That's the
872
+ * right call for *ordering*, but the wrong thing to *inject*. This stage keeps a
873
+ * doc only when it has a real connection to the prompt:
874
+ * - a structural signal: it's a changed file, or matches the branch name, or
875
+ * - it's a canonical doc for the project you're actually in, or
876
+ * - its text clears a query-overlap floor (higher for cross-project docs).
877
+ *
878
+ * When there's no usable query signal (no tokens) it is a no-op. Setting the
879
+ * floor to 0 (env PHREN_MIN_QUERY_RELEVANCE=0) disables it and restores the
880
+ * previous always-fill behavior.
881
+ */
882
+ export function applyRelevanceFloor(rows, keywords, gitCtx, detectedProject, floor = DEFAULT_MIN_QUERY_RELEVANCE) {
883
+ if (!(floor > 0))
884
+ return rows;
885
+ const queryTokens = tokenizeForOverlap(keywords);
886
+ if (!queryTokens.length)
887
+ return rows; // no query signal to judge against
888
+ const changedFiles = gitCtx?.changedFiles ?? new Set();
889
+ const branch = gitCtx?.branch;
890
+ const crossFloor = Math.max(floor, CROSS_PROJECT_MIN_QUERY_RELEVANCE);
891
+ return rows.filter((doc) => {
892
+ if (fileRelevanceBoost(doc.path, changedFiles) > 0)
893
+ return true;
894
+ if (branchMatchBoost(doc.content, branch) > 0)
895
+ return true;
896
+ if (detectedProject && doc.project === detectedProject && doc.type === "canonical")
897
+ return true;
898
+ const isCrossProject = Boolean(detectedProject) && doc.project !== detectedProject;
899
+ return docOverlapScore(queryTokens, doc) >= (isCrossProject ? crossFloor : floor);
900
+ });
901
+ }
857
902
  export function selectSnippets(rows, keywords, tokenBudget, lineBudget, charBudget) {
858
903
  const selected = [];
859
904
  let usedTokens = 36;
@@ -2,6 +2,7 @@
2
2
  * Shell entry point: wires PhrenShell to stdin/stdout.
3
3
  * Extracted from shell.ts to keep the orchestrator under 300 lines.
4
4
  */
5
+ import type { ShellStartup } from "./startup.js";
5
6
  interface LiveStateHost {
6
7
  invalidateSubsectionsCache(): void;
7
8
  setMessage(message: string): void;
@@ -20,7 +21,7 @@ interface StartupIntroPlan {
20
21
  * animation frames raced the first dashboard repaint. Key delivery is now owned
21
22
  * by startShell, which hands the intro a one-shot waiter that consumes the key.
22
23
  */
23
- export type KeypressWaiter = () => Promise<void>;
24
+ export type { KeypressWaiter } from "./intro.js";
24
25
  export declare function resolveStartupIntroPlan(phrenPath: string, version?: string): StartupIntroPlan;
25
26
  export declare function startLiveStatePoller({ phrenPath, shell, repaint, isExiting, intervalMs, computeToken, }: {
26
27
  phrenPath: string;
@@ -30,5 +31,4 @@ export declare function startLiveStatePoller({ phrenPath, shell, repaint, isExit
30
31
  intervalMs?: number;
31
32
  computeToken?: (phrenPath: string) => string;
32
33
  }): () => void;
33
- export declare function startShell(phrenPath: string, profile: string): Promise<void>;
34
- export {};
34
+ export declare function startShell(phrenPath: string, profile: string, startup?: ShellStartup): Promise<void>;
@@ -3,20 +3,14 @@
3
3
  * Extracted from shell.ts to keep the orchestrator under 300 lines.
4
4
  */
5
5
  import { PhrenShell } from "./shell.js";
6
- import { style, clearScreen, paintFrame, enterFullscreen, exitFullscreen, shellStartupFrames, composeStartupFrame, fitFrame, } from "./render.js";
6
+ import { style, clearScreen, paintFrame, enterFullscreen, exitFullscreen, } from "./render.js";
7
7
  import { KeyDecoder, ESC_FLUSH_MS } from "./keys.js";
8
- import { createPhrenAnimator } from "../phren-art.js";
8
+ import { playSplash } from "./intro.js";
9
9
  import { errorMessage } from "../utils.js";
10
10
  import { computePhrenLiveStateToken } from "../shared.js";
11
11
  import { VERSION } from "../init/shared.js";
12
12
  import { loadShellState, saveShellState } from "./state-store.js";
13
13
  const LIVE_STATE_POLL_MS = 2000;
14
- function renderIntroFrame(lines) {
15
- paintFrame(fitFrame(lines));
16
- }
17
- function sleep(ms) {
18
- return new Promise((resolve) => setTimeout(resolve, ms));
19
- }
20
14
  const noopWaiter = () => Promise.resolve();
21
15
  export function resolveStartupIntroPlan(phrenPath, version = VERSION) {
22
16
  const state = loadShellState(phrenPath);
@@ -41,40 +35,17 @@ function markStartupIntroSeen(phrenPath, version = VERSION) {
41
35
  async function playStartupIntro(phrenPath, plan = resolveStartupIntroPlan(phrenPath), waitForAnyKeypress = noopWaiter) {
42
36
  if (!process.stdout.isTTY || plan.variant === "skip")
43
37
  return;
44
- const frames = shellStartupFrames(VERSION);
45
- const renderHint = plan.holdForKeypress
46
- ? `${style.dim("Press any key to enter")}`
47
- : `${style.dim("Loading shell…")}`;
48
- if (plan.variant === "full") {
49
- for (const frame of frames.slice(0, -1)) {
50
- renderIntroFrame(frame.split("\n"));
51
- await sleep(160);
52
- }
53
- }
54
- // Start animated phren during loading
55
- const animator = createPhrenAnimator({ facing: "right" });
56
- animator.start();
57
- function renderAnimatedFrame(hint) {
58
- renderIntroFrame(composeStartupFrame(animator.getFrame(), VERSION, hint));
59
- }
60
- // Animate during dwell/loading period
61
- if (plan.holdForKeypress) {
62
- const animInterval = setInterval(() => renderAnimatedFrame(renderHint), 200);
63
- renderAnimatedFrame(renderHint);
64
- await waitForAnyKeypress();
65
- clearInterval(animInterval);
66
- }
67
- else if (plan.dwellMs > 0) {
68
- const startTime = Date.now();
69
- while (Date.now() - startTime < plan.dwellMs) {
70
- renderAnimatedFrame(renderHint);
71
- await sleep(200);
72
- }
73
- }
74
- else {
75
- renderAnimatedFrame(renderHint);
76
- }
77
- animator.stop();
38
+ // The shell is already on the alternate screen; the splash paints in place.
39
+ // A full intro plays the wordmark reveal, a repeat launch opens on the
40
+ // finished wordmark, and either way the shimmer runs until dismissed.
41
+ await playSplash({
42
+ version: VERSION,
43
+ hint: plan.holdForKeypress ? "Press any key to enter" : "Loading shell…",
44
+ reveal: plan.variant === "full",
45
+ dwellMs: plan.dwellMs,
46
+ waitForKeypress: plan.holdForKeypress ? waitForAnyKeypress : undefined,
47
+ fullscreen: false,
48
+ });
78
49
  if (plan.markSeen) {
79
50
  markStartupIntroSeen(phrenPath);
80
51
  }
@@ -109,8 +80,8 @@ export function startLiveStatePoller({ phrenPath, shell, repaint, isExiting = ()
109
80
  clearInterval(poll);
110
81
  };
111
82
  }
112
- export async function startShell(phrenPath, profile) {
113
- const shell = new PhrenShell(phrenPath, profile);
83
+ export async function startShell(phrenPath, profile, startup = {}) {
84
+ const shell = new PhrenShell(phrenPath, profile, undefined, startup);
114
85
  if (!process.stdin.isTTY) {
115
86
  const { createInterface } = await import("readline");
116
87
  const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: process.stdin.isTTY ?? false });
@@ -169,6 +140,10 @@ export async function startShell(phrenPath, profile) {
169
140
  painting = false;
170
141
  }
171
142
  };
143
+ // The graph view animates (layout settle, fly-to) and finishes builds off
144
+ // the key path; give the shell a way to repaint without a keypress.
145
+ shell.setRepaintHandler(() => { if (!exiting && !introActive)
146
+ void repaint(); });
172
147
  let done;
173
148
  const exitPromise = new Promise((resolve) => { done = resolve; });
174
149
  const restoreTerminal = () => {
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Live coding agents on the knowledge graph.
3
+ *
4
+ * Watch mode shows what phren's memory is doing; this shows who is doing it.
5
+ * Agents are transient runtime state rather than memory, so they decorate the
6
+ * project nodes they are working in instead of becoming graph nodes of their
7
+ * own — the same shape `GraphWatch` uses, and it keeps `graph-core` (which is
8
+ * bundled for the browser) untouched.
9
+ */
10
+ import type { JoinedAgent } from "../../agents/types.js";
11
+ export interface GraphAgentsOptions {
12
+ pollMs?: number;
13
+ /** Injected in tests so nothing shells out and no timer runs. */
14
+ collect?: () => JoinedAgent[];
15
+ runFocus?: (argv: string[]) => boolean;
16
+ enabled?: boolean;
17
+ }
18
+ /** Run a provider-supplied focus command. Never throws. */
19
+ export declare function runFocusCommand(argv: string[]): boolean;
20
+ export declare class GraphAgents {
21
+ readonly phrenPath: string;
22
+ readonly profile: string;
23
+ agents: JoinedAgent[];
24
+ /** Index into `agents`; -1 when nothing is highlighted. */
25
+ highlighted: number;
26
+ enabled: boolean;
27
+ private timer;
28
+ private onUpdate;
29
+ private readonly pollMs;
30
+ private readonly collectFn;
31
+ private readonly runFocus;
32
+ constructor(phrenPath: string, profile: string, opts?: GraphAgentsOptions);
33
+ get running(): boolean;
34
+ private polledOnce;
35
+ start(onUpdate: () => void): void;
36
+ stop(): void;
37
+ toggle(): boolean;
38
+ /** Refresh the list. Never throws; a failing provider just yields nothing. */
39
+ poll(): JoinedAgent[];
40
+ /** Agents grouped by the project they are working in. */
41
+ byProject(): Map<string, JoinedAgent[]>;
42
+ get current(): JoinedAgent | null;
43
+ /** Move the highlight; wraps, and starts from the first agent. */
44
+ cycle(delta: number): JoinedAgent | null;
45
+ clearHighlight(): void;
46
+ /** Bring the highlighted agent to the front in whatever is hosting it. */
47
+ focusCurrent(): JoinedAgent | null;
48
+ }