@phren/agent 0.1.15 → 0.3.5
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.
- package/README.md +86 -0
- package/dist/agent-loop/index.js +239 -65
- package/dist/agent-loop/stream.js +212 -29
- package/dist/agent-loop/types.js +15 -2
- package/dist/checkpoint.js +103 -22
- package/dist/commands/info.js +30 -15
- package/dist/commands/model.js +6 -2
- package/dist/commands/review.js +183 -0
- package/dist/commands/session.js +70 -7
- package/dist/commands.js +168 -12
- package/dist/config.js +87 -10
- package/dist/context/compactor.js +239 -0
- package/dist/context/pruner.js +39 -13
- package/dist/context/token-counter.js +33 -1
- package/dist/custom-commands.js +69 -0
- package/dist/guards/repeat-tool-reminder.js +75 -0
- package/dist/headless.js +115 -0
- package/dist/herdr-hooks.js +71 -0
- package/dist/index.js +351 -48
- package/dist/mcp-client.js +434 -73
- package/dist/mcp-oauth.js +121 -0
- package/dist/memory/anti-patterns.js +7 -3
- package/dist/memory/auto-capture.js +7 -3
- package/dist/memory/context.js +92 -73
- package/dist/memory/project-context.js +24 -5
- package/dist/memory/provenance.js +15 -0
- package/dist/memory/review-triage.js +166 -0
- package/dist/memory/session.js +36 -1
- package/dist/models.js +152 -19
- package/dist/multi/child-entry.js +65 -10
- package/dist/multi/diff-renderer.js +3 -3
- package/dist/multi/markdown.js +125 -27
- package/dist/multi/provider-manager.js +8 -0
- package/dist/multi/publish.js +72 -0
- package/dist/multi/spawner.js +45 -4
- package/dist/multi/syntax-highlight.js +25 -4
- package/dist/multi/types.js +1 -1
- package/dist/permissions/allowlist.js +86 -13
- package/dist/permissions/checker.js +42 -7
- package/dist/permissions/kernel-sandbox.js +197 -0
- package/dist/permissions/prompt.js +10 -1
- package/dist/permissions/sandbox.js +40 -17
- package/dist/providers/anthropic.js +154 -7
- package/dist/providers/codex-auth.js +28 -0
- package/dist/providers/codex.js +134 -23
- package/dist/providers/history.js +35 -0
- package/dist/providers/ollama.js +37 -6
- package/dist/providers/openai-compat.js +171 -74
- package/dist/providers/openrouter.js +47 -17
- package/dist/providers/replay.js +62 -0
- package/dist/providers/resolve.js +41 -7
- package/dist/providers/retry.js +38 -5
- package/dist/providers/types.js +9 -1
- package/dist/repl.js +47 -5
- package/dist/session/log.js +217 -0
- package/dist/session/persist.js +190 -0
- package/dist/settings.js +42 -26
- package/dist/system-prompt.js +18 -2
- package/dist/tools/apply-patch.js +355 -0
- package/dist/tools/edit-engine.js +287 -0
- package/dist/tools/edit-file.js +86 -27
- package/dist/tools/grep.js +25 -10
- package/dist/tools/lint-test.js +0 -22
- package/dist/tools/mcp-resources.js +51 -6
- package/dist/tools/phren-finding.js +12 -4
- package/dist/tools/phren-search.js +7 -2
- package/dist/tools/read-file.js +37 -9
- package/dist/tools/read-image.js +76 -0
- package/dist/tools/registry.js +27 -5
- package/dist/tools/shell.js +134 -71
- package/dist/tools/skill.js +20 -20
- package/dist/tools/spawn-agent.js +77 -13
- package/dist/tools/update-plan.js +48 -0
- package/dist/tools/web-fetch.js +110 -12
- package/dist/tools/web-search.js +4 -4
- package/dist/tui/components/App.js +98 -26
- package/dist/tui/components/ApprovalPanel.js +8 -0
- package/dist/tui/components/InputArea.js +5 -5
- package/dist/tui/components/ModelPicker.js +43 -0
- package/dist/tui/components/PhrenInput.js +10 -5
- package/dist/tui/components/PlanReview.js +7 -0
- package/dist/tui/components/ShortcutHelp.js +5 -0
- package/dist/tui/components/StatusBar.js +46 -20
- package/dist/tui/components/SteerQueue.js +1 -1
- package/dist/tui/components/ThinkingIndicator.js +6 -4
- package/dist/tui/components/ToolCall.js +10 -4
- package/dist/tui/components/ToolDetail.js +21 -0
- package/dist/tui/help.js +6 -0
- package/dist/tui/hooks/useKeyboardShortcuts.js +15 -1
- package/dist/tui/index.js +0 -1
- package/dist/tui/ink-entry.js +317 -33
- package/dist/tui/tool-render.js +1 -1
- package/dist/user-hooks.js +171 -0
- package/package.json +14 -8
- package/dist/multi/multi-commands.js +0 -170
- package/dist/multi/multi-events.js +0 -98
- package/dist/multi/multi-render.js +0 -147
- package/dist/multi/pane.js +0 -28
- package/dist/multi/tui-multi.js +0 -200
- package/dist/permissions/privacy.js +0 -248
- package/dist/tui/components/AgentMessage.js +0 -5
- package/dist/tui/components/ChatMessage.js +0 -23
- package/dist/tui/components/CodeBlock.js +0 -8
- package/dist/tui/components/Separator.js +0 -7
- package/dist/tui/components/StreamingText.js +0 -5
- package/dist/tui/components/UserMessage.js +0 -5
- package/dist/tui/menu-mode.js +0 -86
- package/dist/tui/mouse.js +0 -71
- package/dist/tui/terminal-control.js +0 -62
- package/dist/tui.js +0 -781
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
2
|
+
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
3
|
+
import { createServer } from "node:http";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
/** Per-server credentials; PKCE verifiers and callback state stay in memory. */
|
|
7
|
+
export class McpOAuthProvider {
|
|
8
|
+
options;
|
|
9
|
+
redirectUrl;
|
|
10
|
+
clientMetadata;
|
|
11
|
+
credentials = {};
|
|
12
|
+
file;
|
|
13
|
+
ready;
|
|
14
|
+
verifier;
|
|
15
|
+
nonce = randomBytes(32).toString("hex");
|
|
16
|
+
server;
|
|
17
|
+
pending;
|
|
18
|
+
rejectPending;
|
|
19
|
+
timer;
|
|
20
|
+
saving = Promise.resolve();
|
|
21
|
+
constructor(url, options = {}, directory = process.env.PHREN_MCP_AUTH_DIR ?? path.join(homedir(), ".phren", "agent", "mcp-auth")) {
|
|
22
|
+
this.options = options;
|
|
23
|
+
const port = options.callbackPort ?? 14557;
|
|
24
|
+
if (!Number.isInteger(port) || port < 1024 || port > 65535)
|
|
25
|
+
throw new Error("Invalid MCP OAuth callback port");
|
|
26
|
+
this.redirectUrl = `http://127.0.0.1:${port}/callback`;
|
|
27
|
+
this.clientMetadata = { client_name: "phren-agent", redirect_uris: [this.redirectUrl],
|
|
28
|
+
grant_types: ["authorization_code", "refresh_token"], response_types: ["code"],
|
|
29
|
+
token_endpoint_auth_method: options.clientSecret ? "client_secret_post" : "none", ...(options.scope ? { scope: options.scope } : {}) };
|
|
30
|
+
const key = createHash("sha256").update(`${new URL(url).href}\n${options.clientId ?? ""}\n${this.redirectUrl}`).digest("hex");
|
|
31
|
+
this.file = path.join(directory, `${key}.json`);
|
|
32
|
+
this.ready = readFile(this.file, "utf8").then(raw => {
|
|
33
|
+
const saved = JSON.parse(raw);
|
|
34
|
+
if (saved && typeof saved === "object")
|
|
35
|
+
this.credentials = saved;
|
|
36
|
+
}).catch(() => { });
|
|
37
|
+
}
|
|
38
|
+
state() { return this.nonce; }
|
|
39
|
+
async clientInformation() {
|
|
40
|
+
await this.ready;
|
|
41
|
+
return this.options.clientId ? { client_id: this.options.clientId, ...(this.options.clientSecret ? { client_secret: this.options.clientSecret } : {}) } : this.credentials.client;
|
|
42
|
+
}
|
|
43
|
+
async saveClientInformation(client) { await this.ready; this.credentials.client = client; await this.save(); }
|
|
44
|
+
async tokens() { await this.ready; return this.credentials.tokens; }
|
|
45
|
+
async saveTokens(tokens) { await this.ready; this.credentials.tokens = tokens; await this.save(); }
|
|
46
|
+
saveCodeVerifier(verifier) { this.verifier = verifier; }
|
|
47
|
+
codeVerifier() { if (!this.verifier)
|
|
48
|
+
throw new Error("Missing MCP OAuth PKCE verifier"); return this.verifier; }
|
|
49
|
+
async invalidateCredentials(scope) {
|
|
50
|
+
await this.ready;
|
|
51
|
+
if (scope === "all" || scope === "client")
|
|
52
|
+
delete this.credentials.client;
|
|
53
|
+
if (scope === "all" || scope === "tokens")
|
|
54
|
+
delete this.credentials.tokens;
|
|
55
|
+
if (scope === "all" || scope === "verifier")
|
|
56
|
+
this.verifier = undefined;
|
|
57
|
+
await this.save();
|
|
58
|
+
}
|
|
59
|
+
save() {
|
|
60
|
+
const raw = JSON.stringify(this.credentials);
|
|
61
|
+
this.saving = this.saving.catch(() => { }).then(async () => {
|
|
62
|
+
await mkdir(path.dirname(this.file), { recursive: true, mode: 0o700 });
|
|
63
|
+
const temporary = `${this.file}.${randomBytes(8).toString("hex")}`;
|
|
64
|
+
await writeFile(temporary, raw, { mode: 0o600, flag: "wx" });
|
|
65
|
+
await rename(temporary, this.file);
|
|
66
|
+
});
|
|
67
|
+
return this.saving;
|
|
68
|
+
}
|
|
69
|
+
async redirectToAuthorization(url) {
|
|
70
|
+
if (this.pending)
|
|
71
|
+
throw new Error("MCP authorization is already pending");
|
|
72
|
+
this.pending = new Promise((resolve, reject) => {
|
|
73
|
+
this.rejectPending = reject;
|
|
74
|
+
this.server = createServer((request, response) => {
|
|
75
|
+
response.setHeader("Cache-Control", "no-store");
|
|
76
|
+
response.setHeader("Content-Type", "text/plain; charset=utf-8");
|
|
77
|
+
const callback = new URL(request.url ?? "/", this.redirectUrl);
|
|
78
|
+
if (request.method !== "GET" || callback.pathname !== "/callback" || callback.searchParams.get("state") !== this.nonce) {
|
|
79
|
+
response.writeHead(400);
|
|
80
|
+
response.end("Invalid authorization callback.");
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
const code = callback.searchParams.get("code");
|
|
84
|
+
if (callback.searchParams.has("error") || !code) {
|
|
85
|
+
response.writeHead(400);
|
|
86
|
+
response.end("Authorization was not completed.");
|
|
87
|
+
reject(new Error("MCP authorization was denied"));
|
|
88
|
+
}
|
|
89
|
+
else {
|
|
90
|
+
response.end("Authorization received. You can return to phren-agent.");
|
|
91
|
+
resolve(code);
|
|
92
|
+
}
|
|
93
|
+
this.closeListener();
|
|
94
|
+
});
|
|
95
|
+
this.server.once("error", reject);
|
|
96
|
+
this.timer = setTimeout(() => { reject(new Error("MCP authorization timed out after 5 minutes")); this.closeListener(); }, 300_000);
|
|
97
|
+
});
|
|
98
|
+
this.pending.catch(() => { });
|
|
99
|
+
await new Promise((resolve, reject) => {
|
|
100
|
+
this.server.once("error", reject);
|
|
101
|
+
this.server.listen(Number(new URL(this.redirectUrl).port), "127.0.0.1", resolve);
|
|
102
|
+
});
|
|
103
|
+
process.stderr.write(`Authorize MCP access in your browser:\n${url.href}\n`);
|
|
104
|
+
}
|
|
105
|
+
async authorizationCode() {
|
|
106
|
+
if (!this.pending)
|
|
107
|
+
throw new Error("MCP server requires authorization; enable oauth in its configuration");
|
|
108
|
+
try {
|
|
109
|
+
return await this.pending;
|
|
110
|
+
}
|
|
111
|
+
finally {
|
|
112
|
+
this.pending = undefined;
|
|
113
|
+
this.rejectPending = undefined;
|
|
114
|
+
this.closeListener();
|
|
115
|
+
this.nonce = randomBytes(32).toString("hex");
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
closeListener() { if (this.timer)
|
|
119
|
+
clearTimeout(this.timer); this.server?.close(); this.server = undefined; }
|
|
120
|
+
close() { this.rejectPending?.(new Error("MCP connection closed")); this.closeListener(); }
|
|
121
|
+
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { addFindingToFile } from "@phren/cli/shared/content";
|
|
2
|
+
import { agentProvenance } from "./provenance.js";
|
|
2
3
|
export class AntiPatternTracker {
|
|
3
4
|
attempts = [];
|
|
4
5
|
/** Record a tool execution result. */
|
|
@@ -47,7 +48,7 @@ export class AntiPatternTracker {
|
|
|
47
48
|
/**
|
|
48
49
|
* Save top 3 anti-patterns as findings at session end.
|
|
49
50
|
*/
|
|
50
|
-
async flushAntiPatterns(ctx) {
|
|
51
|
+
async flushAntiPatterns(ctx, sessionId) {
|
|
51
52
|
if (!ctx.project)
|
|
52
53
|
return 0;
|
|
53
54
|
const patterns = this.extractAntiPatterns().slice(0, 3);
|
|
@@ -57,7 +58,10 @@ export class AntiPatternTracker {
|
|
|
57
58
|
try {
|
|
58
59
|
for (const p of patterns) {
|
|
59
60
|
const finding = `[anti-pattern] ${p.tool}: failed with ${p.failedInput.slice(0, 100)} (${p.failedOutput.slice(0, 80)}), succeeded with ${p.succeededInput.slice(0, 100)}`;
|
|
60
|
-
|
|
61
|
+
addFindingToFile(ctx.phrenPath, ctx.project, finding, undefined, {
|
|
62
|
+
provenance: agentProvenance(sessionId),
|
|
63
|
+
...(sessionId ? { sessionId } : {}),
|
|
64
|
+
});
|
|
61
65
|
saved++;
|
|
62
66
|
}
|
|
63
67
|
}
|
|
@@ -3,7 +3,8 @@
|
|
|
3
3
|
* Runs after each turn on error results only.
|
|
4
4
|
*/
|
|
5
5
|
import * as crypto from "crypto";
|
|
6
|
-
import {
|
|
6
|
+
import { addFindingToFile } from "@phren/cli/shared/content";
|
|
7
|
+
import { agentProvenance } from "./provenance.js";
|
|
7
8
|
const SESSION_CAP = 10;
|
|
8
9
|
const COOLDOWN_MS = 30_000;
|
|
9
10
|
/** Patterns that indicate capturable knowledge in error output. */
|
|
@@ -33,7 +34,7 @@ function hashText(text) {
|
|
|
33
34
|
* Analyze error output and auto-capture relevant findings.
|
|
34
35
|
* Returns the number of findings captured this call.
|
|
35
36
|
*/
|
|
36
|
-
export async function analyzeAndCapture(ctx, errorOutput, state) {
|
|
37
|
+
export async function analyzeAndCapture(ctx, errorOutput, state, sessionId) {
|
|
37
38
|
if (!ctx.project)
|
|
38
39
|
return 0;
|
|
39
40
|
if (state.captured >= SESSION_CAP)
|
|
@@ -56,7 +57,10 @@ export async function analyzeAndCapture(ctx, errorOutput, state) {
|
|
|
56
57
|
if (state.hashes.has(hash))
|
|
57
58
|
continue;
|
|
58
59
|
try {
|
|
59
|
-
|
|
60
|
+
addFindingToFile(ctx.phrenPath, ctx.project, finding, undefined, {
|
|
61
|
+
provenance: agentProvenance(sessionId),
|
|
62
|
+
...(sessionId ? { sessionId } : {}),
|
|
63
|
+
});
|
|
60
64
|
state.hashes.add(hash);
|
|
61
65
|
captured++;
|
|
62
66
|
}
|
package/dist/memory/context.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import * as fs from "fs";
|
|
2
2
|
import * as os from "os";
|
|
3
3
|
import * as path from "path";
|
|
4
|
-
import { findPhrenPath
|
|
4
|
+
import { findPhrenPath } from "@phren/cli/paths";
|
|
5
5
|
import { resolveRuntimeProfile } from "@phren/cli/runtime-profile";
|
|
6
|
-
import { buildIndex } from "@phren/cli/shared";
|
|
7
|
-
import { searchKnowledgeRows, rankResults } from "@phren/cli/shared/retrieval";
|
|
6
|
+
import { buildIndex, detectProject } from "@phren/cli/shared";
|
|
7
|
+
import { searchKnowledgeRows, rankResults, isInjectableDocType } from "@phren/cli/shared/retrieval";
|
|
8
|
+
import { storeAwareProjectPath } from "@phren/cli/store-routing";
|
|
8
9
|
import { readTasks } from "@phren/cli/data/tasks";
|
|
9
10
|
import { readFindings } from "@phren/cli/data/access";
|
|
10
11
|
/** Try to find phren path and detect the active project from cwd. */
|
|
@@ -21,30 +22,10 @@ export async function buildPhrenContext(projectOverride) {
|
|
|
21
22
|
let project = projectOverride ?? null;
|
|
22
23
|
if (!project) {
|
|
23
24
|
try {
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
try {
|
|
29
|
-
const configPath = path.join(dir, "project.yaml");
|
|
30
|
-
if (fs.existsSync(configPath)) {
|
|
31
|
-
const content = fs.readFileSync(configPath, "utf-8");
|
|
32
|
-
const sourceMatch = content.match(/source:\s*(.+)/);
|
|
33
|
-
if (sourceMatch?.[1]) {
|
|
34
|
-
const sourcePath = sourceMatch[1].trim().replace(/^['"]|['"]$/g, "");
|
|
35
|
-
if (cwd.startsWith(sourcePath) || cwd === sourcePath) {
|
|
36
|
-
project = name;
|
|
37
|
-
break;
|
|
38
|
-
}
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
catch { /* skip */ }
|
|
43
|
-
if (path.basename(cwd) === name) {
|
|
44
|
-
project = name;
|
|
45
|
-
break;
|
|
46
|
-
}
|
|
47
|
-
}
|
|
25
|
+
// The CLI's own resolver: reads phren.project.yaml sourcePath entries,
|
|
26
|
+
// handles project-local installs, team stores, git worktrees, and picks
|
|
27
|
+
// the longest matching sourcePath so nested projects resolve correctly.
|
|
28
|
+
project = detectProject(phrenPath, process.cwd(), profile || undefined);
|
|
48
29
|
}
|
|
49
30
|
catch { /* no project detection */ }
|
|
50
31
|
}
|
|
@@ -57,7 +38,10 @@ export async function buildPhrenContext(projectOverride) {
|
|
|
57
38
|
/** Read truths.md pinned entries for a project. */
|
|
58
39
|
function readTruths(phrenPath, project) {
|
|
59
40
|
try {
|
|
60
|
-
|
|
41
|
+
// Store-aware: upsertCanonical writes via storeAwareProjectPath, so team-store
|
|
42
|
+
// truths live under the store root, not necessarily <phrenPath>/<project>/.
|
|
43
|
+
const truthsPath = storeAwareProjectPath(phrenPath, project, "truths.md")
|
|
44
|
+
?? path.join(phrenPath, project, "truths.md");
|
|
61
45
|
if (!fs.existsSync(truthsPath))
|
|
62
46
|
return [];
|
|
63
47
|
const content = fs.readFileSync(truthsPath, "utf-8");
|
|
@@ -67,53 +51,71 @@ function readTruths(phrenPath, project) {
|
|
|
67
51
|
return [];
|
|
68
52
|
}
|
|
69
53
|
}
|
|
70
|
-
const CLAUDE_MD_MAX_CHARS = 4000;
|
|
71
54
|
/**
|
|
72
|
-
*
|
|
73
|
-
*
|
|
55
|
+
* Budget for all instruction files together. Codex's default is 32 KiB; the
|
|
56
|
+
* old 4,000-char cap cut a typical monorepo AGENTS.md off after its first
|
|
57
|
+
* screen.
|
|
58
|
+
*/
|
|
59
|
+
export const RULE_FILES_MAX_CHARS = 32_000;
|
|
60
|
+
/**
|
|
61
|
+
* Collect project rule files (AGENTS.md and legacy CLAUDE.md) by walking up from cwd
|
|
62
|
+
* to the filesystem root, then checking the user-level ~/.claude/CLAUDE.md.
|
|
74
63
|
* Returns entries most-specific first (cwd → parent → ... → user-level).
|
|
75
64
|
*/
|
|
76
|
-
function
|
|
65
|
+
function collectRuleFiles() {
|
|
77
66
|
const seen = new Set();
|
|
78
67
|
const results = [];
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
const content = fs.readFileSync(resolved, "utf-8").trim();
|
|
89
|
-
if (content) {
|
|
90
|
-
results.push({ filePath: resolved, content });
|
|
91
|
-
}
|
|
92
|
-
}
|
|
68
|
+
const read = (resolved) => {
|
|
69
|
+
if (seen.has(resolved))
|
|
70
|
+
return;
|
|
71
|
+
seen.add(resolved);
|
|
72
|
+
try {
|
|
73
|
+
if (fs.existsSync(resolved)) {
|
|
74
|
+
const content = fs.readFileSync(resolved, "utf-8").trim();
|
|
75
|
+
if (content)
|
|
76
|
+
results.push({ filePath: resolved, content });
|
|
93
77
|
}
|
|
94
|
-
catch { /* skip unreadable */ }
|
|
95
78
|
}
|
|
79
|
+
catch { /* skip unreadable */ }
|
|
80
|
+
};
|
|
81
|
+
let dir = process.cwd();
|
|
82
|
+
while (true) {
|
|
83
|
+
read(path.resolve(dir, "AGENTS.md"));
|
|
84
|
+
read(path.resolve(dir, "CLAUDE.md"));
|
|
96
85
|
const parent = path.dirname(dir);
|
|
97
86
|
if (parent === dir)
|
|
98
87
|
break; // reached root
|
|
99
88
|
dir = parent;
|
|
100
89
|
}
|
|
101
|
-
//
|
|
102
|
-
|
|
103
|
-
if (
|
|
104
|
-
|
|
105
|
-
try {
|
|
106
|
-
if (fs.existsSync(userLevel)) {
|
|
107
|
-
const content = fs.readFileSync(userLevel, "utf-8").trim();
|
|
108
|
-
if (content) {
|
|
109
|
-
results.push({ filePath: userLevel, content });
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
catch { /* skip */ }
|
|
90
|
+
// PHREN_AGENT_USER_RULES=off skips the user-level file (benchmarks and CI
|
|
91
|
+
// runs should not inherit one person's global instructions).
|
|
92
|
+
if (process.env.PHREN_AGENT_USER_RULES !== "off") {
|
|
93
|
+
read(path.resolve(os.homedir(), ".claude", "CLAUDE.md"));
|
|
114
94
|
}
|
|
115
95
|
return results;
|
|
116
96
|
}
|
|
97
|
+
/**
|
|
98
|
+
* The "## Project instructions" section from AGENTS.md / CLAUDE.md files, or
|
|
99
|
+
* "" when there are none. Independent of a phren store: a repo's own
|
|
100
|
+
* instructions apply whether or not phren memory is set up.
|
|
101
|
+
*/
|
|
102
|
+
export function buildProjectInstructions(maxChars = RULE_FILES_MAX_CHARS) {
|
|
103
|
+
try {
|
|
104
|
+
const ruleFiles = collectRuleFiles();
|
|
105
|
+
if (ruleFiles.length === 0)
|
|
106
|
+
return "";
|
|
107
|
+
let combined = ruleFiles
|
|
108
|
+
.map((f) => `<!-- ${f.filePath} -->\n${f.content}`)
|
|
109
|
+
.join("\n\n---\n\n");
|
|
110
|
+
if (combined.length > maxChars) {
|
|
111
|
+
combined = combined.slice(0, maxChars) + "\n\n<!-- truncated -->";
|
|
112
|
+
}
|
|
113
|
+
return `## Project instructions\n\n${combined}`;
|
|
114
|
+
}
|
|
115
|
+
catch {
|
|
116
|
+
return "";
|
|
117
|
+
}
|
|
118
|
+
}
|
|
117
119
|
/** Build a context string from phren knowledge to inject into the system prompt. */
|
|
118
120
|
export async function buildContextSnippet(ctx, taskKeywords) {
|
|
119
121
|
const sections = [];
|
|
@@ -164,21 +166,34 @@ export async function buildContextSnippet(ctx, taskKeywords) {
|
|
|
164
166
|
}
|
|
165
167
|
catch { /* silent */ }
|
|
166
168
|
}
|
|
167
|
-
// Section 4: CLAUDE.md
|
|
169
|
+
// Section 4: project rule files (AGENTS.md / legacy CLAUDE.md), cwd → parents → ~/.claude/CLAUDE.md
|
|
170
|
+
const instructions = buildProjectInstructions();
|
|
171
|
+
if (instructions)
|
|
172
|
+
sections.push(instructions);
|
|
173
|
+
// Section 5: Available skills catalog — the model should know what skills
|
|
174
|
+
// exist (name + description) instead of guessing names for run_skill.
|
|
168
175
|
try {
|
|
169
|
-
const
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
combined = combined.slice(0, CLAUDE_MD_MAX_CHARS) + "\n\n<!-- truncated -->";
|
|
176
|
-
}
|
|
177
|
-
sections.push(`## CLAUDE.md\n\n${combined}`);
|
|
176
|
+
const { getScopedSkills } = await import("@phren/cli/skill/registry");
|
|
177
|
+
const skills = getScopedSkills(ctx.phrenPath, ctx.profile, ctx.project ?? undefined)
|
|
178
|
+
.filter((s) => s.enabled);
|
|
179
|
+
if (skills.length > 0) {
|
|
180
|
+
const lines = skills.slice(0, 20).map((s) => `- ${s.name}${s.description ? ` — ${s.description}` : ""}`);
|
|
181
|
+
sections.push(`## Available skills (invoke with run_skill)\n\n${lines.join("\n")}`);
|
|
178
182
|
}
|
|
179
183
|
}
|
|
180
184
|
catch { /* silent */ }
|
|
181
|
-
// Section
|
|
185
|
+
// Section 6: Review queue awareness — count + top items, clearly labeled as
|
|
186
|
+
// unverified so candidates are visible without leaking as facts.
|
|
187
|
+
if (ctx.project) {
|
|
188
|
+
try {
|
|
189
|
+
const { getQueueStatus, formatQueueContextSection } = await import("./review-triage.js");
|
|
190
|
+
const section = formatQueueContextSection(getQueueStatus(ctx, 3));
|
|
191
|
+
if (section)
|
|
192
|
+
sections.push(section);
|
|
193
|
+
}
|
|
194
|
+
catch { /* silent */ }
|
|
195
|
+
}
|
|
196
|
+
// Section 7: FTS5 search
|
|
182
197
|
try {
|
|
183
198
|
const db = await buildIndex(ctx.phrenPath, ctx.profile || undefined);
|
|
184
199
|
const result = await searchKnowledgeRows(db, {
|
|
@@ -189,8 +204,12 @@ export async function buildContextSnippet(ctx, taskKeywords) {
|
|
|
189
204
|
phrenPath: ctx.phrenPath,
|
|
190
205
|
});
|
|
191
206
|
const ranked = rankResults(result.rows ?? [], taskKeywords, null, ctx.project || null, ctx.phrenPath, db);
|
|
192
|
-
|
|
193
|
-
|
|
207
|
+
// Automatic injection path: drop non-injectable doc types (notes, review-queue).
|
|
208
|
+
// Notes are the user's private scratch space and review.md is a quarantine of
|
|
209
|
+
// unapproved candidates — neither may reach a prompt without an explicit search.
|
|
210
|
+
const injectable = ranked.filter((r) => isInjectableDocType(r.type ?? ""));
|
|
211
|
+
if (injectable.length > 0) {
|
|
212
|
+
const snippets = injectable.slice(0, 5).map((r) => {
|
|
194
213
|
const content = r.content?.slice(0, 400) ?? "";
|
|
195
214
|
return `[${r.project}/${r.filename}] ${content}`;
|
|
196
215
|
});
|
|
@@ -29,10 +29,12 @@ export function loadProjectContext(ctx) {
|
|
|
29
29
|
}
|
|
30
30
|
}
|
|
31
31
|
/**
|
|
32
|
-
* Run a lightweight LLM reflection at session end
|
|
33
|
-
*
|
|
32
|
+
* Run a lightweight LLM reflection at session end: one call, two outputs.
|
|
33
|
+
* Key-learning bullets append to agent-context.md (warm start), and candidate
|
|
34
|
+
* knowledge items route through the same graduated confidence pipeline as
|
|
35
|
+
* compaction (≥0.8 finding, 0.5–0.8 review queue, below dropped).
|
|
34
36
|
*/
|
|
35
|
-
export async function evolveProjectContext(ctx, provider, sessionMessages) {
|
|
37
|
+
export async function evolveProjectContext(ctx, provider, sessionMessages, opts) {
|
|
36
38
|
const file = contextPath(ctx);
|
|
37
39
|
if (!file)
|
|
38
40
|
return;
|
|
@@ -55,15 +57,32 @@ export async function evolveProjectContext(ctx, provider, sessionMessages) {
|
|
|
55
57
|
.join("\n");
|
|
56
58
|
const reflectionPrompt = "Based on this conversation excerpt, extract 2-4 key learnings about this project " +
|
|
57
59
|
"(patterns, pitfalls, architecture decisions, important paths/configs). " +
|
|
58
|
-
"Be extremely concise — one line per point. Output only the bullet points,
|
|
60
|
+
"Be extremely concise — one line per point. Output only the bullet points, then a final section:\n\n" +
|
|
61
|
+
'## Knowledge\nA fenced json block: {"items":[{"text":"...","confidence":0.9,"kind":"finding|gotcha|decision"}]}\n' +
|
|
62
|
+
'Only durable, non-obvious knowledge worth remembering across sessions. Confidence is YOUR certainty, 0 to 1. Use {"items":[]} if nothing qualifies.\n\n' +
|
|
59
63
|
condensed;
|
|
60
64
|
try {
|
|
61
65
|
const response = await provider.chat("You are a concise technical note-taker.", [{ role: "user", content: reflectionPrompt }], []);
|
|
62
|
-
const
|
|
66
|
+
const fullText = response.content
|
|
63
67
|
.filter((b) => b.type === "text")
|
|
64
68
|
.map((b) => b.text)
|
|
65
69
|
.join("\n")
|
|
66
70
|
.trim();
|
|
71
|
+
// Split off the knowledge section; the bullets before it feed warm start.
|
|
72
|
+
const reflection = fullText.split(/^##\s*Knowledge\b/im)[0].trim();
|
|
73
|
+
// Route extracted knowledge through the graduated pipeline (best effort).
|
|
74
|
+
try {
|
|
75
|
+
const { extractKnowledgeItems, routeKnowledgeItems, resolveCompactionConfig } = await import("../context/compactor.js");
|
|
76
|
+
const items = extractKnowledgeItems(fullText);
|
|
77
|
+
if (items.length > 0) {
|
|
78
|
+
await routeKnowledgeItems(items, {
|
|
79
|
+
phrenCtx: ctx,
|
|
80
|
+
sessionId: opts?.sessionId,
|
|
81
|
+
config: resolveCompactionConfig(),
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
catch { /* best effort */ }
|
|
67
86
|
if (!reflection || reflection.length < 10)
|
|
68
87
|
return;
|
|
69
88
|
const date = new Date().toISOString().slice(0, 10);
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Provenance for findings the agent writes into phren.
|
|
3
|
+
*
|
|
4
|
+
* Every write path (explicit tool, auto-capture, anti-patterns, compaction)
|
|
5
|
+
* goes through this so findings are traceable to the session that produced
|
|
6
|
+
* them and can be staleness-aged by the CLI's trust filter.
|
|
7
|
+
*/
|
|
8
|
+
export function agentProvenance(sessionId, model) {
|
|
9
|
+
return {
|
|
10
|
+
source: "agent",
|
|
11
|
+
tool: "phren-agent",
|
|
12
|
+
...(sessionId ? { session_id: sessionId } : {}),
|
|
13
|
+
...(model ? { model } : {}),
|
|
14
|
+
};
|
|
15
|
+
}
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import { readReviewQueue, dequeueQueueItem } from "@phren/cli/data/access";
|
|
2
|
+
const MS_PER_DAY = 86_400_000;
|
|
3
|
+
function ageDays(date) {
|
|
4
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(date))
|
|
5
|
+
return null;
|
|
6
|
+
const parsed = Date.parse(`${date}T00:00:00Z`);
|
|
7
|
+
if (Number.isNaN(parsed))
|
|
8
|
+
return null;
|
|
9
|
+
return Math.floor((Date.now() - parsed) / MS_PER_DAY);
|
|
10
|
+
}
|
|
11
|
+
function toStatusItem(item) {
|
|
12
|
+
return { text: item.text, line: item.line, date: item.date, ageDays: ageDays(item.date) };
|
|
13
|
+
}
|
|
14
|
+
/** Pending review items for the project. Never throws — empty on any failure. */
|
|
15
|
+
export function getQueueStatus(ctx, topN = 3) {
|
|
16
|
+
if (!ctx.project)
|
|
17
|
+
return { pending: 0, top: [] };
|
|
18
|
+
try {
|
|
19
|
+
const result = readReviewQueue(ctx.phrenPath, ctx.project);
|
|
20
|
+
if (!result.ok || !result.data)
|
|
21
|
+
return { pending: 0, top: [] };
|
|
22
|
+
const review = result.data.filter((item) => item.section === "Review");
|
|
23
|
+
return { pending: review.length, top: review.slice(0, topN).map(toStatusItem) };
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return { pending: 0, top: [] };
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/** All pending review items (for /review). Never throws. */
|
|
30
|
+
export function listQueueItems(ctx) {
|
|
31
|
+
if (!ctx.project)
|
|
32
|
+
return [];
|
|
33
|
+
try {
|
|
34
|
+
const result = readReviewQueue(ctx.phrenPath, ctx.project);
|
|
35
|
+
if (!result.ok || !result.data)
|
|
36
|
+
return [];
|
|
37
|
+
return result.data.filter((item) => item.section === "Review").map(toStatusItem);
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
return [];
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
export const DEFAULT_EXPIRE_DAYS = 14;
|
|
44
|
+
/** Resolve the expiry window: PHREN_AGENT_QUEUE_EXPIRE_DAYS, 0 = never. */
|
|
45
|
+
export function resolveExpireDays() {
|
|
46
|
+
const env = Number.parseInt(process.env.PHREN_AGENT_QUEUE_EXPIRE_DAYS ?? "", 10);
|
|
47
|
+
if (Number.isFinite(env) && env >= 0)
|
|
48
|
+
return env;
|
|
49
|
+
return DEFAULT_EXPIRE_DAYS;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Drop review lines older than expireDays. Undated items never expire.
|
|
53
|
+
*
|
|
54
|
+
* Expiry *dequeues only*. It deliberately does not use `rejectQueueItem`: reject
|
|
55
|
+
* destroys the content wherever it lives, and governance queues findings that are
|
|
56
|
+
* already live in FINDINGS.md ("is this still true?"). Auto-rejecting those on a
|
|
57
|
+
* timer would silently delete knowledge nobody chose to delete — the queue line
|
|
58
|
+
* timing out means "stop asking", not "this was wrong".
|
|
59
|
+
*
|
|
60
|
+
* Re-reads the queue so every dropped line round-trips exactly. Never throws.
|
|
61
|
+
*/
|
|
62
|
+
export function expireStaleItems(ctx, expireDays) {
|
|
63
|
+
if (!ctx.project || expireDays <= 0)
|
|
64
|
+
return { expired: 0, texts: [] };
|
|
65
|
+
const texts = [];
|
|
66
|
+
try {
|
|
67
|
+
for (const item of listQueueItems(ctx)) {
|
|
68
|
+
if (item.ageDays === null || item.ageDays <= expireDays)
|
|
69
|
+
continue;
|
|
70
|
+
const result = dequeueQueueItem(ctx.phrenPath, ctx.project, item.line);
|
|
71
|
+
if (result.ok)
|
|
72
|
+
texts.push(item.text);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
// best effort — whatever expired, expired
|
|
77
|
+
}
|
|
78
|
+
return { expired: texts.length, texts };
|
|
79
|
+
}
|
|
80
|
+
/** Notice for expired items — names what was dropped rather than a bare count. */
|
|
81
|
+
export function formatExpiryNotice(result) {
|
|
82
|
+
if (result.expired === 0)
|
|
83
|
+
return null;
|
|
84
|
+
const shown = result.texts.slice(0, 3).map((text) => (text.length > 60 ? `${text.slice(0, 60)}…` : text));
|
|
85
|
+
const more = result.expired - shown.length;
|
|
86
|
+
const list = shown.map((text) => `"${text}"`).join(", ");
|
|
87
|
+
const suffix = more > 0 ? `, +${more} more` : "";
|
|
88
|
+
return `Review queue: removed ${result.expired} stale item${result.expired === 1 ? "" : "s"} — ${list}${suffix} (unreviewed; existing findings untouched)`;
|
|
89
|
+
}
|
|
90
|
+
/** One-line session-start banner; null when the queue is empty. */
|
|
91
|
+
export function formatQueueBanner(status) {
|
|
92
|
+
if (status.pending === 0)
|
|
93
|
+
return null;
|
|
94
|
+
const top = status.top
|
|
95
|
+
.map((item) => `"${item.text.length > 60 ? `${item.text.slice(0, 60)}…` : item.text}"`)
|
|
96
|
+
.join(", ");
|
|
97
|
+
return `Review queue: ${status.pending} pending${top ? ` — ${top}` : ""} — /review to triage`;
|
|
98
|
+
}
|
|
99
|
+
/** Warm-start section: the model may know candidates exist, clearly unverified. */
|
|
100
|
+
export function formatQueueContextSection(status) {
|
|
101
|
+
if (status.pending === 0)
|
|
102
|
+
return null;
|
|
103
|
+
const lines = status.top.map((item) => `- [unverified] ${item.text}`);
|
|
104
|
+
return `## Review queue (${status.pending} pending — candidate knowledge nobody approved; do NOT treat as truth)\n\n${lines.join("\n")}`;
|
|
105
|
+
}
|
|
106
|
+
const TRIAGE_PROMPT_HEADER = `You are triaging a knowledge review queue for a software project. Each item is a candidate finding an agent extracted but was not confident enough to save directly. For each item decide:
|
|
107
|
+
- approve: durable, plausible, useful project knowledge
|
|
108
|
+
- reject: vague, speculative, obsolete, duplicated, or trivially obvious
|
|
109
|
+
|
|
110
|
+
Respond with ONLY a fenced json block:
|
|
111
|
+
\`\`\`json
|
|
112
|
+
{"proposals":[{"index":1,"verdict":"approve","reason":"one short sentence"}]}
|
|
113
|
+
\`\`\`
|
|
114
|
+
|
|
115
|
+
Items:`;
|
|
116
|
+
/**
|
|
117
|
+
* One out-of-band LLM call proposing a verdict per item. Empty on any failure
|
|
118
|
+
* (parse errors included) — the manual /review go path always still works.
|
|
119
|
+
*/
|
|
120
|
+
export async function proposeTriage(provider, items) {
|
|
121
|
+
if (items.length === 0)
|
|
122
|
+
return [];
|
|
123
|
+
try {
|
|
124
|
+
const numbered = items.map((item, i) => `${i + 1}. ${item.text}`).join("\n");
|
|
125
|
+
const messages = [
|
|
126
|
+
{ role: "user", content: `${TRIAGE_PROMPT_HEADER}\n${numbered}` },
|
|
127
|
+
];
|
|
128
|
+
const response = await provider.chat("You are a precise knowledge-base curator.", messages, []);
|
|
129
|
+
const text = response.content
|
|
130
|
+
.filter((block) => block.type === "text")
|
|
131
|
+
.map((block) => block.text)
|
|
132
|
+
.join("\n");
|
|
133
|
+
const fenced = text.match(/```(?:json)?\s*\n([\s\S]*?)```/);
|
|
134
|
+
const raw = fenced ? fenced[1] : text.match(/\{[\s\S]*"proposals"[\s\S]*\}/)?.[0];
|
|
135
|
+
if (!raw)
|
|
136
|
+
return [];
|
|
137
|
+
const parsed = JSON.parse(raw);
|
|
138
|
+
const proposals = parsed.proposals;
|
|
139
|
+
if (!Array.isArray(proposals))
|
|
140
|
+
return [];
|
|
141
|
+
const valid = [];
|
|
142
|
+
for (const p of proposals) {
|
|
143
|
+
if (typeof p !== "object" || p === null)
|
|
144
|
+
continue;
|
|
145
|
+
const index = p.index;
|
|
146
|
+
const verdict = p.verdict;
|
|
147
|
+
const reason = p.reason;
|
|
148
|
+
if (typeof index !== "number" || index < 1 || index > items.length)
|
|
149
|
+
continue;
|
|
150
|
+
if (verdict !== "approve" && verdict !== "reject")
|
|
151
|
+
continue;
|
|
152
|
+
const item = items[index - 1];
|
|
153
|
+
valid.push({
|
|
154
|
+
index,
|
|
155
|
+
text: item.text,
|
|
156
|
+
line: item.line,
|
|
157
|
+
verdict,
|
|
158
|
+
reason: typeof reason === "string" ? reason : "",
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
return valid;
|
|
162
|
+
}
|
|
163
|
+
catch {
|
|
164
|
+
return [];
|
|
165
|
+
}
|
|
166
|
+
}
|