monomind 1.18.12 → 1.18.13

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.
@@ -66,6 +66,34 @@ if (!entryPoint) {
66
66
  process.exit(0);
67
67
  }
68
68
 
69
+ // Skip if index is already fresh — don't waste CPU on every session start
70
+ const dbPath = path.join(projectDir, '.monomind', 'monograph.db');
71
+ if (fs.existsSync(dbPath)) {
72
+ try {
73
+ const mod = (() => {
74
+ try { return require(path.join(projectDir, 'packages', '@monomind', 'monograph', 'dist', 'src', 'index.js')); } catch {}
75
+ try { return require('@monoes/monograph'); } catch {}
76
+ return null;
77
+ })();
78
+ if (mod && mod.openDb) {
79
+ const db = mod.openDb(dbPath);
80
+ try {
81
+ const row = db.prepare("SELECT value FROM index_meta WHERE key='last_commit_hash'").get();
82
+ if (row && row.value) {
83
+ const { execSync } = require('child_process');
84
+ const behind = parseInt(execSync('git rev-list --count ' + row.value + '..HEAD 2>/dev/null', {
85
+ cwd: projectDir, encoding: 'utf-8', timeout: 2000
86
+ }).trim(), 10) || 0;
87
+ if (behind === 0) {
88
+ console.log('[graph] index is fresh — skipping rebuild');
89
+ process.exit(0);
90
+ }
91
+ }
92
+ } finally { mod.closeDb(db); }
93
+ }
94
+ } catch { /* can't check — proceed with build */ }
95
+ }
96
+
69
97
  // Skip if another build is already in progress (avoids SQLite BUSY on concurrent init + session-start)
70
98
  const lockPath = path.join(graphDir, 'build.lock');
71
99
  const now = Date.now();
@@ -381,7 +381,7 @@ module.exports = {
381
381
  }
382
382
  } catch (e) { /* ignore */ }
383
383
  }
384
- if (nodeCount > 100) {
384
+ if (nodeCount > 100 && hCtx._isGraphFresh()) {
385
385
  // Pre-resolve top-3 relevant files for the user's prompt — the LLM
386
386
  // sees the answer inline instead of being told to call a tool.
387
387
  // 3 is enough signal; more files inflate token cost on every prompt.
@@ -216,6 +216,7 @@ var hCtx = {
216
216
  _recordToolCall: _recordToolCall,
217
217
  _openMonographDb: _openMonographDb,
218
218
  _requireMonograph: _requireMonograph,
219
+ _isGraphFresh: _isGraphFresh,
219
220
  _triggerExtractYamlValue: _triggerExtractYamlValue,
220
221
  _triggerFinalize: _triggerFinalize,
221
222
  _triggerExtractFromFrontmatter: _triggerExtractFromFrontmatter,
@@ -312,7 +313,8 @@ const handlers = {
312
313
  if (db) {
313
314
  // Stop words: language keywords + generic single-word identifiers
314
315
  // that match Variable nodes in markdown/scripts (not real code symbols)
315
- var _grepStop = {import:1,export:1,from:1,require:1,return:1,function:1,const:1,let:1,var:1,class:1,interface:1,type:1,extends:1,implements:1,async:1,await:1,yield:1,throw:1,catch:1,finally:1,typeof:1,instanceof:1,void:1,null:1,undefined:1,true:1,false:1,this:1,super:1,new:1,delete:1,switch:1,case:1,break:1,continue:1,default:1,else:1,while:1,for:1,with:1,include:1,error:1,string:1,number:1,object:1,boolean:1,array:1,value:1,result:1,data:1,name:1,path:1,file:1,node:1,list:1,item:1,index:1,config:1,options:1,params:1,args:1,event:1,state:1,props:1,context:1,module:1,package:1,version:1,model:1,schema:1,table:1,query:1,response:1,request:1,handler:1,logger:1,graph:1,usage:1,storage:1,pipeline:1,service:1,utils:1,types:1,helpers:1,common:1,shared:1,server:1,client:1,source:1,output:1,input:1,stream:1,buffer:1,worker:1,plugin:1,format:1,render:1,update:1,create:1,remove:1,method:1,define:1,invoke:1,process:1,execute:1,resolve:1,reject:1,promise:1,callback:1,cursor:1,record:1,column:1,filter:1,reduce:1,status:1,action:1,commit:1,revert:1,publish:1,symbol:1,target:1,length:1,string:1,global:1,static:1,struct:1,select:1,insert:1,signal:1,socket:1,system:1,memory:1,parser:1,router:1,docker:1,script:1,bundle:1,deploy:1,search:1,prepare:1};
316
+ // monolean: only JS/TS reserved words — generic identifiers (handler, config, router, etc.) are valid symbol names
317
+ var _grepStop = {import:1,export:1,from:1,require:1,return:1,function:1,const:1,let:1,var:1,class:1,interface:1,type:1,extends:1,implements:1,async:1,await:1,yield:1,throw:1,catch:1,finally:1,typeof:1,instanceof:1,void:1,null:1,undefined:1,true:1,false:1,this:1,super:1,new:1,delete:1,switch:1,case:1,break:1,continue:1,default:1,else:1,while:1,for:1,with:1,static:1,enum:1,string:1,number:1,object:1,boolean:1};
316
318
 
317
319
  // --- Strategy 1: clean identifier → exact name match (case-sensitive) ---
318
320
  if (/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(pattern) && pattern.length >= 4
@@ -479,7 +481,8 @@ const handlers = {
479
481
  var db = _openMonographDb();
480
482
  if (db) {
481
483
  try {
482
- var _searchStop = {import:1,export:1,from:1,require:1,return:1,function:1,const:1,let:1,var:1,class:1,interface:1,type:1,extends:1,implements:1,async:1,await:1,yield:1,throw:1,catch:1,finally:1,typeof:1,instanceof:1,void:1,null:1,undefined:1,true:1,false:1,this:1,super:1,new:1,delete:1,switch:1,case:1,break:1,continue:1,default:1,else:1,while:1,for:1,with:1,include:1,error:1,string:1,number:1,object:1,boolean:1,array:1,value:1,result:1,data:1,name:1,path:1,file:1,node:1,list:1,item:1,index:1,config:1,options:1,params:1,args:1,event:1,state:1,props:1,context:1,module:1,package:1,version:1,model:1,schema:1,table:1,query:1,response:1,request:1,handler:1,logger:1,graph:1,usage:1,storage:1,pipeline:1,service:1,utils:1,types:1,helpers:1,common:1,shared:1,server:1,client:1,source:1,output:1,input:1,stream:1,buffer:1,worker:1,plugin:1,format:1,render:1,update:1,create:1,remove:1,method:1,define:1,invoke:1,process:1,execute:1,resolve:1,reject:1,promise:1,callback:1,cursor:1,record:1,column:1,filter:1,reduce:1,status:1,action:1,commit:1,revert:1,publish:1,symbol:1,target:1,length:1,string:1,global:1,static:1,struct:1,select:1,insert:1,signal:1,socket:1,system:1,memory:1,parser:1,router:1,docker:1,script:1,bundle:1,deploy:1,search:1,prepare:1};
484
+ // monolean: only JS/TS reserved words — generic identifiers are valid symbol names
485
+ var _searchStop = {import:1,export:1,from:1,require:1,return:1,function:1,const:1,let:1,var:1,class:1,interface:1,type:1,extends:1,implements:1,async:1,await:1,yield:1,throw:1,catch:1,finally:1,typeof:1,instanceof:1,void:1,null:1,undefined:1,true:1,false:1,this:1,super:1,new:1,delete:1,switch:1,case:1,break:1,continue:1,default:1,else:1,while:1,for:1,with:1,static:1,enum:1,string:1,number:1,object:1,boolean:1};
483
486
 
484
487
  var isCleanSymbol = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(grepPattern);
485
488
 
@@ -183,19 +183,31 @@ function _getDollarRate() {
183
183
 
184
184
  // Staleness guard — skip graph DB lookups when the index is too far behind HEAD.
185
185
  // Returns true if it's safe to use the graph, false if stale.
186
+ // Uses last_commit_hash from the DB (not file mtime, which drifts from backups/WAL/VACUUM).
186
187
  var _graphFreshnessCache = undefined;
187
188
  function _isGraphFresh() {
188
189
  if (_graphFreshnessCache !== undefined) return _graphFreshnessCache;
189
190
  try {
190
- var dbPath = path.join(CWD, '.monomind', 'monograph.db');
191
- var dbStat = fs.statSync(dbPath);
191
+ var db = _openMonographDb();
192
+ if (!db) { _graphFreshnessCache = true; return true; }
193
+ var row = null;
194
+ try {
195
+ row = db.prepare("SELECT value FROM index_meta WHERE key='last_commit_hash'").get() ||
196
+ db.prepare("SELECT value FROM index_meta WHERE key='lastCommit'").get();
197
+ } catch (_) {}
198
+ if (!row || !row.value) {
199
+ // No commit hash → can't check staleness, but DB may still have useful data
200
+ var nodeCount = 0;
201
+ try { nodeCount = db.prepare('SELECT COUNT(*) AS c FROM nodes').get().c; } catch (_) {}
202
+ _graphFreshnessCache = nodeCount > 0;
203
+ return _graphFreshnessCache;
204
+ }
192
205
  var { execSync } = require('child_process');
193
- var buildIso = new Date(dbStat.mtimeMs).toISOString();
194
- var out = execSync("git rev-list --count --since='" + buildIso + "' HEAD 2>/dev/null", {
206
+ var out = execSync('git rev-list --count ' + row.value + '..HEAD 2>/dev/null', {
195
207
  encoding: 'utf-8', timeout: 1500, stdio: ['pipe', 'pipe', 'pipe']
196
208
  }).trim();
197
209
  var behind = parseInt(out, 10) || 0;
198
- _graphFreshnessCache = behind <= 50; // monolean: 50 commits is generous enough
210
+ _graphFreshnessCache = behind <= 50;
199
211
  } catch(e) {
200
212
  _graphFreshnessCache = true; // can't check → assume fresh
201
213
  }
@@ -354,14 +366,24 @@ function injectGodNodesContext(CWD) {
354
366
  try {
355
367
  var nodeCount = db.prepare('SELECT COUNT(*) AS c FROM nodes').get().c;
356
368
  var edgeCount = db.prepare('SELECT COUNT(*) AS c FROM edges').get().c;
369
+ // Precompute degree via indexed edge lookups to avoid O(N) correlated subquery
357
370
  var godNodes = db.prepare(
358
- "SELECT n.name, n.label, n.file_path, " +
359
- "(SELECT COUNT(*) FROM edges WHERE source_id=n.id OR target_id=n.id) AS deg " +
360
- "FROM nodes n " +
371
+ "WITH deg AS (" +
372
+ " SELECT id, cnt FROM (" +
373
+ " SELECT source_id AS id, COUNT(*) AS cnt FROM edges GROUP BY source_id " +
374
+ " UNION ALL " +
375
+ " SELECT target_id AS id, COUNT(*) AS cnt FROM edges GROUP BY target_id" +
376
+ " ) GROUP BY id" +
377
+ " HAVING SUM(cnt) > 0" +
378
+ "), ranked AS (" +
379
+ " SELECT d.id, SUM(d.cnt) AS deg FROM deg d GROUP BY d.id ORDER BY deg DESC LIMIT 50" +
380
+ ") " +
381
+ "SELECT n.name, n.label, n.file_path, r.deg " +
382
+ "FROM ranked r JOIN nodes n ON n.id = r.id " +
361
383
  "WHERE n.label NOT IN ('Concept') " +
362
384
  "AND n.file_path IS NOT NULL AND n.file_path != '' " +
363
385
  "AND n.file_path NOT LIKE '%/node_modules/%' AND n.file_path NOT LIKE '%node_modules%' " +
364
- "ORDER BY deg DESC LIMIT 12"
386
+ "ORDER BY r.deg DESC LIMIT 12"
365
387
  ).all();
366
388
 
367
389
  // Staleness indicator: compare stored commit hash with current HEAD.
@@ -396,6 +418,7 @@ function injectGodNodesContext(CWD) {
396
418
  return n.name + ' (' + n.label + ', ' + n.deg + ' links)';
397
419
  }).join(', ');
398
420
  console.log('[MONOGRAPH_CONTEXT] ' + nodeCount + ' nodes · ' + edgeCount + ' edges. Key nodes: ' + godStr + staleIndicator);
421
+ console.log('[MONOGRAPH_ACTIVE] Indexed knowledge graph available — prefer monograph_query / monograph_suggest over grep/find for symbol and definition lookups.');
399
422
 
400
423
  // Write god nodes into knowledge/chunks.jsonl so semantic search finds them.
401
424
  var knowledgeDir = path.join(CWD, '.monomind', 'knowledge');
@@ -416,7 +439,10 @@ function injectGodNodesContext(CWD) {
416
439
  try { return JSON.parse(line).id !== 'monograph-god-nodes'; } catch(e) { return true; }
417
440
  });
418
441
  existing.push(godChunk);
419
- fs.writeFileSync(chunksFile, existing.join('\n') + '\n');
442
+ // Atomic write: tmp file + rename to avoid corruption on kill/timeout
443
+ var tmpChunks = chunksFile + '.tmp.' + process.pid;
444
+ fs.writeFileSync(tmpChunks, existing.join('\n') + '\n');
445
+ fs.renameSync(tmpChunks, chunksFile);
420
446
  } catch(e) {}
421
447
  }
422
448
  } catch(e) { /* non-fatal */ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "monomind",
3
- "version": "1.18.12",
3
+ "version": "1.18.13",
4
4
  "description": "Monomind - Enterprise AI agent orchestration for Claude Code. Deploy 60+ specialized agents in coordinated swarms with self-learning, fault-tolerant consensus, vector memory, and MCP integration",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",
@@ -66,6 +66,34 @@ if (!entryPoint) {
66
66
  process.exit(0);
67
67
  }
68
68
 
69
+ // Skip if index is already fresh — don't waste CPU on every session start
70
+ const dbPath = path.join(projectDir, '.monomind', 'monograph.db');
71
+ if (fs.existsSync(dbPath)) {
72
+ try {
73
+ const mod = (() => {
74
+ try { return require(path.join(projectDir, 'packages', '@monomind', 'monograph', 'dist', 'src', 'index.js')); } catch {}
75
+ try { return require('@monoes/monograph'); } catch {}
76
+ return null;
77
+ })();
78
+ if (mod && mod.openDb) {
79
+ const db = mod.openDb(dbPath);
80
+ try {
81
+ const row = db.prepare("SELECT value FROM index_meta WHERE key='last_commit_hash'").get();
82
+ if (row && row.value) {
83
+ const { execSync } = require('child_process');
84
+ const behind = parseInt(execSync('git rev-list --count ' + row.value + '..HEAD 2>/dev/null', {
85
+ cwd: projectDir, encoding: 'utf-8', timeout: 2000
86
+ }).trim(), 10) || 0;
87
+ if (behind === 0) {
88
+ console.log('[graph] index is fresh — skipping rebuild');
89
+ process.exit(0);
90
+ }
91
+ }
92
+ } finally { mod.closeDb(db); }
93
+ }
94
+ } catch { /* can't check — proceed with build */ }
95
+ }
96
+
69
97
  // Skip if another build is already in progress (avoids SQLite BUSY on concurrent init + session-start)
70
98
  const lockPath = path.join(graphDir, 'build.lock');
71
99
  const now = Date.now();
@@ -381,7 +381,7 @@ module.exports = {
381
381
  }
382
382
  } catch (e) { /* ignore */ }
383
383
  }
384
- if (nodeCount > 100) {
384
+ if (nodeCount > 100 && hCtx._isGraphFresh()) {
385
385
  // Pre-resolve top-3 relevant files for the user's prompt — the LLM
386
386
  // sees the answer inline instead of being told to call a tool.
387
387
  // 3 is enough signal; more files inflate token cost on every prompt.
@@ -216,6 +216,7 @@ var hCtx = {
216
216
  _recordToolCall: _recordToolCall,
217
217
  _openMonographDb: _openMonographDb,
218
218
  _requireMonograph: _requireMonograph,
219
+ _isGraphFresh: _isGraphFresh,
219
220
  _triggerExtractYamlValue: _triggerExtractYamlValue,
220
221
  _triggerFinalize: _triggerFinalize,
221
222
  _triggerExtractFromFrontmatter: _triggerExtractFromFrontmatter,
@@ -312,7 +313,8 @@ const handlers = {
312
313
  if (db) {
313
314
  // Stop words: language keywords + generic single-word identifiers
314
315
  // that match Variable nodes in markdown/scripts (not real code symbols)
315
- var _grepStop = {import:1,export:1,from:1,require:1,return:1,function:1,const:1,let:1,var:1,class:1,interface:1,type:1,extends:1,implements:1,async:1,await:1,yield:1,throw:1,catch:1,finally:1,typeof:1,instanceof:1,void:1,null:1,undefined:1,true:1,false:1,this:1,super:1,new:1,delete:1,switch:1,case:1,break:1,continue:1,default:1,else:1,while:1,for:1,with:1,include:1,error:1,string:1,number:1,object:1,boolean:1,array:1,value:1,result:1,data:1,name:1,path:1,file:1,node:1,list:1,item:1,index:1,config:1,options:1,params:1,args:1,event:1,state:1,props:1,context:1,module:1,package:1,version:1,model:1,schema:1,table:1,query:1,response:1,request:1,handler:1,logger:1,graph:1,usage:1,storage:1,pipeline:1,service:1,utils:1,types:1,helpers:1,common:1,shared:1,server:1,client:1,source:1,output:1,input:1,stream:1,buffer:1,worker:1,plugin:1,format:1,render:1,update:1,create:1,remove:1,method:1,define:1,invoke:1,process:1,execute:1,resolve:1,reject:1,promise:1,callback:1,cursor:1,record:1,column:1,filter:1,reduce:1,status:1,action:1,commit:1,revert:1,publish:1,symbol:1,target:1,length:1,string:1,global:1,static:1,struct:1,select:1,insert:1,signal:1,socket:1,system:1,memory:1,parser:1,router:1,docker:1,script:1,bundle:1,deploy:1,search:1,prepare:1};
316
+ // monolean: only JS/TS reserved words — generic identifiers (handler, config, router, etc.) are valid symbol names
317
+ var _grepStop = {import:1,export:1,from:1,require:1,return:1,function:1,const:1,let:1,var:1,class:1,interface:1,type:1,extends:1,implements:1,async:1,await:1,yield:1,throw:1,catch:1,finally:1,typeof:1,instanceof:1,void:1,null:1,undefined:1,true:1,false:1,this:1,super:1,new:1,delete:1,switch:1,case:1,break:1,continue:1,default:1,else:1,while:1,for:1,with:1,static:1,enum:1,string:1,number:1,object:1,boolean:1};
316
318
 
317
319
  // --- Strategy 1: clean identifier → exact name match (case-sensitive) ---
318
320
  if (/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(pattern) && pattern.length >= 4
@@ -479,7 +481,8 @@ const handlers = {
479
481
  var db = _openMonographDb();
480
482
  if (db) {
481
483
  try {
482
- var _searchStop = {import:1,export:1,from:1,require:1,return:1,function:1,const:1,let:1,var:1,class:1,interface:1,type:1,extends:1,implements:1,async:1,await:1,yield:1,throw:1,catch:1,finally:1,typeof:1,instanceof:1,void:1,null:1,undefined:1,true:1,false:1,this:1,super:1,new:1,delete:1,switch:1,case:1,break:1,continue:1,default:1,else:1,while:1,for:1,with:1,include:1,error:1,string:1,number:1,object:1,boolean:1,array:1,value:1,result:1,data:1,name:1,path:1,file:1,node:1,list:1,item:1,index:1,config:1,options:1,params:1,args:1,event:1,state:1,props:1,context:1,module:1,package:1,version:1,model:1,schema:1,table:1,query:1,response:1,request:1,handler:1,logger:1,graph:1,usage:1,storage:1,pipeline:1,service:1,utils:1,types:1,helpers:1,common:1,shared:1,server:1,client:1,source:1,output:1,input:1,stream:1,buffer:1,worker:1,plugin:1,format:1,render:1,update:1,create:1,remove:1,method:1,define:1,invoke:1,process:1,execute:1,resolve:1,reject:1,promise:1,callback:1,cursor:1,record:1,column:1,filter:1,reduce:1,status:1,action:1,commit:1,revert:1,publish:1,symbol:1,target:1,length:1,string:1,global:1,static:1,struct:1,select:1,insert:1,signal:1,socket:1,system:1,memory:1,parser:1,router:1,docker:1,script:1,bundle:1,deploy:1,search:1,prepare:1};
484
+ // monolean: only JS/TS reserved words — generic identifiers are valid symbol names
485
+ var _searchStop = {import:1,export:1,from:1,require:1,return:1,function:1,const:1,let:1,var:1,class:1,interface:1,type:1,extends:1,implements:1,async:1,await:1,yield:1,throw:1,catch:1,finally:1,typeof:1,instanceof:1,void:1,null:1,undefined:1,true:1,false:1,this:1,super:1,new:1,delete:1,switch:1,case:1,break:1,continue:1,default:1,else:1,while:1,for:1,with:1,static:1,enum:1,string:1,number:1,object:1,boolean:1};
483
486
 
484
487
  var isCleanSymbol = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(grepPattern);
485
488
 
@@ -183,19 +183,31 @@ function _getDollarRate() {
183
183
 
184
184
  // Staleness guard — skip graph DB lookups when the index is too far behind HEAD.
185
185
  // Returns true if it's safe to use the graph, false if stale.
186
+ // Uses last_commit_hash from the DB (not file mtime, which drifts from backups/WAL/VACUUM).
186
187
  var _graphFreshnessCache = undefined;
187
188
  function _isGraphFresh() {
188
189
  if (_graphFreshnessCache !== undefined) return _graphFreshnessCache;
189
190
  try {
190
- var dbPath = path.join(CWD, '.monomind', 'monograph.db');
191
- var dbStat = fs.statSync(dbPath);
191
+ var db = _openMonographDb();
192
+ if (!db) { _graphFreshnessCache = true; return true; }
193
+ var row = null;
194
+ try {
195
+ row = db.prepare("SELECT value FROM index_meta WHERE key='last_commit_hash'").get() ||
196
+ db.prepare("SELECT value FROM index_meta WHERE key='lastCommit'").get();
197
+ } catch (_) {}
198
+ if (!row || !row.value) {
199
+ // No commit hash → can't check staleness, but DB may still have useful data
200
+ var nodeCount = 0;
201
+ try { nodeCount = db.prepare('SELECT COUNT(*) AS c FROM nodes').get().c; } catch (_) {}
202
+ _graphFreshnessCache = nodeCount > 0;
203
+ return _graphFreshnessCache;
204
+ }
192
205
  var { execSync } = require('child_process');
193
- var buildIso = new Date(dbStat.mtimeMs).toISOString();
194
- var out = execSync("git rev-list --count --since='" + buildIso + "' HEAD 2>/dev/null", {
206
+ var out = execSync('git rev-list --count ' + row.value + '..HEAD 2>/dev/null', {
195
207
  encoding: 'utf-8', timeout: 1500, stdio: ['pipe', 'pipe', 'pipe']
196
208
  }).trim();
197
209
  var behind = parseInt(out, 10) || 0;
198
- _graphFreshnessCache = behind <= 50; // monolean: 50 commits is generous enough
210
+ _graphFreshnessCache = behind <= 50;
199
211
  } catch(e) {
200
212
  _graphFreshnessCache = true; // can't check → assume fresh
201
213
  }
@@ -354,14 +366,24 @@ function injectGodNodesContext(CWD) {
354
366
  try {
355
367
  var nodeCount = db.prepare('SELECT COUNT(*) AS c FROM nodes').get().c;
356
368
  var edgeCount = db.prepare('SELECT COUNT(*) AS c FROM edges').get().c;
369
+ // Precompute degree via indexed edge lookups to avoid O(N) correlated subquery
357
370
  var godNodes = db.prepare(
358
- "SELECT n.name, n.label, n.file_path, " +
359
- "(SELECT COUNT(*) FROM edges WHERE source_id=n.id OR target_id=n.id) AS deg " +
360
- "FROM nodes n " +
371
+ "WITH deg AS (" +
372
+ " SELECT id, cnt FROM (" +
373
+ " SELECT source_id AS id, COUNT(*) AS cnt FROM edges GROUP BY source_id " +
374
+ " UNION ALL " +
375
+ " SELECT target_id AS id, COUNT(*) AS cnt FROM edges GROUP BY target_id" +
376
+ " ) GROUP BY id" +
377
+ " HAVING SUM(cnt) > 0" +
378
+ "), ranked AS (" +
379
+ " SELECT d.id, SUM(d.cnt) AS deg FROM deg d GROUP BY d.id ORDER BY deg DESC LIMIT 50" +
380
+ ") " +
381
+ "SELECT n.name, n.label, n.file_path, r.deg " +
382
+ "FROM ranked r JOIN nodes n ON n.id = r.id " +
361
383
  "WHERE n.label NOT IN ('Concept') " +
362
384
  "AND n.file_path IS NOT NULL AND n.file_path != '' " +
363
385
  "AND n.file_path NOT LIKE '%/node_modules/%' AND n.file_path NOT LIKE '%node_modules%' " +
364
- "ORDER BY deg DESC LIMIT 12"
386
+ "ORDER BY r.deg DESC LIMIT 12"
365
387
  ).all();
366
388
 
367
389
  // Staleness indicator: compare stored commit hash with current HEAD.
@@ -396,6 +418,7 @@ function injectGodNodesContext(CWD) {
396
418
  return n.name + ' (' + n.label + ', ' + n.deg + ' links)';
397
419
  }).join(', ');
398
420
  console.log('[MONOGRAPH_CONTEXT] ' + nodeCount + ' nodes · ' + edgeCount + ' edges. Key nodes: ' + godStr + staleIndicator);
421
+ console.log('[MONOGRAPH_ACTIVE] Indexed knowledge graph available — prefer monograph_query / monograph_suggest over grep/find for symbol and definition lookups.');
399
422
 
400
423
  // Write god nodes into knowledge/chunks.jsonl so semantic search finds them.
401
424
  var knowledgeDir = path.join(CWD, '.monomind', 'knowledge');
@@ -416,7 +439,10 @@ function injectGodNodesContext(CWD) {
416
439
  try { return JSON.parse(line).id !== 'monograph-god-nodes'; } catch(e) { return true; }
417
440
  });
418
441
  existing.push(godChunk);
419
- fs.writeFileSync(chunksFile, existing.join('\n') + '\n');
442
+ // Atomic write: tmp file + rename to avoid corruption on kill/timeout
443
+ var tmpChunks = chunksFile + '.tmp.' + process.pid;
444
+ fs.writeFileSync(tmpChunks, existing.join('\n') + '\n');
445
+ fs.renameSync(tmpChunks, chunksFile);
420
446
  } catch(e) {}
421
447
  }
422
448
  } catch(e) { /* non-fatal */ }
@@ -131,8 +131,18 @@ const monographHealthTool = {
131
131
  // Fall back to legacy 'lastCommit' for indexes built with older versions.
132
132
  const meta = db.prepare("SELECT value FROM index_meta WHERE key = 'last_commit_hash'").get() ?? db.prepare("SELECT value FROM index_meta WHERE key = 'lastCommit'").get();
133
133
  const lastCommit = meta?.value ?? null;
134
- if (!lastCommit)
134
+ if (!lastCommit) {
135
+ // last_commit_hash can be missing even when the index is populated
136
+ // (e.g. git rev-parse failed during build). Check actual data before
137
+ // claiming "never built".
138
+ const nodeCount = db.prepare('SELECT COUNT(*) AS c FROM nodes').get().c;
139
+ if (nodeCount > 0) {
140
+ const indexedAt = db.prepare("SELECT value FROM index_meta WHERE key = 'indexed_at'").get()?.value;
141
+ return text(`Index is built (${nodeCount} nodes${indexedAt ? `, indexed at ${indexedAt}` : ''}) but no commit hash was recorded — staleness tracking unavailable.\n` +
142
+ 'Run monograph_build to fix commit tracking.');
143
+ }
135
144
  return text('Index has never been built. Run monograph_build first.');
145
+ }
136
146
  if (!/^[0-9a-f]{7,40}$/i.test(lastCommit)) {
137
147
  return text('Index metadata is corrupt: invalid commit SHA. Run monograph_build to re-index.');
138
148
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@monoes/monomindcli",
3
- "version": "1.18.12",
3
+ "version": "1.18.13",
4
4
  "type": "module",
5
5
  "description": "Monomind CLI - Enterprise AI agent orchestration with 60+ specialized agents, swarm coordination, MCP server, self-learning hooks, and vector memory for Claude Code",
6
6
  "main": "dist/src/index.js",