@phren/cli 0.1.33 → 0.1.35
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/dist/cli/config-proactivity.js +12 -6
- package/dist/cli/config-synonyms.js +7 -4
- package/dist/cli/hooks.js +7 -3
- package/dist/cli/session-background.js +5 -6
- package/dist/cli/session-tool-hook.js +2 -0
- package/dist/cli/team.js +26 -13
- package/dist/cli-registry.js +11 -0
- package/dist/content/dedup.js +25 -3
- package/dist/content/learning.js +10 -16
- package/dist/finding/impact.js +4 -0
- package/dist/governance/scores.js +26 -45
- package/dist/index.js +67 -32
- package/dist/init/config.js +2 -2
- package/dist/link/skills.js +1 -1
- package/dist/logger.js +19 -0
- package/dist/phren-paths.d.ts +6 -0
- package/dist/phren-paths.js +17 -0
- package/dist/shared/index.d.ts +16 -0
- package/dist/shared/index.js +163 -17
- package/dist/shared/retrieval.js +25 -6
- package/dist/telemetry.js +4 -1
- package/dist/tools/finding.d.ts +1 -0
- package/dist/tools/finding.js +40 -2
- package/package.json +3 -3
|
@@ -41,7 +41,8 @@ export function handleConfigProactivity(subcommand, args) {
|
|
|
41
41
|
if (projectArg) {
|
|
42
42
|
if (!isValidProjectName(projectArg)) {
|
|
43
43
|
console.error(`Invalid project name: "${projectArg}"`);
|
|
44
|
-
process.
|
|
44
|
+
process.exitCode = 1;
|
|
45
|
+
return;
|
|
45
46
|
}
|
|
46
47
|
const resolved = mergeConfig(phrenPath, projectArg);
|
|
47
48
|
console.log(JSON.stringify({
|
|
@@ -57,17 +58,20 @@ export function handleConfigProactivity(subcommand, args) {
|
|
|
57
58
|
}
|
|
58
59
|
if (filteredArgs.length !== 1) {
|
|
59
60
|
printProactivityUsage(subcommand);
|
|
60
|
-
process.
|
|
61
|
+
process.exitCode = 1;
|
|
62
|
+
return;
|
|
61
63
|
}
|
|
62
64
|
const level = normalizeProactivityLevel(value);
|
|
63
65
|
if (!level) {
|
|
64
66
|
printProactivityUsage(subcommand);
|
|
65
|
-
process.
|
|
67
|
+
process.exitCode = 1;
|
|
68
|
+
return;
|
|
66
69
|
}
|
|
67
70
|
if (projectArg) {
|
|
68
71
|
if (!isValidProjectName(projectArg)) {
|
|
69
72
|
console.error(`Invalid project name: "${projectArg}"`);
|
|
70
|
-
process.
|
|
73
|
+
process.exitCode = 1;
|
|
74
|
+
return;
|
|
71
75
|
}
|
|
72
76
|
warnIfUnregistered(phrenPath, projectArg);
|
|
73
77
|
const key = subcommand === "proactivity" ? "proactivity"
|
|
@@ -117,12 +121,14 @@ export function handleConfigProjectOwnership(args) {
|
|
|
117
121
|
}
|
|
118
122
|
if (args.length !== 1) {
|
|
119
123
|
console.error(`Usage: phren config project-ownership [${PROJECT_OWNERSHIP_MODES.join("|")}]`);
|
|
120
|
-
process.
|
|
124
|
+
process.exitCode = 1;
|
|
125
|
+
return;
|
|
121
126
|
}
|
|
122
127
|
const ownership = parseProjectOwnershipMode(value);
|
|
123
128
|
if (!ownership) {
|
|
124
129
|
console.error(`Usage: phren config project-ownership [${PROJECT_OWNERSHIP_MODES.join("|")}]`);
|
|
125
|
-
process.
|
|
130
|
+
process.exitCode = 1;
|
|
131
|
+
return;
|
|
126
132
|
}
|
|
127
133
|
writeInstallPreferences(phrenPath, { projectOwnershipDefault: ownership });
|
|
128
134
|
console.log(JSON.stringify(projectOwnershipConfigSnapshot(phrenPath), null, 2));
|
|
@@ -24,7 +24,8 @@ export function handleConfigSynonyms(args) {
|
|
|
24
24
|
}
|
|
25
25
|
if (!project || !isValidProjectName(project)) {
|
|
26
26
|
printSynonymsUsage();
|
|
27
|
-
process.
|
|
27
|
+
process.exitCode = 1;
|
|
28
|
+
return;
|
|
28
29
|
}
|
|
29
30
|
if (action === "list") {
|
|
30
31
|
console.log(JSON.stringify({
|
|
@@ -39,7 +40,8 @@ export function handleConfigSynonyms(args) {
|
|
|
39
40
|
const synonyms = parseSynonymItems(args[3]);
|
|
40
41
|
if (!term || synonyms.length === 0) {
|
|
41
42
|
printSynonymsUsage();
|
|
42
|
-
process.
|
|
43
|
+
process.exitCode = 1;
|
|
44
|
+
return;
|
|
43
45
|
}
|
|
44
46
|
const updated = learnSynonym(phrenPath, project, term, synonyms);
|
|
45
47
|
console.log(JSON.stringify({ project, term, synonyms: updated[term.toLowerCase()] ?? [], updated }, null, 2));
|
|
@@ -49,12 +51,13 @@ export function handleConfigSynonyms(args) {
|
|
|
49
51
|
const term = args[2];
|
|
50
52
|
if (!term) {
|
|
51
53
|
printSynonymsUsage();
|
|
52
|
-
process.
|
|
54
|
+
process.exitCode = 1;
|
|
55
|
+
return;
|
|
53
56
|
}
|
|
54
57
|
const updated = removeLearnedSynonym(phrenPath, project, term, parseSynonymItems(args[3]));
|
|
55
58
|
console.log(JSON.stringify({ project, term: term.toLowerCase(), updated }, null, 2));
|
|
56
59
|
return;
|
|
57
60
|
}
|
|
58
61
|
printSynonymsUsage();
|
|
59
|
-
process.
|
|
62
|
+
process.exitCode = 1;
|
|
60
63
|
}
|
package/dist/cli/hooks.js
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
// cli-hooks-globs.ts — project glob matching
|
|
7
7
|
import { debugLog, sessionMarker, sessionsDir, getPhrenPath, } from "../shared.js";
|
|
8
8
|
import { mergeConfig, } from "../shared/governance.js";
|
|
9
|
-
import {
|
|
9
|
+
import { loadIndexForHook, detectProject, } from "../shared/index.js";
|
|
10
10
|
import { isProjectHookEnabled } from "../project-config.js";
|
|
11
11
|
import { checkConsolidationNeeded, } from "../shared/content.js";
|
|
12
12
|
import { buildRobustFtsQuery, extractKeywordEntries, isFeatureEnabled, clampInt, errorMessage, } from "../utils.js";
|
|
@@ -118,9 +118,10 @@ export async function handleHookPrompt() {
|
|
|
118
118
|
.map(([topic]) => topic);
|
|
119
119
|
}
|
|
120
120
|
const tIndex0 = Date.now();
|
|
121
|
-
|
|
121
|
+
// Never block the prompt on a rebuild: serve the current/stale snapshot and
|
|
122
|
+
// refresh in a detached process (see loadIndexForHook).
|
|
123
|
+
const db = await loadIndexForHook(getPhrenPath(), profile);
|
|
122
124
|
stage.indexMs = Date.now() - tIndex0;
|
|
123
|
-
const gitCtx = getGitContext(cwd);
|
|
124
125
|
const intent = detectTaskIntent(prompt);
|
|
125
126
|
const detectedProject = cwd ? detectProject(getPhrenPath(), cwd, profile) : null;
|
|
126
127
|
if (detectedProject)
|
|
@@ -129,6 +130,9 @@ export async function handleHookPrompt() {
|
|
|
129
130
|
appendAuditLog(getPhrenPath(), "hook_prompt", `status=project_disabled project=${detectedProject}`);
|
|
130
131
|
process.exit(0);
|
|
131
132
|
}
|
|
133
|
+
// Resolve git context AFTER the enabled check — it spawns 3 git processes and is
|
|
134
|
+
// wasted work when the project has hooks disabled.
|
|
135
|
+
const gitCtx = getGitContext(cwd);
|
|
132
136
|
const resolvedConfig = mergeConfig(getPhrenPath(), detectedProject ?? undefined);
|
|
133
137
|
const safeQuery = buildRobustFtsQuery(keywords, detectedProject, getPhrenPath());
|
|
134
138
|
if (!safeQuery)
|
|
@@ -107,9 +107,10 @@ export function scheduleBackgroundMaintenance(phrenPathLocal, project) {
|
|
|
107
107
|
}
|
|
108
108
|
if (project)
|
|
109
109
|
spawnArgs.push(project);
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
110
|
+
// Keep this log under .runtime/ (gitignored), matching background-sync.log.
|
|
111
|
+
// Writing it under .config/ makes it a tracked file that diverges per machine
|
|
112
|
+
// and breaks the Stop-hook pull-rebase.
|
|
113
|
+
const logPath = runtimeFile(phrenPathLocal, "background-maintenance.log");
|
|
113
114
|
const logFd = fs.openSync(logPath, "a");
|
|
114
115
|
fs.writeSync(logFd, `[${new Date().toISOString()}] spawn ${process.execPath} ${spawnArgs.join(" ")}\n`);
|
|
115
116
|
const child = spawnDetachedChild(spawnArgs, { phrenPath: phrenPathLocal, logFd });
|
|
@@ -158,9 +159,7 @@ export function scheduleBackgroundMaintenance(phrenPathLocal, project) {
|
|
|
158
159
|
catch (err) {
|
|
159
160
|
const errMsg = errorMessage(err);
|
|
160
161
|
try {
|
|
161
|
-
|
|
162
|
-
fs.mkdirSync(logDir, { recursive: true });
|
|
163
|
-
fs.appendFileSync(path.join(logDir, "background-maintenance.log"), `[${new Date().toISOString()}] spawn failed: ${errMsg}\n`);
|
|
162
|
+
fs.appendFileSync(runtimeFile(phrenPathLocal, "background-maintenance.log"), `[${new Date().toISOString()}] spawn failed: ${errMsg}\n`);
|
|
164
163
|
}
|
|
165
164
|
catch (err) {
|
|
166
165
|
logger.debug("hooks-session", `backgroundMaintenance logSpawnFailure: ${errorMessage(err)}`);
|
|
@@ -6,6 +6,7 @@ import * as fs from "fs";
|
|
|
6
6
|
import * as path from "path";
|
|
7
7
|
import { buildHookContext, debugLog, appendAuditLog, runtimeFile, sessionMarker, getPhrenPath, getWorkflowPolicy, appendReviewQueue, getProactivityLevelForFindings, FINDING_SENSITIVITY_CONFIG, isProjectHookEnabled, errorMessage, detectProject, } from "./hooks-context.js";
|
|
8
8
|
import { logger } from "../logger.js";
|
|
9
|
+
import { rotateJsonlIfLarge } from "../phren-paths.js";
|
|
9
10
|
import { buildIndex, queryRows, } from "../shared/index.js";
|
|
10
11
|
import { filterTaskByPriority } from "../shared/retrieval.js";
|
|
11
12
|
// ── PostToolUse hook ─────────────────────────────────────────────────────────
|
|
@@ -122,6 +123,7 @@ export async function handleHookTool() {
|
|
|
122
123
|
try {
|
|
123
124
|
const logFile = runtimeFile(ctx.phrenPath, "tool-log.jsonl");
|
|
124
125
|
fs.mkdirSync(path.dirname(logFile), { recursive: true });
|
|
126
|
+
rotateJsonlIfLarge(logFile);
|
|
125
127
|
fs.appendFileSync(logFile, JSON.stringify(entry) + "\n");
|
|
126
128
|
}
|
|
127
129
|
catch (err) {
|
package/dist/cli/team.js
CHANGED
|
@@ -28,23 +28,27 @@ async function handleTeamInit(args) {
|
|
|
28
28
|
const description = getOptionValue(args, "--description");
|
|
29
29
|
if (!name) {
|
|
30
30
|
console.error("Usage: phren team init <name> [--remote <url>] [--description <text>]");
|
|
31
|
-
process.
|
|
31
|
+
process.exitCode = 1;
|
|
32
|
+
return;
|
|
32
33
|
}
|
|
33
34
|
if (!isValidProjectName(name)) {
|
|
34
35
|
console.error(`Invalid store name: "${name}". Use lowercase letters, numbers, hyphens.`);
|
|
35
|
-
process.
|
|
36
|
+
process.exitCode = 1;
|
|
37
|
+
return;
|
|
36
38
|
}
|
|
37
39
|
// Check if store already exists
|
|
38
40
|
const existing = findStoreByName(phrenPath, name);
|
|
39
41
|
if (existing) {
|
|
40
42
|
console.error(`Store "${name}" already exists at ${existing.path}`);
|
|
41
|
-
process.
|
|
43
|
+
process.exitCode = 1;
|
|
44
|
+
return;
|
|
42
45
|
}
|
|
43
46
|
const storesDir = path.join(path.dirname(phrenPath), ".phren-stores");
|
|
44
47
|
const storePath = path.join(storesDir, name);
|
|
45
48
|
if (fs.existsSync(storePath)) {
|
|
46
49
|
console.error(`Directory already exists: ${storePath}`);
|
|
47
|
-
process.
|
|
50
|
+
process.exitCode = 1;
|
|
51
|
+
return;
|
|
48
52
|
}
|
|
49
53
|
// Create the team store directory
|
|
50
54
|
fs.mkdirSync(storePath, { recursive: true });
|
|
@@ -135,24 +139,28 @@ async function handleTeamJoin(args) {
|
|
|
135
139
|
const nameOverride = getOptionValue(args, "--name");
|
|
136
140
|
if (!remote) {
|
|
137
141
|
console.error("Usage: phren team join <git-url> [--name <name>]");
|
|
138
|
-
process.
|
|
142
|
+
process.exitCode = 1;
|
|
143
|
+
return;
|
|
139
144
|
}
|
|
140
145
|
const storesDir = path.join(path.dirname(phrenPath), ".phren-stores");
|
|
141
146
|
// Infer name from URL if not provided
|
|
142
147
|
const inferredName = nameOverride || path.basename(remote, ".git").toLowerCase().replace(/[^a-z0-9_-]/g, "-");
|
|
143
148
|
if (!isValidProjectName(inferredName)) {
|
|
144
149
|
console.error(`Invalid store name: "${inferredName}". Use --name to specify a valid name.`);
|
|
145
|
-
process.
|
|
150
|
+
process.exitCode = 1;
|
|
151
|
+
return;
|
|
146
152
|
}
|
|
147
153
|
const existing = findStoreByName(phrenPath, inferredName);
|
|
148
154
|
if (existing) {
|
|
149
155
|
console.error(`Store "${inferredName}" already exists at ${existing.path}`);
|
|
150
|
-
process.
|
|
156
|
+
process.exitCode = 1;
|
|
157
|
+
return;
|
|
151
158
|
}
|
|
152
159
|
const storePath = path.join(storesDir, inferredName);
|
|
153
160
|
if (fs.existsSync(storePath)) {
|
|
154
161
|
console.error(`Directory already exists: ${storePath}`);
|
|
155
|
-
process.
|
|
162
|
+
process.exitCode = 1;
|
|
163
|
+
return;
|
|
156
164
|
}
|
|
157
165
|
// Clone the remote
|
|
158
166
|
console.log(`Cloning ${remote}...`);
|
|
@@ -190,20 +198,24 @@ async function handleTeamAddProject(args) {
|
|
|
190
198
|
const projectName = positional[1];
|
|
191
199
|
if (!storeName || !projectName) {
|
|
192
200
|
console.error("Usage: phren team add-project <store-name> <project-name>");
|
|
193
|
-
process.
|
|
201
|
+
process.exitCode = 1;
|
|
202
|
+
return;
|
|
194
203
|
}
|
|
195
204
|
if (!isValidProjectName(projectName)) {
|
|
196
205
|
console.error(`Invalid project name: "${projectName}"`);
|
|
197
|
-
process.
|
|
206
|
+
process.exitCode = 1;
|
|
207
|
+
return;
|
|
198
208
|
}
|
|
199
209
|
const store = findStoreByName(phrenPath, storeName);
|
|
200
210
|
if (!store) {
|
|
201
211
|
console.error(`Store "${storeName}" not found. Run 'phren store list' to see available stores.`);
|
|
202
|
-
process.
|
|
212
|
+
process.exitCode = 1;
|
|
213
|
+
return;
|
|
203
214
|
}
|
|
204
215
|
if (store.role === "readonly") {
|
|
205
216
|
console.error(`Store "${storeName}" is read-only. Cannot add projects.`);
|
|
206
|
-
process.
|
|
217
|
+
process.exitCode = 1;
|
|
218
|
+
return;
|
|
207
219
|
}
|
|
208
220
|
// Create project directory in the store
|
|
209
221
|
const projectDir = path.join(store.path, projectName);
|
|
@@ -287,7 +299,8 @@ export async function handleTeamNamespace(args) {
|
|
|
287
299
|
`);
|
|
288
300
|
if (subcommand) {
|
|
289
301
|
console.error(`Unknown subcommand: ${subcommand}`);
|
|
290
|
-
process.
|
|
302
|
+
process.exitCode = 1;
|
|
303
|
+
return;
|
|
291
304
|
}
|
|
292
305
|
}
|
|
293
306
|
}
|
package/dist/cli-registry.js
CHANGED
|
@@ -573,6 +573,17 @@ export const REGISTRY = [
|
|
|
573
573
|
await handleBackgroundMaintenance(args[0]);
|
|
574
574
|
},
|
|
575
575
|
},
|
|
576
|
+
{
|
|
577
|
+
name: "background-reindex",
|
|
578
|
+
topic: "core",
|
|
579
|
+
usage: "phren background-reindex",
|
|
580
|
+
summary: "Internal: rebuild the FTS index off the hook path",
|
|
581
|
+
hidden: true,
|
|
582
|
+
run: async (_args, ctx) => {
|
|
583
|
+
const { buildIndex } = await import("./shared/index.js");
|
|
584
|
+
await buildIndex(ctx.phrenPath(), ctx.profile());
|
|
585
|
+
},
|
|
586
|
+
},
|
|
576
587
|
{
|
|
577
588
|
name: "debug-injection",
|
|
578
589
|
topic: "core",
|
package/dist/content/dedup.js
CHANGED
|
@@ -284,6 +284,24 @@ function learningPolarity(text) {
|
|
|
284
284
|
return "negative";
|
|
285
285
|
return "neutral";
|
|
286
286
|
}
|
|
287
|
+
// Minimum topical overlap (Jaccard over substantive tokens, with observation tags
|
|
288
|
+
// and metadata stripped) required before two findings that share an entity and have
|
|
289
|
+
// opposing polarity are treated as a contradiction. The bare "one shared entity +
|
|
290
|
+
// opposite polarity" rule fires on unrelated findings that merely mention the same
|
|
291
|
+
// tool or word (e.g. a git-workflow decision and a security decision that both say
|
|
292
|
+
// "GitHub"); requiring genuine subject-matter overlap removes that false-positive
|
|
293
|
+
// class while keeping real same-topic contradictions.
|
|
294
|
+
const CONFLICT_MIN_TOPIC_OVERLAP = 0.12;
|
|
295
|
+
/** Strip observation tags like [decision] so a shared tag is not counted as shared topic. */
|
|
296
|
+
function stripObservationTags(text) {
|
|
297
|
+
return text.replace(/\[[a-zA-Z_-]+\]/g, " ");
|
|
298
|
+
}
|
|
299
|
+
/** Jaccard overlap of the substantive tokens of two findings (tags + metadata removed). */
|
|
300
|
+
function topicalOverlap(a, b) {
|
|
301
|
+
const ta = jaccardTokenize(stripObservationTags(stripMetadata(a)));
|
|
302
|
+
const tb = jaccardTokenize(stripObservationTags(stripMetadata(b)));
|
|
303
|
+
return jaccardSimilarity(ta, tb);
|
|
304
|
+
}
|
|
287
305
|
/** Returns existing learning lines that appear to conflict with newFinding. */
|
|
288
306
|
export function detectConflicts(newFinding, existingLines, dynamicEntities) {
|
|
289
307
|
const newEntities = extractProseEntities(newFinding, dynamicEntities);
|
|
@@ -301,9 +319,13 @@ export function detectConflicts(newFinding, existingLines, dynamicEntities) {
|
|
|
301
319
|
if (shared.length === 0)
|
|
302
320
|
continue;
|
|
303
321
|
const linePol = learningPolarity(line);
|
|
304
|
-
if (linePol
|
|
305
|
-
|
|
306
|
-
|
|
322
|
+
if (linePol === "neutral" || linePol === newPol)
|
|
323
|
+
continue;
|
|
324
|
+
// Require genuine topical overlap, not just one incidental shared entity, before
|
|
325
|
+
// flagging. Unrelated findings that happen to share a tool name fall below this bar.
|
|
326
|
+
if (topicalOverlap(newFinding, line) < CONFLICT_MIN_TOPIC_OVERLAP)
|
|
327
|
+
continue;
|
|
328
|
+
conflicts.push(line);
|
|
307
329
|
}
|
|
308
330
|
return conflicts;
|
|
309
331
|
}
|
package/dist/content/learning.js
CHANGED
|
@@ -6,7 +6,7 @@ import { normalizeMemoryScope } from "../shared.js";
|
|
|
6
6
|
import { withFileLock } from "../shared/governance.js";
|
|
7
7
|
import { isValidProjectName, safeProjectPath } from "../utils.js";
|
|
8
8
|
import { buildCitationComment, buildScopeComment, buildSourceComment, getHeadCommit, getRepoRoot, inferCitationLocation, } from "./citation.js";
|
|
9
|
-
import { isDuplicateFinding, scanForSecrets, normalizeObservationTags, resolveCoref
|
|
9
|
+
import { isDuplicateFinding, scanForSecrets, normalizeObservationTags, resolveCoref } from "./dedup.js";
|
|
10
10
|
import { validateFindingsFormat, validateFinding } from "./validate.js";
|
|
11
11
|
import { countActiveFindings, autoArchiveToReference } from "./archive.js";
|
|
12
12
|
import { resolveAutoFindingTaskItem, resolveFindingTaskReference, } from "../finding/context.js";
|
|
@@ -81,7 +81,7 @@ export function autoDetectFindingType(text) {
|
|
|
81
81
|
return null;
|
|
82
82
|
}
|
|
83
83
|
function prepareFinding(opts) {
|
|
84
|
-
const { finding: learning, project, fullHistory, extraAnnotations, citationInput, scope, provenance, nowIso, inferredRepo, headCommit
|
|
84
|
+
const { finding: learning, project, fullHistory, extraAnnotations, citationInput, scope, provenance, nowIso, inferredRepo, headCommit } = opts;
|
|
85
85
|
const secretType = scanForSecrets(learning);
|
|
86
86
|
if (secretType) {
|
|
87
87
|
return { status: "rejected", reason: `Contains ${secretType}` };
|
|
@@ -113,20 +113,14 @@ function prepareFinding(opts) {
|
|
|
113
113
|
if (isDuplicateFinding(fullHistory, bullet)) {
|
|
114
114
|
return { status: "duplicate" };
|
|
115
115
|
}
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
status_reason: "conflicts_with",
|
|
125
|
-
status_ref: snippet,
|
|
126
|
-
};
|
|
127
|
-
bullet += ` <!-- conflicts_with: "${snippet}" --> <!-- phren:contradicts "${snippet}" -->`;
|
|
128
|
-
debugLog(`add_finding: conflict detected for "${project}": ${snippet}`);
|
|
129
|
-
}
|
|
116
|
+
// NOTE: heuristic contradiction detection is intentionally NOT done here. The lexical
|
|
117
|
+
// heuristic (shared entity + opposing polarity) produces false positives, so it must
|
|
118
|
+
// never silently mutate the stored finding's status. Instead the MCP add_finding tool
|
|
119
|
+
// surfaces heuristic conflict *candidates* (via findConflictCandidates) in its response
|
|
120
|
+
// so the calling agent — an LLM already in the loop with full context — can judge them,
|
|
121
|
+
// exactly as it already does for potential duplicates. A hard "contradicted" status is
|
|
122
|
+
// reserved for the LLM-confirmed path (checkSemanticConflicts) and explicit user
|
|
123
|
+
// resolution via resolve_contradiction.
|
|
130
124
|
if (extraAnnotations && extraAnnotations.length > 0) {
|
|
131
125
|
const lifecycleFromExtra = parseFindingLifecycle(`- lifecycle ${extraAnnotations.join(" ")}`);
|
|
132
126
|
if (lifecycleFromExtra.status !== "active" ||
|
package/dist/finding/impact.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import * as crypto from "crypto";
|
|
2
2
|
import * as fs from "fs";
|
|
3
3
|
import { impactLogFile } from "../shared.js";
|
|
4
|
+
import { rotateJsonlIfLarge } from "../phren-paths.js";
|
|
4
5
|
import { withFileLock } from "../shared/governance.js";
|
|
5
6
|
import { normalizeFindingText } from "../content/metadata.js";
|
|
6
7
|
let highImpactCache = null;
|
|
@@ -86,6 +87,9 @@ function appendImpact(phrenPath, entries) {
|
|
|
86
87
|
return;
|
|
87
88
|
const file = impactLogFile(phrenPath);
|
|
88
89
|
withFileLock(file, () => {
|
|
90
|
+
// getHighImpactFindings re-parses this whole file on the hook hot path, so cap
|
|
91
|
+
// it — otherwise it grows unbounded (seen at 2MB) and every prompt re-parses it.
|
|
92
|
+
rotateJsonlIfLarge(file);
|
|
89
93
|
const lines = entries.map((entry) => JSON.stringify(entry));
|
|
90
94
|
fs.appendFileSync(file, lines.join("\n") + "\n");
|
|
91
95
|
});
|
|
@@ -34,24 +34,14 @@ function entriesObject(data) {
|
|
|
34
34
|
return data.entries;
|
|
35
35
|
return data;
|
|
36
36
|
}
|
|
37
|
-
function
|
|
38
|
-
|
|
39
|
-
if (!fs.existsSync(filePath))
|
|
40
|
-
return true;
|
|
41
|
-
const raw = fs.readFileSync(filePath, "utf8");
|
|
42
|
-
const data = JSON.parse(raw);
|
|
43
|
-
if (!isRecord(data))
|
|
44
|
-
return false;
|
|
45
|
-
if (isVersionedEntries(data) && !hasValidSchemaVersion(data))
|
|
46
|
-
return false;
|
|
47
|
-
if (isVersionedEntries(data) && !isRecord(data.entries))
|
|
48
|
-
return false;
|
|
49
|
-
return Object.values(entriesObject(data)).every((entry) => isEntryScore(entry));
|
|
50
|
-
}
|
|
51
|
-
catch (err) {
|
|
52
|
-
debugLog(`validateScoresJson failed for ${filePath}: ${errorMessage(err)}`);
|
|
37
|
+
function validateScoresData(data) {
|
|
38
|
+
if (!isRecord(data))
|
|
53
39
|
return false;
|
|
54
|
-
|
|
40
|
+
if (isVersionedEntries(data) && !hasValidSchemaVersion(data))
|
|
41
|
+
return false;
|
|
42
|
+
if (isVersionedEntries(data) && !isRecord(data.entries))
|
|
43
|
+
return false;
|
|
44
|
+
return Object.values(entriesObject(data)).every((entry) => isEntryScore(entry));
|
|
55
45
|
}
|
|
56
46
|
function normalizeVersionedEntries(data, guard) {
|
|
57
47
|
const out = {};
|
|
@@ -69,11 +59,11 @@ function readScoresFile(phrenPath) {
|
|
|
69
59
|
try {
|
|
70
60
|
if (!fs.existsSync(file))
|
|
71
61
|
return { ...DEFAULT_MEMORY_SCORES_FILE.entries };
|
|
72
|
-
|
|
62
|
+
const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
63
|
+
if (!validateScoresData(parsed)) {
|
|
73
64
|
debugLog(`readScoresFile: ${file} failed validation, using defaults`);
|
|
74
65
|
return { ...DEFAULT_MEMORY_SCORES_FILE.entries };
|
|
75
66
|
}
|
|
76
|
-
const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
77
67
|
return normalizeVersionedEntries(parsed, isEntryScore).entries;
|
|
78
68
|
}
|
|
79
69
|
catch (err) {
|
|
@@ -103,24 +93,27 @@ function appendScoreJournal(phrenPath, key, delta) {
|
|
|
103
93
|
fs.appendFileSync(file, JSON.stringify(entry) + "\n");
|
|
104
94
|
});
|
|
105
95
|
}
|
|
96
|
+
function parseScoreJournal(raw, context) {
|
|
97
|
+
return raw
|
|
98
|
+
.split("\n")
|
|
99
|
+
.filter(Boolean)
|
|
100
|
+
.map((line) => {
|
|
101
|
+
try {
|
|
102
|
+
return JSON.parse(line);
|
|
103
|
+
}
|
|
104
|
+
catch (err) {
|
|
105
|
+
logger.debug("scores", `${context} parseLine: ${errorMessage(err)}`);
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
})
|
|
109
|
+
.filter((entry) => entry !== null && typeof entry.key === "string" && typeof entry.delta === "object" && entry.delta !== null);
|
|
110
|
+
}
|
|
106
111
|
function readScoreJournal(phrenPath) {
|
|
107
112
|
const file = scoresJournalFile(phrenPath);
|
|
108
113
|
if (!fs.existsSync(file))
|
|
109
114
|
return [];
|
|
110
115
|
try {
|
|
111
|
-
return fs.readFileSync(file, "utf8")
|
|
112
|
-
.split("\n")
|
|
113
|
-
.filter(Boolean)
|
|
114
|
-
.map((line) => {
|
|
115
|
-
try {
|
|
116
|
-
return JSON.parse(line);
|
|
117
|
-
}
|
|
118
|
-
catch (err) {
|
|
119
|
-
logger.debug("scores", `readScoreJournal parseLine: ${errorMessage(err)}`);
|
|
120
|
-
return null;
|
|
121
|
-
}
|
|
122
|
-
})
|
|
123
|
-
.filter((entry) => entry !== null && typeof entry.key === "string" && typeof entry.delta === "object" && entry.delta !== null);
|
|
116
|
+
return parseScoreJournal(fs.readFileSync(file, "utf8"), "readScoreJournal");
|
|
124
117
|
}
|
|
125
118
|
catch (err) {
|
|
126
119
|
debugLog(`readScoreJournal failed: ${errorMessage(err)}`);
|
|
@@ -140,19 +133,7 @@ function claimScoreJournal(phrenPath) {
|
|
|
140
133
|
if (!claimedFile)
|
|
141
134
|
return [];
|
|
142
135
|
try {
|
|
143
|
-
return fs.readFileSync(claimedFile, "utf8")
|
|
144
|
-
.split("\n")
|
|
145
|
-
.filter(Boolean)
|
|
146
|
-
.map((line) => {
|
|
147
|
-
try {
|
|
148
|
-
return JSON.parse(line);
|
|
149
|
-
}
|
|
150
|
-
catch (err) {
|
|
151
|
-
logger.debug("scores", `claimScoreJournal parseLine: ${errorMessage(err)}`);
|
|
152
|
-
return null;
|
|
153
|
-
}
|
|
154
|
-
})
|
|
155
|
-
.filter((entry) => entry !== null && typeof entry.key === "string" && typeof entry.delta === "object" && entry.delta !== null);
|
|
136
|
+
return parseScoreJournal(fs.readFileSync(claimedFile, "utf8"), "claimScoreJournal");
|
|
156
137
|
}
|
|
157
138
|
catch (err) {
|
|
158
139
|
debugLog(`claimScoreJournal failed: ${errorMessage(err)}`);
|
package/dist/index.js
CHANGED
|
@@ -1,30 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
3
|
-
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
4
2
|
import * as fs from "fs";
|
|
5
3
|
import * as path from "path";
|
|
6
4
|
import { findPhrenPathWithArg, debugLog, runtimeDir, } from "./shared.js";
|
|
7
5
|
import { log as structuredLog, logger } from "./logger.js";
|
|
8
|
-
import { buildIndex, updateFileInIndex as updateFileInIndexFn, } from "./shared/index.js";
|
|
9
|
-
import { runCustomHooks } from "./hooks.js";
|
|
10
|
-
import { register as registerSearch } from "./tools/search.js";
|
|
11
|
-
import { register as registerTask } from "./tools/tasks.js";
|
|
12
|
-
import { register as registerFinding } from "./tools/finding.js";
|
|
13
|
-
import { register as registerMemory } from "./tools/memory.js";
|
|
14
|
-
import { register as registerData } from "./tools/data.js";
|
|
15
|
-
import { register as registerGraph } from "./tools/graph.js";
|
|
16
|
-
import { register as registerSession } from "./tools/session.js";
|
|
17
|
-
import { register as registerOps } from "./tools/ops.js";
|
|
18
|
-
import { register as registerSkills } from "./tools/skills.js";
|
|
19
|
-
import { register as registerHooks } from "./tools/hooks.js";
|
|
20
|
-
import { register as registerExtract } from "./tools/extract.js";
|
|
21
|
-
import { register as registerConfig } from "./tools/config.js";
|
|
22
|
-
import { mcpResponse } from "./tools/types.js";
|
|
23
6
|
import { errorMessage } from "./utils.js";
|
|
24
7
|
import { printIntegratedHelp, printIntegratedVersion, resolveTopLevelInvocation, runTopLevelCommand, } from "./entrypoint.js";
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
8
|
+
// NOTE: the MCP-server-only module graph (MCP SDK, FTS indexer, tool registries,
|
|
9
|
+
// startup-embedding, custom-hook engine) is intentionally NOT imported here. It is
|
|
10
|
+
// dynamically imported inside main() so that top-level commands — hook-prompt,
|
|
11
|
+
// --version, --help — which never reach main() do not pay its ~1.8s cold-start cost.
|
|
12
|
+
// This matters most for the PostToolUse `hook-tool`, which spawns per tool call.
|
|
28
13
|
const invocation = resolveTopLevelInvocation(process.argv.slice(2));
|
|
29
14
|
if (invocation.kind === "help") {
|
|
30
15
|
printIntegratedHelp();
|
|
@@ -70,10 +55,24 @@ function cleanStaleLocks(phrenPath) {
|
|
|
70
55
|
}
|
|
71
56
|
}
|
|
72
57
|
async function main() {
|
|
58
|
+
// Lazy-load the MCP-server-only module graph. Only the long-lived MCP server
|
|
59
|
+
// reaches main(), so paying the import cost here — not at module scope — keeps
|
|
60
|
+
// every hook subprocess fast (hook-prompt, hook-tool, --version never get here).
|
|
61
|
+
const [{ McpServer }, { StdioServerTransport }, { buildIndex, flushEmbeddingQueue, updateFileInIndex: updateFileInIndexFn }, { runCustomHooks }, { mcpResponse }, { startEmbeddingWarmup }, { resolveRuntimeProfile }, { VERSION: PACKAGE_VERSION },] = await Promise.all([
|
|
62
|
+
import("@modelcontextprotocol/sdk/server/mcp.js"),
|
|
63
|
+
import("@modelcontextprotocol/sdk/server/stdio.js"),
|
|
64
|
+
import("./shared/index.js"),
|
|
65
|
+
import("./hooks.js"),
|
|
66
|
+
import("./tools/types.js"),
|
|
67
|
+
import("./startup-embedding.js"),
|
|
68
|
+
import("./runtime-profile.js"),
|
|
69
|
+
import("./package-metadata.js"),
|
|
70
|
+
]);
|
|
73
71
|
const profile = resolveRuntimeProfile(phrenPath);
|
|
74
72
|
cleanStaleLocks(phrenPath);
|
|
75
73
|
let db = null;
|
|
76
74
|
let indexReady = false;
|
|
75
|
+
let shuttingDown = false;
|
|
77
76
|
try {
|
|
78
77
|
db = await buildIndex(phrenPath, profile);
|
|
79
78
|
indexReady = true;
|
|
@@ -173,8 +172,15 @@ async function main() {
|
|
|
173
172
|
"get_findings",
|
|
174
173
|
"get_tasks",
|
|
175
174
|
]);
|
|
175
|
+
const registeredToolNames = new Set();
|
|
176
176
|
server.registerTool = function (name, config, handler) {
|
|
177
177
|
const registeredName = name;
|
|
178
|
+
// Registration runs before server.connect, so throwing here fails fast at
|
|
179
|
+
// startup instead of letting a later module silently shadow an earlier tool.
|
|
180
|
+
if (registeredToolNames.has(registeredName)) {
|
|
181
|
+
throw new Error(`Duplicate MCP tool registration: "${String(registeredName)}"`);
|
|
182
|
+
}
|
|
183
|
+
registeredToolNames.add(registeredName);
|
|
178
184
|
let finalConfig = config;
|
|
179
185
|
if (ALWAYS_LOAD_TOOLS.has(registeredName)) {
|
|
180
186
|
const cfgObj = config;
|
|
@@ -182,6 +188,17 @@ async function main() {
|
|
|
182
188
|
finalConfig = { ...cfgObj, _meta: { ...existingMeta, "anthropic/alwaysLoad": true } };
|
|
183
189
|
}
|
|
184
190
|
const wrapped = async (...args) => {
|
|
191
|
+
if (shuttingDown) {
|
|
192
|
+
return {
|
|
193
|
+
content: [{
|
|
194
|
+
type: "text",
|
|
195
|
+
text: JSON.stringify({
|
|
196
|
+
ok: false,
|
|
197
|
+
error: "phren-mcp server is shutting down; retry in a new session",
|
|
198
|
+
}, null, 2),
|
|
199
|
+
}],
|
|
200
|
+
};
|
|
201
|
+
}
|
|
185
202
|
if (!indexReady || !db) {
|
|
186
203
|
return {
|
|
187
204
|
content: [{
|
|
@@ -220,23 +237,30 @@ async function main() {
|
|
|
220
237
|
updateFileInIndexFn(db, filePath, phrenPath);
|
|
221
238
|
},
|
|
222
239
|
};
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
240
|
+
// Lazy-imported tool registries — only the MCP server needs them. Registration
|
|
241
|
+
// order is irrelevant (each module registers a disjoint set of tools).
|
|
242
|
+
const toolModules = await Promise.all([
|
|
243
|
+
import("./tools/search.js"),
|
|
244
|
+
import("./tools/tasks.js"),
|
|
245
|
+
import("./tools/finding.js"),
|
|
246
|
+
import("./tools/memory.js"),
|
|
247
|
+
import("./tools/data.js"),
|
|
248
|
+
import("./tools/graph.js"),
|
|
249
|
+
import("./tools/session.js"),
|
|
250
|
+
import("./tools/ops.js"),
|
|
251
|
+
import("./tools/skills.js"),
|
|
252
|
+
import("./tools/hooks.js"),
|
|
253
|
+
import("./tools/extract.js"),
|
|
254
|
+
import("./tools/config.js"),
|
|
255
|
+
]);
|
|
256
|
+
for (const mod of toolModules)
|
|
257
|
+
mod.register(server, ctx);
|
|
235
258
|
const transport = new StdioServerTransport();
|
|
236
259
|
await server.connect(transport);
|
|
237
260
|
console.error(`phren-mcp running (${phrenPath})`);
|
|
238
261
|
// Graceful shutdown: drain write queue and close DB before exit
|
|
239
262
|
async function shutdown(signal) {
|
|
263
|
+
shuttingDown = true;
|
|
240
264
|
structuredLog("info", "shutdown", `Received ${signal}, draining write queue...`);
|
|
241
265
|
try {
|
|
242
266
|
await writeQueue;
|
|
@@ -244,6 +268,17 @@ async function main() {
|
|
|
244
268
|
catch {
|
|
245
269
|
// Write queue errors already logged
|
|
246
270
|
}
|
|
271
|
+
// Persist any pending embeddings; bounded so a slow/unreachable Ollama
|
|
272
|
+
// can't stall shutdown.
|
|
273
|
+
try {
|
|
274
|
+
await Promise.race([
|
|
275
|
+
flushEmbeddingQueue(),
|
|
276
|
+
new Promise((resolve) => setTimeout(resolve, 3000)),
|
|
277
|
+
]);
|
|
278
|
+
}
|
|
279
|
+
catch (err) {
|
|
280
|
+
logger.warn("shutdown", `embFlush: ${errorMessage(err)}`);
|
|
281
|
+
}
|
|
247
282
|
try {
|
|
248
283
|
db?.close();
|
|
249
284
|
}
|