@chemx/starter-kit 26.9.21-8 → 26.9.23-1269

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.
Files changed (130) hide show
  1. package/cli/audit/ast-visitors.js +10 -17
  2. package/cli/audit/autofix.js +17 -2
  3. package/cli/audit/clone-detector.js +64 -0
  4. package/cli/audit/clone-detector.spec.js +46 -0
  5. package/cli/audit/hook-shape-validator.js +312 -0
  6. package/cli/audit/prompts.js +1 -1
  7. package/cli/audit/reporter-clones.js +33 -0
  8. package/cli/audit/reporter-hotspot-graph.js +34 -0
  9. package/cli/audit/rules-registry.js +6 -1
  10. package/cli/audit/rules.js +10 -2
  11. package/cli/audit/rules.spec.js +129 -0
  12. package/cli/audit-stages.spec.js +30 -0
  13. package/cli/audit.js +12 -3
  14. package/cli/commands/cmd-audit.js +43 -3
  15. package/cli/commands/cmd-project.js +100 -0
  16. package/cli/commands/cmd-router.js +34 -2
  17. package/cli/commands-schema.js +14 -0
  18. package/cli/create.spec.js +2 -2
  19. package/cli/exploder.js +258 -0
  20. package/cli/exploder.spec.js +99 -0
  21. package/cli/generator-compact.spec.js +104 -0
  22. package/cli/generator-framework.spec.js +72 -0
  23. package/cli/generator-templates/archetypes/collection-archetypes.js +9 -9
  24. package/cli/generator-templates/archetypes/index.js +34 -4
  25. package/cli/generator-templates/archetypes/input-archetypes.js +2 -2
  26. package/cli/generator-templates/archetypes/layout-archetypes.js +2 -2
  27. package/cli/generator-templates/archetypes/minimal-archetypes.js +131 -0
  28. package/cli/generator-templates/archetypes/status-archetypes.js +4 -4
  29. package/cli/generator-templates/archetypes/vector-matcher.js +50 -0
  30. package/cli/generator-templates/archetypes/vector-matcher.spec.js +25 -0
  31. package/cli/generator-templates/compact.js +130 -0
  32. package/cli/generator-templates/controller-converters.js +93 -0
  33. package/cli/generator-templates/controller.js +2 -64
  34. package/cli/generator-templates/react.js +1 -1
  35. package/cli/generator-templates/svelte.js +1 -1
  36. package/cli/generator-templates/types.js +2 -2
  37. package/cli/generator-templates/vue.js +1 -1
  38. package/cli/generator-templates.js +1 -0
  39. package/cli/generator-templates.spec.js +6 -1
  40. package/cli/generator.js +94 -7
  41. package/cli/help.js +1 -1
  42. package/cli/index.js +21 -8
  43. package/cli/installer-templates.js +1 -1
  44. package/cli/mcp/antigravity.js +3 -2
  45. package/cli/mcp/installer.js +7 -7
  46. package/cli/mcp/installer.spec.js +3 -3
  47. package/cli/mcp/manifests.js +3 -2
  48. package/cli/mcp/prompts.js +1 -1
  49. package/cli/mcp/server.js +2 -0
  50. package/cli/mcp/tools-audit.js +95 -0
  51. package/cli/mcp/tools-generate.js +62 -0
  52. package/cli/mcp/tools-patch.js +72 -0
  53. package/cli/mcp/tools-patterns.js +71 -0
  54. package/cli/mcp/tools-project.js +75 -0
  55. package/cli/mcp/tools-project.spec.js +51 -0
  56. package/cli/mcp/tools-q-modes.js +69 -0
  57. package/cli/mcp/tools-q.js +58 -0
  58. package/cli/mcp/tools-read.js +69 -0
  59. package/cli/mcp/tools-search-util.js +35 -0
  60. package/cli/mcp/tools-search.js +15 -294
  61. package/cli/mcp/tools-team-feed.js +57 -0
  62. package/cli/mcp/tools-team-locks.js +63 -0
  63. package/cli/mcp/tools-team-mailbox.js +32 -0
  64. package/cli/mcp/tools-team-tasks.js +84 -0
  65. package/cli/mcp/tools-team.js +37 -183
  66. package/cli/mcp/tools-verify.js +47 -0
  67. package/cli/mcp/tools-write.js +33 -0
  68. package/cli/mcp/tools.js +72 -376
  69. package/cli/mutators.js +10 -23
  70. package/cli/pillars-schema.js +3 -3
  71. package/cli/project-detector.js +47 -0
  72. package/cli/reader-shorthand.spec.js +60 -0
  73. package/cli/reader.js +67 -24
  74. package/cli/search-bulletproof.spec.js +104 -0
  75. package/cli/search-db.js +33 -5
  76. package/cli/search-queries-hotspot-graph.js +65 -0
  77. package/cli/search-queries-hotspot-graph.spec.js +66 -0
  78. package/cli/search-queries-similar.js +84 -0
  79. package/cli/search-queries-similar.spec.js +43 -0
  80. package/cli/search-schema.js +30 -10
  81. package/cli/search.js +9 -2
  82. package/cli/team/index.js +9 -0
  83. package/cli/team/team-commands.js +104 -64
  84. package/cli/team/team-concurrency-stress.spec.js +95 -0
  85. package/cli/team/team-db-mailbox.js +86 -0
  86. package/cli/team/team-db-task-helpers.js +30 -28
  87. package/cli/team/team-db-tasks.js +13 -5
  88. package/cli/team/team-flags.js +69 -0
  89. package/cli/team/team-format.js +87 -46
  90. package/cli/team/team-mailbox-empirical.spec.js +191 -0
  91. package/cli/team/team-mailbox.spec.js +93 -0
  92. package/cli/team/team-memory.js +84 -0
  93. package/cli/team/team-memory.spec.js +74 -0
  94. package/cli/team/team-projects-coordinator.js +100 -0
  95. package/cli/team/team-projects-format.js +45 -0
  96. package/cli/team/team-projects-memory.js +70 -0
  97. package/cli/team/team-projects.js +94 -0
  98. package/cli/team/team-projects.spec.js +116 -0
  99. package/cli/team/team-schema-memory.js +25 -0
  100. package/cli/team/team-schema-projects.js +50 -0
  101. package/cli/team/team-schema.js +33 -14
  102. package/cli/team/team-tasks-hierarchy.spec.js +80 -0
  103. package/cli/team/team-tokens.js +95 -0
  104. package/cli/team/team-triage.js +159 -12
  105. package/cli/team/team-verification-gate.spec.js +253 -0
  106. package/cli/team/team.spec.js +1 -1
  107. package/cli/trend.js +84 -0
  108. package/cli/trend.spec.js +51 -0
  109. package/cli/ui-actions-tasks.js +13 -5
  110. package/cli/ui-actions.js +10 -2
  111. package/cli/ui-client-api.js +2 -2
  112. package/cli/ui-client-script.js +12 -15
  113. package/cli/ui-e2e-verification.spec.js +13 -3
  114. package/cli/ui-filetree.spec.js +5 -5
  115. package/cli/ui-handlers.js +10 -2
  116. package/cli/ui-html.js +26 -34
  117. package/cli/ui-index.html +905 -0
  118. package/cli/ui-kanban.spec.js +12 -12
  119. package/cli/ui-server.js +7 -0
  120. package/cli/ui-sse.js +57 -0
  121. package/cli/ui-sse.spec.js +74 -0
  122. package/cli/ui-styles.js +195 -81
  123. package/cli/ui-template-kanban.js +15 -1
  124. package/cli/ui-vbulletin.spec.js +12 -13
  125. package/cli/ui.spec.js +12 -5
  126. package/cli/verify.js +19 -8
  127. package/package.json +3 -1
  128. package/scripts/check-framework-generation.mjs +195 -0
  129. package/scripts/pre-commit.sh +2 -7
  130. package/scripts/publish-both.mjs +4 -0
@@ -0,0 +1,72 @@
1
+ import path from 'node:path';
2
+ import { syncSingleFileIndex } from '../search.js';
3
+ import { patchFile } from '../patcher.js';
4
+ import { handleCheckCommand } from '../search-commands.js';
5
+
6
+ export const isSevereViolation = (v) => {
7
+ const isCritical = v.severity === 'CRITICAL';
8
+ const isHigh = v.severity === 'HIGH';
9
+ return isCritical || isHigh;
10
+ };
11
+
12
+ export const formatPatchWarnings = (result) => {
13
+ const warnings = [];
14
+ const hasLineBudget = Boolean(result.lineBudget);
15
+ const isBudgetExceeded = hasLineBudget && !result.lineBudget.passed;
16
+ if (isBudgetExceeded) {
17
+ warnings.push(`[Directive 1.A] ${result.lineBudget.warning}`);
18
+ }
19
+
20
+ const violations = result.violations || [];
21
+ for (const v of violations) {
22
+ if (isSevereViolation(v)) {
23
+ warnings.push(`[${v.severity} - ${v.rule}] Line ${v.line}: ${v.hazard} -> ${v.directive || ''}`);
24
+ }
25
+ }
26
+
27
+ return warnings.length > 0 ? warnings : undefined;
28
+ };
29
+
30
+ export const handleChemxPatch = (args = {}, cwd = process.cwd()) => {
31
+ const hasPath = Boolean(args.path);
32
+ const hasTargetContent = args.targetContent !== undefined;
33
+ const hasReplacementContent = args.replacementContent !== undefined;
34
+ const hasRequiredArgs = hasPath && hasTargetContent && hasReplacementContent;
35
+
36
+ if (!hasRequiredArgs) {
37
+ throw new Error('chemx_patch requires "path", "targetContent", and "replacementContent" arguments.');
38
+ }
39
+
40
+ const targetPath = path.isAbsolute(args.path) ? args.path : path.resolve(cwd, args.path);
41
+ const result = patchFile(targetPath, {
42
+ targetContent: args.targetContent,
43
+ replacementContent: args.replacementContent,
44
+ allowMultiple: Boolean(args.allowMultiple),
45
+ cwd
46
+ });
47
+
48
+ try {
49
+ syncSingleFileIndex(targetPath, cwd);
50
+ } catch (err) {
51
+ if (process.env.CHEMX_DEBUG) {
52
+ process.stderr.write(`[patch-sync] Auto-index skipped for ${targetPath}: ${err.message}\n`);
53
+ }
54
+ }
55
+
56
+ return {
57
+ ...result,
58
+ warnings: formatPatchWarnings(result)
59
+ };
60
+ };
61
+
62
+ export const handleChemxCheck = (args = {}, cwd = process.cwd()) => {
63
+ if (args.path === 'RESTART_MCP') {
64
+ setTimeout(() => process.exit(0), 50);
65
+ return { restarting: true };
66
+ }
67
+ if (!args.path) {
68
+ throw new Error('chemx_check requires "path" argument.');
69
+ }
70
+ const targetPath = path.isAbsolute(args.path) ? args.path : path.resolve(cwd, args.path);
71
+ return handleCheckCommand(targetPath, { isJson: true, isCli: false });
72
+ };
@@ -0,0 +1,71 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { runAudit as executeAstAudit } from '../audit.js';
4
+ import { runAutofix } from '../audit/autofix.js';
5
+ import { resolveTargetCwd } from './tools-search.js';
6
+
7
+ export const handleQueryPatterns = (args = {}, cwd = process.cwd()) => {
8
+ const baseCwd = resolveTargetCwd(cwd);
9
+ const targetDir = args.dir || (fs.existsSync(path.resolve(baseCwd, 'src')) ? 'src' : '.');
10
+ const resolvedTarget = path.isAbsolute(targetDir) ? targetDir : path.resolve(baseCwd, targetDir);
11
+ const report = executeAstAudit(resolvedTarget, { cwd: baseCwd });
12
+ const rawPatterns = report.patterns || [];
13
+ const filterType = args.type || 'ALL';
14
+ const minOccurrences = typeof args.minOccurrences === 'number' ? args.minOccurrences : 2;
15
+ const isCompact = args.compact !== false;
16
+
17
+ const matchesType = (p) => filterType === 'ALL' || p.type === filterType;
18
+ const matchesCount = (p) => p.fileCount >= minOccurrences;
19
+
20
+ const candidates = rawPatterns
21
+ .filter((p) => matchesType(p) && matchesCount(p))
22
+ .map((p) => {
23
+ const base = {
24
+ id: p.id,
25
+ type: p.type,
26
+ label: p.label,
27
+ detail: p.detail,
28
+ suggestedCapsule: p.suggestedCapsule,
29
+ recommendation: p.recommendation,
30
+ fileCount: p.fileCount,
31
+ totalHits: p.totalHits,
32
+ impactScore: p.impactScore
33
+ };
34
+
35
+ if (isCompact) {
36
+ const sampleOccurrences = [];
37
+ const seenSampleFiles = new Set();
38
+ for (const occ of (p.occurrences || [])) {
39
+ if (!seenSampleFiles.has(occ.filePath)) {
40
+ seenSampleFiles.add(occ.filePath);
41
+ sampleOccurrences.push({ file: occ.filePath, line: occ.line });
42
+ if (sampleOccurrences.length >= 3) break;
43
+ }
44
+ }
45
+ return {
46
+ ...base,
47
+ files: p.uniqueFiles || Array.from(new Set((p.occurrences || []).map((o) => o.filePath))),
48
+ sampleOccurrences
49
+ };
50
+ }
51
+ return { ...base, occurrences: p.occurrences };
52
+ });
53
+
54
+ return {
55
+ scannedDir: targetDir,
56
+ totalCandidates: candidates.length,
57
+ compact: isCompact,
58
+ candidates
59
+ };
60
+ };
61
+
62
+ export const handleAutofix = (args = {}, cwd = process.cwd()) => {
63
+ const baseCwd = resolveTargetCwd(cwd);
64
+ const rawTarget = args.path || args.dir || (fs.existsSync(path.resolve(baseCwd, 'src')) ? 'src' : '.');
65
+ const targetDir = path.isAbsolute(rawTarget) ? rawTarget : path.resolve(baseCwd, rawTarget);
66
+ return runAutofix(targetDir, {
67
+ dryRun: Boolean(args.dryRun),
68
+ rules: args.rules,
69
+ cwd: baseCwd
70
+ });
71
+ };
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Chemical X Protocol: MCP Project & Coordinator Tools
3
+ * Exposes persistent coordinator lifecycle, step execution, and memory via MCP
4
+ */
5
+
6
+ import { openIndexDb } from '../search-db.js';
7
+ import {
8
+ initProjectSession,
9
+ getActiveProjectSession,
10
+ postProjectMessage,
11
+ getProjectMessages,
12
+ updateProjectSession
13
+ } from '../team/team-projects.js';
14
+ import { queryRelevantLearnings } from '../team/team-projects-memory.js';
15
+ import { executeCoordinatorStep } from '../team/team-projects-coordinator.js';
16
+ import { listTasks } from '../team/team-db-tasks.js';
17
+
18
+ export const handleChemxProject = async (args = {}, cwd = process.cwd()) => {
19
+ const db = openIndexDb(cwd);
20
+ if (!db) {
21
+ return { error: 'SQLite database unavailable' };
22
+ }
23
+
24
+ const subAction = args.subAction || args.action || 'status';
25
+
26
+ const isInit = subAction === 'init' || subAction === 'start';
27
+ if (isInit) {
28
+ const goal = args.goal || args.title || 'Autonomous codebase optimization';
29
+ return initProjectSession(db, {
30
+ goal,
31
+ title: (args.title || goal).slice(0, 40),
32
+ budgetLimit: args.budgetLimit || 2.0,
33
+ maxTurns: args.maxTurns || 10
34
+ });
35
+ }
36
+
37
+ const isStep = subAction === 'step' || subAction === 'turn';
38
+ if (isStep) {
39
+ return executeCoordinatorStep(db, { cwd, costUsd: args.costUsd });
40
+ }
41
+
42
+ const isChat = subAction === 'chat' || subAction === 'msg';
43
+ if (isChat) {
44
+ const active = getActiveProjectSession(db);
45
+ if (!active) return { error: 'no_active_session' };
46
+ return postProjectMessage(db, {
47
+ projectId: active.id,
48
+ turnIndex: active.current_turn,
49
+ authorId: args.as || '@user',
50
+ role: 'user',
51
+ message: args.message || 'Status check'
52
+ });
53
+ }
54
+
55
+ const isLearnings = subAction === 'learnings' || subAction === 'memory';
56
+ if (isLearnings) {
57
+ return queryRelevantLearnings(db, { tier: args.tier, limit: args.limit || 10 });
58
+ }
59
+
60
+ const isPauseToggle = subAction === 'pause' || subAction === 'resume';
61
+ if (isPauseToggle) {
62
+ const active = getActiveProjectSession(db);
63
+ if (!active) return { error: 'no_active_session' };
64
+ const status = subAction === 'pause' ? 'paused' : 'active';
65
+ return updateProjectSession(db, active.id, { status });
66
+ }
67
+
68
+ // Default: status
69
+ const session = getActiveProjectSession(db);
70
+ const messages = session ? getProjectMessages(db, session.id, 5) : [];
71
+ const activeTasks = session ? listTasks(db, { status: 'in_progress' }) : [];
72
+ const learnings = queryRelevantLearnings(db, { limit: 5 });
73
+
74
+ return { session, messages, activeTasks, learnings };
75
+ };
@@ -0,0 +1,51 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert';
3
+ import { DatabaseSync } from 'node:sqlite';
4
+ import { initTeamSchema } from '../team/team-schema.js';
5
+ import { handleChemxProject } from './tools-project.js';
6
+ import { handleChemx } from './tools.js';
7
+
8
+ test('mcp-tools: handleChemxProject lifecycle operations', async () => {
9
+ const session = await handleChemxProject({
10
+ subAction: 'init',
11
+ goal: 'Test project through MCP gateway',
12
+ budgetLimit: 1.0,
13
+ maxTurns: 5
14
+ });
15
+
16
+ assert.ok(session);
17
+ assert.equal(session.goal_description, 'Test project through MCP gateway');
18
+
19
+ const chatRes = await handleChemxProject({
20
+ subAction: 'chat',
21
+ message: 'Focus on atom decomposition first'
22
+ });
23
+ assert.ok(chatRes);
24
+ assert.equal(chatRes.message, 'Focus on atom decomposition first');
25
+
26
+ const stepRes = await handleChemxProject({
27
+ subAction: 'step'
28
+ });
29
+ assert.ok(stepRes);
30
+ assert.equal(stepRes.status, 'ok');
31
+ assert.equal(stepRes.turn, 1);
32
+
33
+ const statusRes = await handleChemxProject({
34
+ subAction: 'status'
35
+ });
36
+ assert.ok(statusRes.session);
37
+ assert.equal(statusRes.session.current_turn, 1);
38
+ });
39
+
40
+ test('mcp-tools: master tool chemx command parser routes project', async () => {
41
+ const initRes = await handleChemx({
42
+ command: 'project init "Master Gateway Initiative"'
43
+ });
44
+ assert.ok(initRes);
45
+ assert.equal(initRes.title, 'Master Gateway Initiative');
46
+
47
+ const statusRes = await handleChemx({
48
+ command: 'project status'
49
+ });
50
+ assert.ok(statusRes.session);
51
+ });
@@ -0,0 +1,69 @@
1
+ import {
2
+ findSymbolDefinition, findSymbolReferences, findFileDependencies,
3
+ findFileDependents, calculateBlastRadius, querySemanticIndex, queryHybridIndex
4
+ } from '../search-queries.js';
5
+ import { toColumnar } from '../columnar.js';
6
+
7
+ export const executeBlastRadiusQuery = (activeDb, query, args = {}) => {
8
+ const blast = calculateBlastRadius(activeDb, query, { maxDepth: args.maxDepth || 5 });
9
+ const allConsumers = [...blast.directConsumers, ...blast.transitiveConsumers];
10
+ const col = toColumnar(allConsumers, ['path', 'tier', 'depth']);
11
+ return {
12
+ target: blast.target, seed: blast.seedPath, count: blast.totalImpactCount,
13
+ depth: blast.depth, tiers: blast.tiers, format: 'columnar',
14
+ cols: col.cols, rows: col.rows, tests: blast.impactedTests.map((t) => t.path || t)
15
+ };
16
+ };
17
+
18
+ export const executeSemanticQuery = (activeDb, query, args = {}) => {
19
+ const results = querySemanticIndex(activeDb, query, { limit: args.limit || 20, tier: args.tier });
20
+ const col = toColumnar(results, ['filePath', 'targetType', 'targetName', 'tier', 'similarity']);
21
+ return { query, mode: 'semantic', count: results.length, format: 'columnar', cols: col.cols, rows: col.rows };
22
+ };
23
+
24
+ export const executeHybridQuery = (activeDb, query, args = {}) => {
25
+ const results = queryHybridIndex(activeDb, query, { limit: args.limit || 20 });
26
+ const col = toColumnar(results, ['filePath', 'name', 'tier', 'score', 'ftsRank', 'vecRank']);
27
+ return { query, mode: 'hybrid (BM25 + Vector RRF)', count: results.length, format: 'columnar', cols: col.cols, rows: col.rows };
28
+ };
29
+
30
+ export const executeConnectionsQuery = (activeDb, query) => {
31
+ const symDef = findSymbolDefinition(activeDb, query);
32
+ if (symDef) {
33
+ const deps = findFileDependencies(activeDb, symDef.filePath);
34
+ const symRefs = findSymbolReferences(activeDb, query);
35
+ const blast = calculateBlastRadius(activeDb, symDef.name);
36
+ return {
37
+ symbol: symDef.name, kind: symDef.kind, filePath: symDef.filePath,
38
+ lines: `${symDef.startLine}-${symDef.endLine}`, signature: symDef.signature,
39
+ dependencies: deps.map((d) => `${d.sourceModule}: ${d.importedSymbol}`),
40
+ consumers: symRefs.map((r) => `${r.importerPath}:${r.line}`),
41
+ blastRadius: { totalImpactCount: blast.totalImpactCount, impactedTests: blast.impactedTests.map((t) => t.path) }
42
+ };
43
+ }
44
+ const deps = findFileDependencies(activeDb, query);
45
+ const dependents = findFileDependents(activeDb, query);
46
+ if (deps.length > 0 || dependents.length > 0) {
47
+ const blast = calculateBlastRadius(activeDb, query);
48
+ return {
49
+ file: query,
50
+ dependencies: deps.map((d) => `${d.sourceModule}: ${d.importedSymbol}`),
51
+ dependents: dependents.map((d) => `${d.importerPath}:${d.line}`),
52
+ blastRadius: { totalImpactCount: blast.totalImpactCount, impactedTests: blast.impactedTests.map((t) => t.path) }
53
+ };
54
+ }
55
+ return null;
56
+ };
57
+
58
+ export const executeFtsFallback = (activeDb, query) => {
59
+ try {
60
+ const clean = query.replace(/[^\w\s-]/g, ' ').trim();
61
+ if (clean) {
62
+ const rows = activeDb.prepare('SELECT file_path, name, tier FROM fts_index WHERE fts_index MATCH ? LIMIT 10').all(`"${clean}"*`);
63
+ if (rows.length > 0) return rows.map((r) => `[FTS MATCH] ${r.file_path} (${r.name || r.tier})`).join('\n');
64
+ }
65
+ } catch (err) {
66
+ if (process.env.CHEMX_DEBUG) process.stderr.write(`[fts-fallback] Search failed for ${query}: ${err.message}\n`);
67
+ }
68
+ return null;
69
+ };
@@ -0,0 +1,58 @@
1
+ import { syncSearchIndex } from '../search.js';
2
+ import { openIndexDb, queryIndex } from '../search-db.js';
3
+ import { toColumnar } from '../columnar.js';
4
+ import { resolveTargetCwd } from './tools-search-util.js';
5
+ import {
6
+ executeBlastRadiusQuery, executeSemanticQuery,
7
+ executeHybridQuery, executeConnectionsQuery, executeFtsFallback
8
+ } from './tools-q-modes.js';
9
+
10
+ export const handleChemxQ = (args = {}, cwd = process.cwd()) => {
11
+ const targetCwd = resolveTargetCwd(args.cwd || cwd);
12
+ const query = args.query || args.symbol;
13
+ if (!query) throw new Error('chemx_q requires "query" or "symbol" argument.');
14
+ const db = openIndexDb(targetCwd);
15
+ if (!db) syncSearchIndex('src', targetCwd);
16
+ const activeDb = openIndexDb(targetCwd);
17
+ if (!activeDb) throw new Error('Unable to initialize Chemical X AST search index database.');
18
+
19
+ if (args.blastRadius || args.impact) return executeBlastRadiusQuery(activeDb, query, args);
20
+ if (args.semantic) return executeSemanticQuery(activeDb, query, args);
21
+ if (args.hybrid) return executeHybridQuery(activeDb, query, args);
22
+
23
+ if (args.connections || args.symbol) {
24
+ const conn = executeConnectionsQuery(activeDb, query);
25
+ if (conn) return conn;
26
+ }
27
+
28
+ const limit = typeof args.limit === 'number' ? args.limit : 20;
29
+ const results = queryIndex(activeDb, { query, tier: args.tier || 'all', limit });
30
+
31
+ if (args.columnar) {
32
+ return toColumnar(results, ['path', 'tier', 'lines', 'symbols', 'props', 'hooks'], {
33
+ symbols: (r) => (r.symbols || []).map((s) => s.name),
34
+ props: (r) => (r.props || []).map((p) => p.name),
35
+ hooks: (r) => r.hooks || []
36
+ });
37
+ }
38
+
39
+ if (args.inspect) {
40
+ return results.map((r) => ({
41
+ path: r.path, tier: r.tier, lines: r.lines,
42
+ symbols: (r.symbols || []).map((s) => s.name),
43
+ props: (r.props || []).map((p) => p.name),
44
+ hooks: r.hooks || []
45
+ }));
46
+ }
47
+
48
+ const lines = results.map((r) => {
49
+ const mainSym = (r.symbols || []).find((s) => s.isExport)?.name || '';
50
+ const symPart = mainSym ? ` (${mainSym})` : '';
51
+ const hookPart = r.hooks && r.hooks.length > 0 ? ` [${r.hooks.slice(0, 2).join(',')}]` : '';
52
+ return `[${r.tier.toUpperCase()}] ${r.path}:${r.lines}L${symPart}${hookPart}`;
53
+ });
54
+
55
+ if (lines.length > 0) return lines.join('\n');
56
+ const fts = executeFtsFallback(activeDb, query);
57
+ return fts || `No matching capsules or symbols for "${query}"`;
58
+ };
@@ -0,0 +1,69 @@
1
+ import path from 'node:path';
2
+ import { openIndexDb } from '../search-db.js';
3
+ import {
4
+ findSymbolReferences, findFileDependencies, findFileDependents, calculateBlastRadius
5
+ } from '../search-queries.js';
6
+ import { findSimilarSymbols } from '../search-queries-similar.js';
7
+ import { readTokenOptimized } from '../reader.js';
8
+ import { EXT_LANG_MAP, resolveTargetCwd } from './tools-search-util.js';
9
+
10
+ const buildConnectionCard = (db, symbol, targetPath) => {
11
+ const blast = calculateBlastRadius(db, symbol || targetPath);
12
+ if (symbol) {
13
+ const refs = findSymbolReferences(db, symbol);
14
+ const similar = findSimilarSymbols(db, symbol, 3);
15
+ const simSuffix = similar.length > 0
16
+ ? ` Similar symbols: ${similar.map((s) => `${s.name} (${Math.round(s.similarity * 100)}%)`).join(', ')}.`
17
+ : '';
18
+ return `\n// Connections for ${symbol}: referenced by ${refs.length} file(s) [${refs.slice(0, 3).map((r) => path.basename(r.importerPath)).join(', ')}]. Blast Radius: ${blast.totalImpactCount} affected file(s) across ${blast.depth} hops (${blast.impactedTests.length} tests).${simSuffix}`;
19
+ }
20
+ const deps = findFileDependencies(db, targetPath);
21
+ const dependents = findFileDependents(db, targetPath);
22
+ return `\n// File Connections: imports ${deps.length} symbol(s), imported by ${dependents.length} file(s). Blast Radius: ${blast.totalImpactCount} affected file(s) across ${blast.depth} hops (${blast.impactedTests.length} tests).`;
23
+ };
24
+
25
+ const buildContextEnvelope = (db, targetPath) => {
26
+ try {
27
+ const fileImports = findFileDependencies(db, targetPath);
28
+ if (fileImports.length > 0) {
29
+ const topImports = fileImports.slice(0, 5).map((i) => i.importedSymbol).filter(Boolean);
30
+ if (topImports.length > 0) return `// Context: module imports [${topImports.join(', ')}]\n`;
31
+ }
32
+ } catch (err) {
33
+ if (process.env.CHEMX_DEBUG) process.stderr.write(`[context-envelope] Failed for ${targetPath}: ${err.message}\n`);
34
+ }
35
+ return '';
36
+ };
37
+
38
+ export const handleChemxRead = (args = {}, cwd = process.cwd()) => {
39
+ if (!args.path) throw new Error('chemx_read requires "path" argument.');
40
+ const targetCwd = resolveTargetCwd(args.cwd || cwd);
41
+ let rawPath = args.path;
42
+ let startLine = args.startLine;
43
+ let endLine = args.endLine;
44
+
45
+ const colonMatch = typeof rawPath === 'string' && rawPath.match(/^([^:]+):(\d+)(?:[-:](\d+))?$/);
46
+ if (colonMatch) {
47
+ rawPath = colonMatch[1];
48
+ if (startLine === undefined) startLine = parseInt(colonMatch[2], 10);
49
+ if (endLine === undefined && colonMatch[3]) endLine = parseInt(colonMatch[3], 10);
50
+ }
51
+
52
+ const targetPath = path.isAbsolute(rawPath) ? rawPath : path.resolve(targetCwd, rawPath);
53
+ const res = readTokenOptimized(targetPath, {
54
+ outline: args.outline, symbol: args.symbol,
55
+ stripComments: args.stripComments !== false, compact: args.compact !== false,
56
+ startLine, endLine
57
+ });
58
+
59
+ const db = (args.connections || args.symbol) ? openIndexDb(targetCwd) : null;
60
+ const connectionCard = (args.connections && db) ? buildConnectionCard(db, args.symbol, targetPath) : '';
61
+ const contextEnvelope = (args.symbol && db) ? buildContextEnvelope(db, targetPath) : '';
62
+
63
+ const ext = path.extname(targetPath).toLowerCase();
64
+ const lang = EXT_LANG_MAP[ext] || '';
65
+ const fence = res.content.includes('```') ? '~~~' : '```';
66
+ const fenced = `${fence}${lang}\n${res.content}\n${fence}`;
67
+ const header = `// ${res.file} (${res.lineCount || res.totalLines} lines, ~${res.tokensEst} tokens)${connectionCard}\n`;
68
+ return header + contextEnvelope + fenced;
69
+ };
@@ -0,0 +1,35 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ export const PROJECT_ROOT = path.resolve(path.dirname(new URL(import.meta.url).pathname), '../..');
5
+
6
+ export const EXT_LANG_MAP = {
7
+ '.js': 'javascript',
8
+ '.mjs': 'javascript',
9
+ '.cjs': 'javascript',
10
+ '.ts': 'typescript',
11
+ '.mts': 'typescript',
12
+ '.cts': 'typescript',
13
+ '.vue': 'vue',
14
+ '.json': 'json',
15
+ '.scss': 'scss',
16
+ '.css': 'css',
17
+ '.html': 'html',
18
+ '.md': 'markdown',
19
+ '.yaml': 'yaml',
20
+ '.yml': 'yaml',
21
+ '.sh': 'bash',
22
+ '.bash': 'bash',
23
+ '.sql': 'sql'
24
+ };
25
+
26
+ export const resolveTargetCwd = (cwd) => {
27
+ const hasCwd = Boolean(cwd);
28
+ const isUserHome = cwd === '/home/xopher';
29
+ const hasPackageJson = hasCwd && fs.existsSync(path.resolve(cwd, 'package.json'));
30
+ const isValidProjectCwd = hasCwd && !isUserHome && hasPackageJson;
31
+ if (!isValidProjectCwd) {
32
+ return PROJECT_ROOT;
33
+ }
34
+ return cwd;
35
+ };