@phren/cli 0.1.33 → 0.1.34
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/team.js +26 -13
- package/dist/content/dedup.js +25 -3
- package/dist/content/learning.js +10 -16
- package/dist/generated/memory-ui-graph.browser.js +1 -1
- package/dist/governance/scores.js +26 -45
- package/dist/index.js +32 -1
- package/dist/memory-ui-graph.runtime.js +1 -1
- package/dist/shared/index.d.ts +2 -0
- package/dist/shared/index.js +90 -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
package/dist/shared/index.js
CHANGED
|
@@ -72,7 +72,7 @@ import { formatActorAttribution, parseSourceComment } from "../content/citation.
|
|
|
72
72
|
import { beginUserFragmentBuildCache, endUserFragmentBuildCache, extractAndLinkFragments, ensureGlobalEntitiesTable, } from "./fragment-graph.js";
|
|
73
73
|
import { bootstrapSqlJs } from "./sqljs.js";
|
|
74
74
|
import { getProjectOwnershipMode, getProjectSourcePath, readProjectConfig } from "../project-config.js";
|
|
75
|
-
import { buildSourceDocKey,
|
|
75
|
+
import { buildSourceDocKey, decodeStringRow, getDocSourceKey, queryDocRows, queryRows, } from "../index-query.js";
|
|
76
76
|
import { classifyTopicForText, readProjectTopics, } from "../project-topics.js";
|
|
77
77
|
export { porterStem } from "./stemmer.js";
|
|
78
78
|
export { cosineFallback } from "./search-fallback.js";
|
|
@@ -92,9 +92,19 @@ function scheduleEmbedding(phrenPath, docPath, content) {
|
|
|
92
92
|
if (_embTimer)
|
|
93
93
|
clearTimeout(_embTimer);
|
|
94
94
|
_embTimer = setTimeout(() => { _embTimer = null; void _drainEmbQueue(); }, 500);
|
|
95
|
-
// Unref so the timer doesn't keep short-lived CLI processes alive
|
|
95
|
+
// Unref so the timer doesn't keep short-lived CLI processes alive. Pending
|
|
96
|
+
// embeddings are lost if such a process exits first (acceptable: they're
|
|
97
|
+
// regenerated on demand); the MCP server calls flushEmbeddingQueue on shutdown.
|
|
96
98
|
_embTimer.unref();
|
|
97
99
|
}
|
|
100
|
+
/** Drain pending embeddings immediately (used by the MCP server's graceful shutdown). */
|
|
101
|
+
export async function flushEmbeddingQueue() {
|
|
102
|
+
if (_embTimer) {
|
|
103
|
+
clearTimeout(_embTimer);
|
|
104
|
+
_embTimer = null;
|
|
105
|
+
}
|
|
106
|
+
await _drainEmbQueue();
|
|
107
|
+
}
|
|
98
108
|
async function _drainEmbQueue() {
|
|
99
109
|
if (_embQueue.size === 0)
|
|
100
110
|
return;
|
|
@@ -375,10 +385,17 @@ function computePhrenHash(phrenPath, profile, preGlobbed) {
|
|
|
375
385
|
}
|
|
376
386
|
const INDEX_HASHES_FILENAME = "index-hashes.json";
|
|
377
387
|
const INDEX_SCHEMA_VERSION = 3; // bump when FTS schema changes to force full rebuild
|
|
388
|
+
// Deletion share above which an incremental update falls back to a full rebuild.
|
|
389
|
+
const MAX_INCREMENTAL_DELETE_RATIO = 0.5;
|
|
378
390
|
function hashFileContent(filePath) {
|
|
379
391
|
const content = fs.readFileSync(filePath, "utf-8");
|
|
380
392
|
return crypto.createHash("sha256").update(content).digest("hex");
|
|
381
393
|
}
|
|
394
|
+
/** Errors expected from idempotent schema migrations run against older cached DBs. */
|
|
395
|
+
function isExpectedMigrationError(err) {
|
|
396
|
+
const msg = errorMessage(err).toLowerCase();
|
|
397
|
+
return msg.includes("duplicate column name") || msg.includes("no such table");
|
|
398
|
+
}
|
|
382
399
|
function loadHashMap(phrenPath) {
|
|
383
400
|
const runtimeDir = path.join(phrenPath, ".runtime");
|
|
384
401
|
const hashFile = path.join(runtimeDir, INDEX_HASHES_FILENAME);
|
|
@@ -392,7 +409,7 @@ function loadHashMap(phrenPath) {
|
|
|
392
409
|
}
|
|
393
410
|
return { hashes: {} };
|
|
394
411
|
}
|
|
395
|
-
function saveHashMap(phrenPath, hashes, knownPaths) {
|
|
412
|
+
function saveHashMap(phrenPath, hashes, knownPaths, meta) {
|
|
396
413
|
const runtimeDir = path.join(phrenPath, ".runtime");
|
|
397
414
|
try {
|
|
398
415
|
fs.mkdirSync(runtimeDir, { recursive: true });
|
|
@@ -402,24 +419,34 @@ function saveHashMap(phrenPath, hashes, knownPaths) {
|
|
|
402
419
|
// Prune entries for files that no longer exist to prevent ghost paths from causing
|
|
403
420
|
// repeated full rebuilds when deleted files are found in the hash map.
|
|
404
421
|
let existing = {};
|
|
422
|
+
let existingMeta = {};
|
|
405
423
|
try {
|
|
406
424
|
const data = JSON.parse(fs.readFileSync(hashFile, "utf-8"));
|
|
407
425
|
if (data.hashes && typeof data.hashes === "object")
|
|
408
426
|
existing = data.hashes;
|
|
427
|
+
if (data.meta && typeof data.meta === "object")
|
|
428
|
+
existingMeta = data.meta;
|
|
409
429
|
}
|
|
410
430
|
catch (err) {
|
|
411
431
|
logger.debug("saveHashMap readExisting", errorMessage(err));
|
|
412
432
|
}
|
|
413
433
|
const merged = { ...existing, ...hashes };
|
|
434
|
+
const mergedMeta = { ...existingMeta, ...meta };
|
|
414
435
|
// Remove entries for paths that no longer exist. When knownPaths is provided
|
|
415
436
|
// (build passes supply the full file list), use set membership instead of
|
|
416
437
|
// hitting the filesystem — avoids N sync stat calls inside the lock.
|
|
417
438
|
for (const filePath of Object.keys(merged)) {
|
|
418
439
|
if (knownPaths ? !knownPaths.has(filePath) : !fs.existsSync(filePath)) {
|
|
419
440
|
delete merged[filePath];
|
|
441
|
+
delete mergedMeta[filePath];
|
|
420
442
|
}
|
|
421
443
|
}
|
|
422
|
-
|
|
444
|
+
// Drop meta for paths without a hash entry (meta is only an optimization).
|
|
445
|
+
for (const filePath of Object.keys(mergedMeta)) {
|
|
446
|
+
if (!(filePath in merged))
|
|
447
|
+
delete mergedMeta[filePath];
|
|
448
|
+
}
|
|
449
|
+
fs.writeFileSync(hashFile, JSON.stringify({ version: INDEX_SCHEMA_VERSION, hashes: merged, meta: mergedMeta }, null, 2));
|
|
423
450
|
});
|
|
424
451
|
}
|
|
425
452
|
catch (err) {
|
|
@@ -680,7 +707,8 @@ export function updateFileInIndex(db, filePath, phrenPath) {
|
|
|
680
707
|
try {
|
|
681
708
|
const hashData = loadHashMap(phrenPath);
|
|
682
709
|
hashData.hashes[resolvedPath] = hashFileContent(resolvedPath);
|
|
683
|
-
|
|
710
|
+
const stat = fs.statSync(resolvedPath);
|
|
711
|
+
saveHashMap(phrenPath, hashData.hashes, undefined, { [resolvedPath]: { mtimeMs: stat.mtimeMs, size: stat.size } });
|
|
684
712
|
}
|
|
685
713
|
catch (err) {
|
|
686
714
|
logger.debug("updateFileInIndex hashMap", errorMessage(err));
|
|
@@ -839,13 +867,29 @@ function mergeManualLinks(db, phrenPath) {
|
|
|
839
867
|
return;
|
|
840
868
|
try {
|
|
841
869
|
const manualLinks = JSON.parse(fs.readFileSync(manualLinksPath, 'utf8'));
|
|
870
|
+
// Resolve all sourceDoc keys in one query instead of one lookup per link.
|
|
871
|
+
// Mirrors queryDocBySourceKey semantics: match project + basename(filename),
|
|
872
|
+
// then compare the full source-doc key.
|
|
873
|
+
const projects = [...new Set(manualLinks.map((l) => l.sourceDoc.match(/^([^/]+)\//)?.[1]).filter((p) => !!p))];
|
|
874
|
+
const filenames = [...new Set(manualLinks
|
|
875
|
+
.map((l) => l.sourceDoc.match(/^[^/]+\/(.+)$/)?.[1])
|
|
876
|
+
.filter((rest) => !!rest)
|
|
877
|
+
.map((rest) => path.basename(rest)))];
|
|
878
|
+
const validSourceKeys = new Set();
|
|
879
|
+
if (projects.length && filenames.length) {
|
|
880
|
+
const sql = `SELECT project, filename, path FROM docs WHERE project IN (${projects.map(() => "?").join(",")}) AND filename IN (${filenames.map(() => "?").join(",")})`;
|
|
881
|
+
const rows = queryRows(db, sql, [...projects, ...filenames]) ?? [];
|
|
882
|
+
for (const row of rows) {
|
|
883
|
+
const [project, filename, docPath] = decodeStringRow(row, 3, "mergeManualLinks");
|
|
884
|
+
validSourceKeys.add(getDocSourceKey({ project, filename, path: docPath }, phrenPath));
|
|
885
|
+
}
|
|
886
|
+
}
|
|
842
887
|
let pruned = false;
|
|
843
888
|
const validLinks = [];
|
|
844
889
|
for (const link of manualLinks) {
|
|
845
890
|
try {
|
|
846
891
|
// Validate: skip manual links whose sourceDoc no longer exists in the index
|
|
847
|
-
|
|
848
|
-
if (!docCheck) {
|
|
892
|
+
if (!validSourceKeys.has(link.sourceDoc)) {
|
|
849
893
|
logger.debug("manualLinks", `pruning stale link to "${link.sourceDoc}"`);
|
|
850
894
|
pruned = true;
|
|
851
895
|
continue;
|
|
@@ -952,7 +996,11 @@ async function buildIndexImpl(phrenPath, profile) {
|
|
|
952
996
|
try {
|
|
953
997
|
db.run("ALTER TABLE entities ADD COLUMN first_seen_at TEXT");
|
|
954
998
|
}
|
|
955
|
-
catch {
|
|
999
|
+
catch (err) {
|
|
1000
|
+
// Usually "duplicate column name" — column already exists
|
|
1001
|
+
if (!isExpectedMigrationError(err))
|
|
1002
|
+
logger.warn("buildIndex migration", errorMessage(err));
|
|
1003
|
+
}
|
|
956
1004
|
debugLog(`Loaded FTS index from cache (${hash.slice(0, 8)}) in ${Date.now() - t0}ms [sentinel-hit]`);
|
|
957
1005
|
appendIndexEvent(phrenPath, {
|
|
958
1006
|
event: "build_index",
|
|
@@ -992,16 +1040,31 @@ async function buildIndexImpl(phrenPath, profile) {
|
|
|
992
1040
|
try {
|
|
993
1041
|
db.run("ALTER TABLE entities ADD COLUMN first_seen_at TEXT");
|
|
994
1042
|
}
|
|
995
|
-
catch {
|
|
996
|
-
|
|
1043
|
+
catch (err) {
|
|
1044
|
+
// Usually "duplicate column name" — column already exists
|
|
1045
|
+
if (!isExpectedMigrationError(err))
|
|
1046
|
+
logger.warn("buildIndex migration", errorMessage(err));
|
|
1047
|
+
}
|
|
1048
|
+
// Compute current file hashes and determine what changed.
|
|
1049
|
+
// Files whose mtime+size match the stored snapshot reuse the stored hash,
|
|
1050
|
+
// skipping a read+SHA256 per file; the content hash stays the source of
|
|
1051
|
+
// truth whenever the stat changed.
|
|
997
1052
|
const allFiles = globResult.entries;
|
|
1053
|
+
const savedMeta = savedHashData.meta ?? {};
|
|
998
1054
|
const currentHashes = {};
|
|
1055
|
+
const currentMeta = {};
|
|
999
1056
|
const changedFiles = [];
|
|
1000
1057
|
const newFiles = [];
|
|
1001
1058
|
for (const entry of allFiles) {
|
|
1002
1059
|
try {
|
|
1003
|
-
const
|
|
1060
|
+
const stat = fs.statSync(entry.fullPath);
|
|
1061
|
+
const prevHash = savedHashes[entry.fullPath];
|
|
1062
|
+
const prevMeta = savedMeta[entry.fullPath];
|
|
1063
|
+
const statUnchanged = prevHash !== undefined && prevMeta !== undefined
|
|
1064
|
+
&& prevMeta.mtimeMs === stat.mtimeMs && prevMeta.size === stat.size;
|
|
1065
|
+
const fileHash = statUnchanged ? prevHash : hashFileContent(entry.fullPath);
|
|
1004
1066
|
currentHashes[entry.fullPath] = fileHash;
|
|
1067
|
+
currentMeta[entry.fullPath] = { mtimeMs: stat.mtimeMs, size: stat.size };
|
|
1005
1068
|
if (!(entry.fullPath in savedHashes)) {
|
|
1006
1069
|
newFiles.push(entry);
|
|
1007
1070
|
}
|
|
@@ -1016,10 +1079,13 @@ async function buildIndexImpl(phrenPath, profile) {
|
|
|
1016
1079
|
// Check for files missing from the index (deleted files)
|
|
1017
1080
|
const currentPaths = new Set(Object.keys(currentHashes));
|
|
1018
1081
|
const missingFromIndex = Object.keys(savedHashes).filter(p => !currentPaths.has(p));
|
|
1019
|
-
// Force full rebuild
|
|
1082
|
+
// Force a full rebuild when a large share of saved files vanished at once —
|
|
1083
|
+
// guards against pathological glob results (e.g. a temporarily unmounted
|
|
1084
|
+
// store dir) and bounds FTS bloat from mass tombstones. Smaller deletions
|
|
1085
|
+
// are removed incrementally.
|
|
1020
1086
|
const totalSaved = Object.keys(savedHashes).length;
|
|
1021
|
-
if (totalSaved > 0 && missingFromIndex.length / totalSaved >
|
|
1022
|
-
debugLog(
|
|
1087
|
+
if (totalSaved > 0 && missingFromIndex.length / totalSaved > MAX_INCREMENTAL_DELETE_RATIO) {
|
|
1088
|
+
debugLog(`>${MAX_INCREMENTAL_DELETE_RATIO * 100}% files missing (${missingFromIndex.length}/${totalSaved}), forcing full rebuild`);
|
|
1023
1089
|
// Fall through to full rebuild below
|
|
1024
1090
|
}
|
|
1025
1091
|
else if (changedFiles.length === 0 && newFiles.length === 0 && missingFromIndex.length === 0) {
|
|
@@ -1076,7 +1142,11 @@ async function buildIndexImpl(phrenPath, profile) {
|
|
|
1076
1142
|
try {
|
|
1077
1143
|
db.run("DELETE FROM global_entities WHERE doc_key = ?", [sourceDocKey]);
|
|
1078
1144
|
}
|
|
1079
|
-
catch {
|
|
1145
|
+
catch (err) {
|
|
1146
|
+
// Usually "no such table" — table may not exist in older cached DBs
|
|
1147
|
+
if (!isExpectedMigrationError(err))
|
|
1148
|
+
logger.warn("buildIndex migration", errorMessage(err));
|
|
1149
|
+
}
|
|
1080
1150
|
db.run("DELETE FROM docs WHERE path = ?", [entry.fullPath]);
|
|
1081
1151
|
}
|
|
1082
1152
|
if (insertFileIntoIndex(db, entry, phrenPath, { scheduleEmbeddings: true })) {
|
|
@@ -1103,7 +1173,7 @@ async function buildIndexImpl(phrenPath, profile) {
|
|
|
1103
1173
|
throw err;
|
|
1104
1174
|
}
|
|
1105
1175
|
}
|
|
1106
|
-
saveHashMap(phrenPath, currentHashes, new Set(Object.keys(currentHashes)));
|
|
1176
|
+
saveHashMap(phrenPath, currentHashes, new Set(Object.keys(currentHashes)), currentMeta);
|
|
1107
1177
|
touchSentinel(phrenPath);
|
|
1108
1178
|
invalidateDfCache();
|
|
1109
1179
|
// Save updated cache
|
|
@@ -1160,6 +1230,7 @@ async function buildIndexImpl(phrenPath, profile) {
|
|
|
1160
1230
|
ensureGlobalEntitiesTable(db);
|
|
1161
1231
|
const allFiles = globResult.entries;
|
|
1162
1232
|
const newHashes = {};
|
|
1233
|
+
const newMeta = {};
|
|
1163
1234
|
let fileCount = 0;
|
|
1164
1235
|
// Try loading cached fragment graph
|
|
1165
1236
|
const graphPath = runtimeFile(phrenPath, 'entity-graph.json');
|
|
@@ -1167,6 +1238,8 @@ async function buildIndexImpl(phrenPath, profile) {
|
|
|
1167
1238
|
for (const entry of allFiles) {
|
|
1168
1239
|
try {
|
|
1169
1240
|
newHashes[entry.fullPath] = hashFileContent(entry.fullPath);
|
|
1241
|
+
const stat = fs.statSync(entry.fullPath);
|
|
1242
|
+
newMeta[entry.fullPath] = { mtimeMs: stat.mtimeMs, size: stat.size };
|
|
1170
1243
|
}
|
|
1171
1244
|
catch (err) {
|
|
1172
1245
|
logger.debug("computePhrenHash skip", errorMessage(err));
|
|
@@ -1202,7 +1275,7 @@ async function buildIndexImpl(phrenPath, profile) {
|
|
|
1202
1275
|
// Always merge manual links (survive rebuild)
|
|
1203
1276
|
mergeManualLinks(db, phrenPath);
|
|
1204
1277
|
// ── Finalize: persist hashes, save cache, log ─────────────────────────────
|
|
1205
|
-
saveHashMap(phrenPath, newHashes, new Set(Object.keys(newHashes)));
|
|
1278
|
+
saveHashMap(phrenPath, newHashes, new Set(Object.keys(newHashes)), newMeta);
|
|
1206
1279
|
touchSentinel(phrenPath);
|
|
1207
1280
|
invalidateDfCache();
|
|
1208
1281
|
const buildMs = Date.now() - t0;
|
package/dist/shared/retrieval.js
CHANGED
|
@@ -68,17 +68,36 @@ function intentBoost(intent, docType) {
|
|
|
68
68
|
return 2;
|
|
69
69
|
return 0;
|
|
70
70
|
}
|
|
71
|
+
// fileRelevanceBoost runs once per candidate doc during ranking, all sharing the
|
|
72
|
+
// same changedFiles Set. Cache the normalized view (keyed by the Set instance) so
|
|
73
|
+
// path normalization happens once per ranking pass instead of once per doc.
|
|
74
|
+
const _normalizedChangedFiles = new WeakMap();
|
|
75
|
+
function normalizeChangedFiles(changedFiles) {
|
|
76
|
+
let cached = _normalizedChangedFiles.get(changedFiles);
|
|
77
|
+
if (cached)
|
|
78
|
+
return cached;
|
|
79
|
+
const basenames = new Set();
|
|
80
|
+
const paths = [];
|
|
81
|
+
for (const cf of changedFiles) {
|
|
82
|
+
const n = cf.replace(/\\/g, "/");
|
|
83
|
+
basenames.add(path.basename(n));
|
|
84
|
+
paths.push(n);
|
|
85
|
+
}
|
|
86
|
+
cached = { basenames, paths };
|
|
87
|
+
_normalizedChangedFiles.set(changedFiles, cached);
|
|
88
|
+
return cached;
|
|
89
|
+
}
|
|
71
90
|
export function fileRelevanceBoost(filePath, changedFiles) {
|
|
72
91
|
if (changedFiles.size === 0)
|
|
73
92
|
return 0;
|
|
74
93
|
const normalized = filePath.replace(/\\/g, "/");
|
|
75
94
|
const docBasename = path.basename(normalized);
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
95
|
+
const { basenames, paths } = normalizeChangedFiles(changedFiles);
|
|
96
|
+
// Exact basename match to avoid 'index.ts' matching 'shared-index.ts'
|
|
97
|
+
if (basenames.has(docBasename))
|
|
98
|
+
return 3;
|
|
99
|
+
// Also match if the full changed-file path is a suffix of the doc path
|
|
100
|
+
for (const n of paths) {
|
|
82
101
|
if (normalized.endsWith(`/${n}`))
|
|
83
102
|
return 3;
|
|
84
103
|
}
|
package/dist/telemetry.js
CHANGED
|
@@ -55,7 +55,10 @@ function flushTelemetryForPath(phrenPath) {
|
|
|
55
55
|
const file = telemetryPath(phrenPath);
|
|
56
56
|
try {
|
|
57
57
|
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
58
|
-
|
|
58
|
+
// Usage stats are private to the user: owner-only perms, including files
|
|
59
|
+
// created by older versions (mode only applies on create).
|
|
60
|
+
fs.writeFileSync(file, JSON.stringify(data, null, 2) + "\n", { mode: 0o600 });
|
|
61
|
+
fs.chmodSync(file, 0o600);
|
|
59
62
|
}
|
|
60
63
|
catch (err) {
|
|
61
64
|
logger.debug("telemetry flush", errorMessage(err));
|
package/dist/tools/finding.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
1
|
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2
2
|
import { type McpContext } from "./types.js";
|
|
3
|
+
export declare function findConflictCandidates(phrenPath: string, project: string, finding: string): string[];
|
|
3
4
|
export declare function register(server: McpServer, ctx: McpContext): void;
|
package/dist/tools/finding.js
CHANGED
|
@@ -8,7 +8,7 @@ import { removeFinding as removeFindingCore, removeFindings as removeFindingsCor
|
|
|
8
8
|
import { debugLog, EXEC_TIMEOUT_MS, FINDING_TYPES, normalizeMemoryScope, } from "../shared.js";
|
|
9
9
|
import { getCurrentActor, getMachineName } from "../machine-identity.js";
|
|
10
10
|
import { addFindingToFile, addFindingsToFile, checkSemanticConflicts, autoMergeConflicts, } from "../shared/content.js";
|
|
11
|
-
import { jaccardTokenize, jaccardSimilarity, stripMetadata } from "../content/dedup.js";
|
|
11
|
+
import { jaccardTokenize, jaccardSimilarity, stripMetadata, detectConflicts, extractDynamicEntities } from "../content/dedup.js";
|
|
12
12
|
import { runCustomHooks } from "../hooks.js";
|
|
13
13
|
import { incrementSessionFindings } from "./session.js";
|
|
14
14
|
import { extractFragmentNames } from "../shared/fragment-graph.js";
|
|
@@ -49,6 +49,30 @@ function findJaccardCandidates(phrenPath, project, finding) {
|
|
|
49
49
|
return [];
|
|
50
50
|
}
|
|
51
51
|
}
|
|
52
|
+
// Heuristic conflict candidates surfaced to the calling agent so it can decide whether a
|
|
53
|
+
// genuine contradiction exists — no extra LLM/API call, the agent in the loop is the judge.
|
|
54
|
+
// Mirrors findJaccardCandidates (potential duplicates). Capped to keep the response small.
|
|
55
|
+
const MAX_CONFLICT_CANDIDATES = 5;
|
|
56
|
+
export function findConflictCandidates(phrenPath, project, finding) {
|
|
57
|
+
try {
|
|
58
|
+
const findingsPath = path.join(phrenPath, project, FINDINGS_FILENAME);
|
|
59
|
+
if (!fs.existsSync(findingsPath))
|
|
60
|
+
return [];
|
|
61
|
+
const content = fs.readFileSync(findingsPath, "utf8");
|
|
62
|
+
const activeBullets = content.split("\n").filter((l) => l.startsWith("- ") && !isInactiveFindingLine(l));
|
|
63
|
+
if (activeBullets.length === 0)
|
|
64
|
+
return [];
|
|
65
|
+
const dynamicEntities = extractDynamicEntities(phrenPath, project);
|
|
66
|
+
return detectConflicts(finding, activeBullets, dynamicEntities)
|
|
67
|
+
.map((line) => stripMetadata(line).replace(/^-\s+/, "").trim().slice(0, 80))
|
|
68
|
+
.filter((snippet) => snippet.length > 0)
|
|
69
|
+
.slice(0, MAX_CONFLICT_CANDIDATES);
|
|
70
|
+
}
|
|
71
|
+
catch (err) {
|
|
72
|
+
logger.debug("add_finding", `findConflictCandidates: ${errorMessage(err)}`);
|
|
73
|
+
return [];
|
|
74
|
+
}
|
|
75
|
+
}
|
|
52
76
|
function extractConflictsWith(annotations) {
|
|
53
77
|
return annotations
|
|
54
78
|
.map((annotation) => annotation.match(/<!--\s*conflicts_with:\s*"([^"]+)"/)?.[1])
|
|
@@ -142,11 +166,15 @@ async function handleAddFinding(ctx, params) {
|
|
|
142
166
|
return withWriteQueue(async () => {
|
|
143
167
|
runCustomHooks(phrenPath, "pre-finding", { PHREN_PROJECT: project });
|
|
144
168
|
const allPotentialDuplicates = [];
|
|
169
|
+
const allPotentialConflicts = [];
|
|
145
170
|
const extraAnnotationsByFinding = [];
|
|
146
171
|
for (const f of findings) {
|
|
147
172
|
const candidates = findJaccardCandidates(phrenPath, project, f);
|
|
148
173
|
if (candidates.length > 0)
|
|
149
174
|
allPotentialDuplicates.push({ finding: f, candidates });
|
|
175
|
+
const conflictCandidates = findConflictCandidates(phrenPath, project, f);
|
|
176
|
+
if (conflictCandidates.length > 0)
|
|
177
|
+
allPotentialConflicts.push({ finding: f, candidates: conflictCandidates });
|
|
150
178
|
try {
|
|
151
179
|
const conflicts = await checkSemanticConflicts(phrenPath, project, f);
|
|
152
180
|
extraAnnotationsByFinding.push(conflicts.checked && conflicts.annotations.length > 0 ? conflicts.annotations : []);
|
|
@@ -180,6 +208,7 @@ async function handleAddFinding(ctx, params) {
|
|
|
180
208
|
skipped,
|
|
181
209
|
rejected,
|
|
182
210
|
...(allPotentialDuplicates.length > 0 ? { potentialDuplicates: allPotentialDuplicates } : {}),
|
|
211
|
+
...(allPotentialConflicts.length > 0 ? { potentialConflicts: allPotentialConflicts } : {}),
|
|
183
212
|
},
|
|
184
213
|
});
|
|
185
214
|
});
|
|
@@ -191,6 +220,8 @@ async function handleAddFinding(ctx, params) {
|
|
|
191
220
|
const taggedFinding = applyFindingTypePrefix(finding, findingType);
|
|
192
221
|
// Jaccard "maybe zone" scan — free, no LLM call. Return candidates so the agent decides.
|
|
193
222
|
const potentialDuplicates = findJaccardCandidates(phrenPath, project, taggedFinding);
|
|
223
|
+
// Heuristic contradiction candidates — also free, also agent-decides. No extra API call.
|
|
224
|
+
const potentialConflicts = findConflictCandidates(phrenPath, project, taggedFinding);
|
|
194
225
|
const semanticConflicts = await checkSemanticConflicts(phrenPath, project, taggedFinding);
|
|
195
226
|
runCustomHooks(phrenPath, "pre-finding", { PHREN_PROJECT: project });
|
|
196
227
|
const result = addFindingToFile(phrenPath, project, taggedFinding, citation, {
|
|
@@ -249,9 +280,15 @@ async function handleAddFinding(ctx, params) {
|
|
|
249
280
|
// Full DB fragment linking happens on the next index rebuild via updateFileInIndex →
|
|
250
281
|
// extractAndLinkFragments. We surface hints here so callers can see what was detected.
|
|
251
282
|
const detectedFragments = extractFragmentNames(taggedFinding);
|
|
283
|
+
// Surface heuristic conflict candidates for the agent to judge (only when the LLM path
|
|
284
|
+
// didn't already confirm a conflict, to avoid double-reporting the same relationship).
|
|
285
|
+
const conflictNote = (potentialConflicts.length > 0 && conflictsWithList.length === 0)
|
|
286
|
+
? ` ⚠ Possible contradiction with existing finding(s): ${potentialConflicts.map((c) => `"${c}"`).join("; ")}.` +
|
|
287
|
+
` If this genuinely contradicts one, resolve it with resolve_contradiction (or supersede_finding); if they're unrelated, ignore this note.`
|
|
288
|
+
: "";
|
|
252
289
|
return mcpResponse({
|
|
253
290
|
ok: true,
|
|
254
|
-
message: result.data.message,
|
|
291
|
+
message: result.data.message + conflictNote,
|
|
255
292
|
data: {
|
|
256
293
|
project,
|
|
257
294
|
finding: taggedFinding,
|
|
@@ -260,6 +297,7 @@ async function handleAddFinding(ctx, params) {
|
|
|
260
297
|
...(conflictsWithList.length > 0 ? { conflicts: conflictsWithList } : {}),
|
|
261
298
|
...(detectedFragments.length > 0 ? { detectedFragments } : {}),
|
|
262
299
|
...(potentialDuplicates.length > 0 ? { potentialDuplicates } : {}),
|
|
300
|
+
...(potentialConflicts.length > 0 ? { potentialConflicts } : {}),
|
|
263
301
|
scope: normalizedScope,
|
|
264
302
|
}
|
|
265
303
|
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@phren/cli",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.34",
|
|
4
4
|
"description": "Knowledge layer for AI agents — CLI, MCP server, and data layer",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -79,8 +79,8 @@
|
|
|
79
79
|
"glob": "^13.0.6",
|
|
80
80
|
"graphology": "^0.26.0",
|
|
81
81
|
"graphology-layout-forceatlas2": "^0.10.1",
|
|
82
|
-
"inquirer": "^
|
|
83
|
-
"js-yaml": "^4.
|
|
82
|
+
"inquirer": "^14.0.2",
|
|
83
|
+
"js-yaml": "^4.2.0",
|
|
84
84
|
"sigma": "^3.0.3",
|
|
85
85
|
"sql.js-fts5": "^1.4.0",
|
|
86
86
|
"zod": "^4.4.3"
|