Fix same-vault Graphify semantic merge

This commit is contained in:
Зарубин Филипп
2026-06-18 00:54:10 +03:00
parent bb640adcfe
commit ccb8004f63
4 changed files with 241 additions and 17 deletions
+173
View File
@@ -0,0 +1,173 @@
import { promises as fs } from 'node:fs'
const VALID_FILE_TYPES = new Set(['code', 'concept', 'document', 'image', 'paper', 'rationale'])
const EDGE_KEY_FIELDS = ['source', 'target', 'relation', 'type', 'label', 'source_file']
export async function readGraph(file) {
return JSON.parse(await fs.readFile(file, 'utf8'))
}
export async function writeGraph(file, graph) {
await fs.writeFile(file, `${JSON.stringify(graph, null, 2)}\n`, 'utf8')
}
export function normalizeNodeId(id) {
let value = String(id || '')
while (/^[^:]+::/.test(value)) value = value.replace(/^[^:]+::/, '')
return value
}
export function normalizeFileType(value) {
const raw = String(value || '').trim()
return VALID_FILE_TYPES.has(raw) ? raw : 'concept'
}
function isBlank(value) {
return value === undefined || value === null || value === ''
}
function mergeNode(existing, incoming) {
const out = { ...existing }
for (const [key, value] of Object.entries(incoming)) {
if (key === 'id') continue
if (isBlank(out[key]) && !isBlank(value)) out[key] = value
}
out.file_type = normalizeFileType(out.file_type)
return out
}
function edgeArrayKey(graph) {
if (Array.isArray(graph.links)) return 'links'
if (Array.isArray(graph.edges)) return 'edges'
return 'links'
}
function normalizeEndpoint(value, idMap) {
const raw = String(value || '')
return idMap.get(raw) || normalizeNodeId(raw)
}
function normalizeEdge(edge, idMap) {
const out = { ...edge }
if ('source' in out) out.source = normalizeEndpoint(out.source, idMap)
if ('target' in out) out.target = normalizeEndpoint(out.target, idMap)
if (Array.isArray(out.nodes)) out.nodes = out.nodes.map(id => normalizeEndpoint(id, idMap))
return out
}
function edgeKey(edge) {
const fields = EDGE_KEY_FIELDS.map(field => edge[field] ?? '').join('\u0000')
const nodes = Array.isArray(edge.nodes) ? edge.nodes.join('\u0000') : ''
return `${fields}\u0000${nodes}`
}
export function normalizeGraphObject(graph) {
const sourceNodes = Array.isArray(graph.nodes) ? graph.nodes : []
const sourceEdgeKey = edgeArrayKey(graph)
const sourceEdges = Array.isArray(graph[sourceEdgeKey]) ? graph[sourceEdgeKey] : []
const idMap = new Map()
const nodesById = new Map()
const edgesByKey = new Map()
const stats = {
stripped_namespaces: 0,
normalized_file_types: 0,
merged_duplicate_nodes: 0,
dropped_duplicate_edges: 0
}
for (const node of sourceNodes) {
const originalId = String(node.id || '')
const normalizedId = normalizeNodeId(originalId)
if (normalizedId !== originalId) stats.stripped_namespaces += 1
idMap.set(originalId, normalizedId)
const fileType = normalizeFileType(node.file_type)
if (node.file_type && fileType !== node.file_type) stats.normalized_file_types += 1
const normalizedNode = { ...node, id: normalizedId, file_type: fileType }
if (nodesById.has(normalizedId)) {
stats.merged_duplicate_nodes += 1
nodesById.set(normalizedId, mergeNode(nodesById.get(normalizedId), normalizedNode))
} else {
nodesById.set(normalizedId, normalizedNode)
}
}
for (const edge of sourceEdges) {
const normalizedEdge = normalizeEdge(edge, idMap)
const key = edgeKey(normalizedEdge)
if (edgesByKey.has(key)) {
stats.dropped_duplicate_edges += 1
continue
}
edgesByKey.set(key, normalizedEdge)
}
const normalized = {
...graph,
nodes: [...nodesById.values()],
[sourceEdgeKey]: [...edgesByKey.values()]
}
if (sourceEdgeKey === 'links') delete normalized.edges
if (sourceEdgeKey === 'edges') delete normalized.links
return { graph: normalized, stats, edgeKey: sourceEdgeKey }
}
export function mergeGraphObjects(baseGraph, incomingGraph) {
const base = normalizeGraphObject(baseGraph)
const incoming = normalizeGraphObject(incomingGraph)
const outputEdgeKey = base.edgeKey || 'links'
const nodesById = new Map()
const edgesByKey = new Map()
const stats = {
base: base.stats,
incoming: incoming.stats,
merged_duplicate_nodes: 0,
dropped_duplicate_edges: 0
}
for (const node of base.graph.nodes || []) nodesById.set(node.id, node)
for (const node of incoming.graph.nodes || []) {
if (nodesById.has(node.id)) {
stats.merged_duplicate_nodes += 1
nodesById.set(node.id, mergeNode(nodesById.get(node.id), node))
} else {
nodesById.set(node.id, node)
}
}
for (const edge of base.graph[base.edgeKey] || []) edgesByKey.set(edgeKey(edge), edge)
for (const edge of incoming.graph[incoming.edgeKey] || []) {
const key = edgeKey(edge)
if (edgesByKey.has(key)) {
stats.dropped_duplicate_edges += 1
continue
}
edgesByKey.set(key, edge)
}
const graph = {
...base.graph,
nodes: [...nodesById.values()],
[outputEdgeKey]: [...edgesByKey.values()]
}
if (outputEdgeKey === 'links') delete graph.edges
if (outputEdgeKey === 'edges') delete graph.links
return { graph, stats }
}
export function graphStats(graph) {
const edges = Array.isArray(graph.links) ? graph.links : Array.isArray(graph.edges) ? graph.edges : []
const prefixes = new Map()
let badFileTypes = 0
for (const node of graph.nodes || []) {
const id = String(node.id || '')
const prefix = id.match(/^([^:]+)::/)?.[1]
if (prefix) prefixes.set(prefix, (prefixes.get(prefix) || 0) + 1)
if (node.file_type && !VALID_FILE_TYPES.has(node.file_type)) badFileTypes += 1
}
return {
nodes: Array.isArray(graph.nodes) ? graph.nodes.length : 0,
edges: edges.length,
prefixes: [...prefixes.entries()].sort((a, b) => b[1] - a[1]),
bad_file_types: badFileTypes
}
}
+12 -17
View File
@@ -4,6 +4,7 @@ import { existsSync, readFileSync } from 'node:fs'
import path from 'node:path'
import os from 'node:os'
import { spawn } from 'node:child_process'
import { graphStats as normalizedGraphStats, mergeGraphObjects, readGraph, writeGraph } from './mnemazine-graph-utils.mjs'
const argv = process.argv.slice(2)
@@ -38,7 +39,7 @@ const TIMEOUT_MS = Number(arg('timeout-seconds', String(CONFIG.timeout_seconds |
const SMOKE_TIMEOUT_MS = Number(arg('smoke-timeout-seconds', String(CONFIG.smoke_timeout_seconds || '120'))) * 1000
const SHRINK_THRESHOLD = Number(arg('shrink-threshold', String(CONFIG.shrink_threshold || '0.85')))
const MAX_CONCURRENCY = arg('max-concurrency', process.env.MNEMAZINE_GRAPHIFY_MAX_CONCURRENCY || String(CONFIG.max_concurrency || (BACKEND === 'kimi' ? '3' : '')))
const ALLOW_PARTIAL_SEMANTIC = arg('allow-partial-semantic', process.env.MNEMAZINE_GRAPHIFY_ALLOW_PARTIAL || '1') !== '0'
const ALLOW_PARTIAL_SEMANTIC = arg('allow-partial-semantic', process.env.MNEMAZINE_GRAPHIFY_ALLOW_PARTIAL || String(CONFIG.allow_partial_semantic ? 1 : 0)) !== '0'
const JSON_OUT = hasFlag('json')
const GRAPHIFY_OUT = path.join(VAULT, 'graphify-out')
const GRAPH_PATH = path.join(GRAPHIFY_OUT, 'graph.json')
@@ -407,24 +408,18 @@ async function realignReport() {
}
async function mergeSemanticGraph(semanticGraphPath) {
const mergedPath = path.join(GRAPHIFY_OUT, 'merged-graph.json')
const result = await runCommand('graphify', ['merge-graphs', GRAPH_PATH, semanticGraphPath, '--out', mergedPath], { cwd: ROOT })
if (result.code !== 0 || result.timedOut || !existsSync(mergedPath)) {
return {
ok: false,
code: result.code,
timedOut: result.timedOut,
stdout_tail: truncate(result.stdout, 1200),
stderr_tail: truncate(result.stderr, 1200)
}
}
await fs.rename(mergedPath, GRAPH_PATH)
const before = await readGraph(GRAPH_PATH)
const semantic = await readGraph(semanticGraphPath)
const merged = mergeGraphObjects(before, semantic)
await writeGraph(GRAPH_PATH, merged.graph)
return {
ok: true,
code: result.code,
timedOut: result.timedOut,
stdout_tail: truncate(result.stdout, 1200),
stderr_tail: truncate(result.stderr, 1200)
code: 0,
timedOut: false,
stats: merged.stats,
graph: normalizedGraphStats(merged.graph),
stdout_tail: '',
stderr_tail: ''
}
}
+2
View File
@@ -51,6 +51,8 @@ async function checkSyntax() {
'scripts/mnemazine-vault-quality-gate.mjs',
'scripts/mnemazine-refresh-graphify.mjs',
'scripts/mnemazine-refresh-graphify-smoke.mjs',
'scripts/mnemazine-graph-utils.mjs',
'scripts/mnemazine-repair-graphify-graph.mjs',
'scripts/mnemazine-synthesize.mjs',
'scripts/mnemazine-weekly-brief-html.mjs',
'scripts/mnemazine-report-quality-gate.mjs',
@@ -0,0 +1,54 @@
#!/usr/bin/env node
import { promises as fs } from 'node:fs'
import { existsSync } from 'node:fs'
import path from 'node:path'
import {
graphStats,
normalizeGraphObject,
readGraph,
writeGraph
} from './mnemazine-graph-utils.mjs'
const argv = process.argv.slice(2)
function arg(name, fallback = '') {
const hit = argv.find(item => item === `--${name}` || item.startsWith(`--${name}=`))
if (!hit) return fallback
return hit.includes('=') ? hit.split('=').slice(1).join('=') : argv[argv.indexOf(hit) + 1] || fallback
}
function hasFlag(name) {
return argv.includes(`--${name}`)
}
const graphPath = path.resolve(arg('graph', path.join(process.env.HOME || '.', 'Мозг/graphify-out/graph.json')))
const outPath = arg('out', '')
const apply = hasFlag('apply')
async function main() {
if (!existsSync(graphPath)) throw new Error(`graph not found: ${graphPath}`)
const beforeGraph = await readGraph(graphPath)
const before = graphStats(beforeGraph)
const repaired = normalizeGraphObject(beforeGraph)
const after = graphStats(repaired.graph)
const target = apply ? graphPath : path.resolve(outPath || `${graphPath}.repaired`)
await fs.mkdir(path.dirname(target), { recursive: true })
await writeGraph(target, repaired.graph)
const summary = {
ok: true,
applied: apply,
graph: graphPath,
out: target,
before,
after,
repair: repaired.stats
}
console.log(JSON.stringify(summary, null, 2))
}
main().catch(error => {
console.error(error.message || error)
process.exit(1)
})