13 changed files with 1777 additions and 239 deletions

No files matched your search

+23
View File
@@ -0,0 +1,23 @@
# NPM Ignore
.git
.github
.gitignore
.DS_Store
.env*
test/
tests/
examples/
scripts/
docs/
mcp/
AI.md
*.log
coverage/
node_modules/
# Keep bin and library code
!bin/
!package.json
!README.md
!LICENSE
!CHANGELOG.md
+42
View File
@@ -132,6 +132,7 @@ GIMS now uses the **[S4 Versioning System](https://github.com/s41r4j/s4vs)**, a
| `g v major` | Force major bump (`1.0.0` → `2.0.0`) |
| `g v --list` | List stable releases (hides dev tags) |
| `g v --prune` | Delete old `dev` tags (keeps last 10) |
| `g v --undo` | Undo last version bump (delete latest tag) |
| `g v -i` | Version analysis with timestamp |
| `g whoami` | Dynamic identity & version banner |
@@ -149,6 +150,47 @@ GIMS now uses the **[S4 Versioning System](https://github.com/s41r4j/s4vs)**, a
---
## 🤖 AI-Native Integration (New)
GIMS is designed to be "AI-Native", allowing AI agents to directly understand and control your git repository.
### 1. Model Context Protocol (MCP) Server
GIMS includes a built-in [MCP](https://modelcontextprotocol.io/) server. This allows AI assistants like **Claude Desktop**, **Cursor**, and **VS Code** to directly "see" and "use" GIMS tools.
#### Available Tools
- `get_status`: Get AI-enhanced git status and insights.
- `analyze_history`: Analyze commit history and patterns.
- `version_info`: Get current S4 version details.
- `generate_commit_message`: Generate a commit message for staged changes.
- `run_git_command`: Safe execution of raw git commands.
#### Usage with Claude Desktop
Add to your `claude_desktop_config.json`:
```json
{
"mcpServers": {
"gims": {
"command": "node",
"args": ["/path/to/gims/mcp/index.js"]
}
}
}
```
### 2. OpenAI / Custom Agent Integration
If you are building your own AI agent (using OpenAI, LangChain, etc.), you can plug GIMS tools directly into your `tools` array using our auto-generated schemas.
**Schema Location:** `bin/tools-schema.json`
```javascript
const tools = require('gims/bin/tools-schema.json');
// Pass 'tools' directly to OpenAI API
```
---
## 🤖 AI Providers
GIMS supports multiple AI providers. Choose based on your needs:
+307 -141
View File
@@ -128,6 +128,24 @@ async function confirmCommit(message, isLocalHeuristic) {
});
}
function askQuestion(promptText) {
const readline = require('readline');
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
return new Promise(resolve => {
rl.question(promptText, answer => {
rl.close();
resolve(answer.trim());
});
});
}
async function confirmPrompt(message, defaultYes = true) {
const suffix = defaultYes ? '[Y/n]' : '[y/N]';
const answer = (await askQuestion(`${message} ${suffix}: `)).toLowerCase();
if (answer === '') return defaultYes;
return answer === 'y' || answer === 'yes';
}
async function resolveCommit(input) {
if (/^\d+$/.test(input)) {
const { all } = await safeLog();
@@ -145,6 +163,25 @@ async function hasChanges() {
return status.files.length > 0;
}
// Returns staged diff string, auto-staging as needed, or null when nothing to commit.
async function getStagedDiff(opts) {
if (!(await hasChanges()) && !opts.all) return null;
if (opts.all) {
Progress.info('Staging all changes...');
await git.add('.');
}
let diff = await git.diff(['--cached', '--no-ext-diff']);
if (!diff.trim()) {
Progress.info('No staged changes found; staging all changes...');
await git.add('.');
diff = await git.diff(['--cached', '--no-ext-diff']);
}
return diff.trim() ? diff : null;
}
program
.name('gims')
.alias('g')
@@ -332,38 +369,96 @@ program.command('config')
}
});
program.command('quick-help').alias('q')
.description('Show quick reference for main commands')
program.command('help', { isDefault: true })
.description('Show structured help menu')
.action(() => {
console.log(color.bold('🚀 GIMS Quick Reference\n'));
console.log(color.bold('\n🚀 GIMS - Git Made Simple\n'));
console.log(color.bold('Core Workflow:'));
console.log(` ${color.cyan('g s')} Status with AI insights`);
console.log(` ${color.cyan('g o')} AI commit + push`);
console.log(` ${color.cyan('g l')} AI commit locally`);
console.log(` ${color.cyan('g wip')} Quick WIP commit\n`);
const sections = [
{
title: '🤖 AI & Core Workflow',
cmds: [
{ name: 'g s | status', desc: 'Status with AI insights' },
{ name: 'g o | online', desc: 'Auto-stage + AI commit + Push' },
{ name: 'g l | local', desc: 'Auto-stage + AI commit (local)' },
{ name: 'g r | review', desc: 'AI Code Review detected changes' },
{ name: 'g sg | suggest', desc: 'Get AI message suggestions' },
{ name: 'g int | interactive', desc: 'Interactive commit wizard' }
]
},
{
title: '🔄 Sync & Maintenance',
cmds: [
{ name: 'g sp | safe-pull', desc: 'Safe pull (stash -> pull -> pop)' },
{ name: 'g sync', desc: 'Smart sync (pull + rebase/merge)' },
{ name: 'g f | fix', desc: 'Fix branch sync issues' },
{ name: 'g main', desc: 'Switch to main & pull latest' },
{ name: 'g clean | cleanup', desc: 'Remove dead local branches' },
{ name: 'g del', desc: 'Delete branch (local + remote)' },
{ name: 'g pull', desc: 'Standard git pull' },
{ name: 'g push', desc: 'Standard git push' }
]
},
{
title: '📜 History & Inspection',
cmds: [
{ name: 'g ls | list', desc: 'Compact commit history' },
{ name: 'g ll | largelist', desc: 'Detailed commit history' },
{ name: 'g last', desc: 'Show last commit diff' },
{ name: 'g t | today', desc: 'Show commits made today' },
{ name: 'g stats', desc: 'Personal commit statistics' },
{ name: 'g w | whoami', desc: 'Show system identity' },
{ name: 'g p | preview', desc: 'Preview commit message' }
]
},
{
title: '📦 Stashing & Work-in-Progress',
cmds: [
{ name: 'g ss | stash-save', desc: 'Quick stash save' },
{ name: 'g pop | stash-pop', desc: 'Pop latest stash' },
{ name: 'g stash', desc: 'Enhanced stash management' },
{ name: 'g wip', desc: 'Quick work-in-progress commit' },
{ name: 'g split', desc: 'Split large changesets' },
{ name: 'g us | unstage', desc: 'Unstage all files' },
{ name: 'g x | discard', desc: 'Discard all changes' }
]
},
{
title: '🌿 Branching & Undo',
cmds: [
{ name: 'g b | branch', desc: 'List or create branches' },
{ name: 'g u | undo', desc: 'Undo last commit' },
{ name: 'g a | amend', desc: 'Amend last commit' },
{ name: 'g rs | reset', desc: 'Reset branch to commit' },
{ name: 'g rv | revert', desc: 'Revert commit safely' },
{ name: 'g conflicts', desc: 'Resolve merge conflicts' }
]
},
{
title: '🔧 Config & Utilities',
cmds: [
{ name: 'g v | version', desc: 'S4 Version management' },
{ name: 'g setup', desc: 'Run setup wizard' },
{ name: 'g config', desc: 'Manage configuration' },
{ name: 'g init', desc: 'Initialize new repo' },
{ name: 'g clone', desc: 'Clone a repository' },
{ name: 'g m | commit', desc: 'Commit with custom message' }
]
}
];
console.log(color.bold('Sync & Fix:'));
console.log(` ${color.cyan('g sp')} Safe pull (stash → pull → pop)`);
console.log(` ${color.cyan('g fix')} Fix branch sync issues`);
console.log(` ${color.cyan('g main')} Switch to main + pull\n`);
sections.forEach(section => {
console.log(color.cyan(color.bold(section.title)));
// Calculate padding dynamically based on longest command name in this section
const maxLen = Math.max(...section.cmds.map(c => c.name.length)) + 4;
console.log(color.bold('Stash:'));
console.log(` ${color.cyan('g ss')} Quick stash save`);
console.log(` ${color.cyan('g pop')} Pop latest stash`);
console.log(` ${color.cyan('g us')} Unstage all files\n`);
section.cmds.forEach(cmd => {
console.log(` ${cmd.name.padEnd(maxLen)} ${color.dim(cmd.desc)}`);
});
console.log('');
});
console.log(color.bold('Smart Commands:'));
console.log(` ${color.cyan('g r')} AI code review`);
console.log(` ${color.cyan('g t')} Today's commits`);
console.log(` ${color.cyan('g last')} Last commit details\n`);
console.log(color.bold('History:'));
console.log(` ${color.cyan('g ls')} Commit history`);
console.log(` ${color.cyan('g a')} Amend last commit`);
console.log(` ${color.cyan('g u')} Undo last commit\n`);
console.log(`Full help: ${color.cyan('g --help')}`);
console.log(color.dim('Use "g <command> --help" for more details on any command.'));
});
program.command('init').alias('i')
@@ -470,27 +565,12 @@ program.command('local').alias('l')
const opts = getOpts();
try {
if (!(await hasChanges()) && !opts.all) {
const rawDiff = await getStagedDiff(opts);
if (!rawDiff) {
Progress.warning('No changes to commit');
return;
}
if (opts.all) {
Progress.info('Staging all changes...');
await git.add('.');
}
let rawDiff = await git.diff(['--cached', '--no-ext-diff']);
if (!rawDiff.trim()) {
Progress.info('No staged changes found; staging all changes...');
await git.add('.');
rawDiff = await git.diff(['--cached', '--no-ext-diff']);
if (!rawDiff.trim()) {
Progress.warning('No changes to commit');
return;
}
}
if (opts.progressIndicators) Progress.start('🤖 Generating commit message');
const result = await generateCommitMessage(rawDiff, opts);
if (opts.progressIndicators) Progress.stop('');
@@ -532,27 +612,12 @@ program.command('online').alias('o')
const opts = getOpts();
try {
if (!(await hasChanges()) && !opts.all) {
const rawDiff = await getStagedDiff(opts);
if (!rawDiff) {
Progress.warning('No changes to commit');
return;
}
if (opts.all) {
Progress.info('Staging all changes...');
await git.add('.');
}
let rawDiff = await git.diff(['--cached', '--no-ext-diff']);
if (!rawDiff.trim()) {
Progress.info('No staged changes found; staging all changes...');
await git.add('.');
rawDiff = await git.diff(['--cached', '--no-ext-diff']);
if (!rawDiff.trim()) {
Progress.warning('No changes to commit');
return;
}
}
if (opts.progressIndicators) Progress.start('🤖 Generating commit message');
const result = await generateCommitMessage(rawDiff, opts);
if (opts.progressIndicators) Progress.stop('');
@@ -617,22 +682,12 @@ program.command('commit <message...>').alias('m')
const msg = (messageParts || []).join(' ').trim();
if (!msg) { console.log('Provide a commit message.'); return; }
if (!(await hasChanges()) && !opts.all) {
console.log('No changes to commit.');
const rawDiff = await getStagedDiff(opts);
if (!rawDiff) {
Progress.warning('No changes to commit');
return;
}
if (opts.all) await git.add('.');
let rawDiff = await git.diff(['--cached', '--no-ext-diff']);
if (!rawDiff.trim()) {
// Auto-stage all changes by default when nothing is staged
console.log(color.yellow('No staged changes found; staging all changes (git add .).'));
await git.add('.');
rawDiff = await git.diff(['--cached', '--no-ext-diff']);
if (!rawDiff.trim()) { console.log('No changes to commit.'); return; }
}
if (opts.dryRun) {
console.log(color.yellow('[dry-run] Would commit with custom message:'));
console.log(msg);
@@ -664,16 +719,114 @@ program.command('pull')
program.command('push')
.description('Push commits to remote')
.action(async () => {
.option('--tags', 'Push all tags to remote')
.action(async (cmdOptions) => {
await ensureRepo();
try {
Progress.info('Pushing to remote...');
await git.push();
Progress.success('Pushed to remote');
if (cmdOptions.tags) {
Progress.info('Pushing tags to remote...');
await git.push(['--tags']);
Progress.success('Tags pushed to remote');
} else {
Progress.info('Pushing to remote...');
await git.push();
Progress.success('Pushed to remote');
}
}
catch (e) { handleError('Push error', e); }
});
program.command('mirror [url]')
.alias('mr')
.description('Manage extra push destinations for origin (g push fans out to all of them)')
.action(async (url) => {
await ensureRepo();
try {
const remotes = await git.getRemotes(true);
const origin = remotes.find(r => r.name === 'origin');
if (!origin) {
Progress.warning("No 'origin' remote configured");
return;
}
const primary = origin.refs.fetch;
const pushUrls = (await git.raw(['config', '--get-all', 'remote.origin.pushurl']).catch(() => ''))
.split('\n').map(s => s.trim()).filter(Boolean);
const mirrors = pushUrls.filter(u => u !== primary);
if (url) {
if (primary === url || pushUrls.includes(url)) {
Progress.warning('That URL is already registered for origin');
return;
}
Progress.info(`Verifying ${url}...`);
try {
await git.listRemote([url]);
} catch {
const proceed = await confirmPrompt(`Could not reach "${url}". Add it anyway?`, false);
if (!proceed) { Progress.info('Cancelled'); return; }
}
// Make the primary an explicit pushurl first so it isn't lost once we add others
if (pushUrls.length === 0) {
await git.raw(['remote', 'set-url', '--push', 'origin', primary]);
}
await git.raw(['remote', 'set-url', '--add', '--push', 'origin', url]);
Progress.success(`Added mirror: ${url}`);
Progress.info(`'g push' now pushes to ${mirrors.length + 2} destination(s)`);
return;
}
console.log(color.bold('\nPush destinations for origin:'));
console.log(` ${color.green('●')} ${primary} ${color.dim('(primary)')}`);
if (mirrors.length === 0) {
console.log(color.dim('\nNo mirrors configured.'));
console.log(color.dim(`Add one with: ${color.cyan('g mirror <url>')}`));
return;
}
mirrors.forEach(m => console.log(` ${color.cyan('○')} ${m} ${color.dim('(mirror)')}`));
// Single readline session for the whole remove flow — separate
// interfaces on the same stdin can drop input on later prompts.
const readline = require('readline');
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
const ask = (q) => new Promise(resolve => rl.question(q, a => resolve(a.trim())));
const confirm = async (message, defaultYes) => {
const suffix = defaultYes ? '[Y/n]' : '[y/N]';
const answer = (await ask(`${message} ${suffix}: `)).toLowerCase();
if (answer === '') return defaultYes;
return answer === 'y' || answer === 'yes';
};
try {
const wantsRemove = await confirm('\nRemove a mirror?', false);
if (!wantsRemove) return;
let target = mirrors[0];
if (mirrors.length > 1) {
const answer = await ask(`Which mirror? [1-${mirrors.length}]: `);
const idx = parseInt(answer) - 1;
if (isNaN(idx) || idx < 0 || idx >= mirrors.length) {
Progress.warning('Invalid selection, cancelled');
return;
}
target = mirrors[idx];
}
const confirmDelete = await confirm(`Remove "${target}"?`, false);
if (!confirmDelete) { Progress.info('Cancelled'); return; }
await git.raw(['remote', 'set-url', '--delete', '--push', 'origin', target]);
Progress.success(`Removed mirror: ${target}`);
} finally {
rl.close();
}
} catch (e) {
handleError('Mirror error', e);
}
});
program.command('sync')
.description('Smart sync: pull + rebase/merge')
.option('--rebase', 'Use rebase instead of merge')
@@ -768,11 +921,12 @@ program.command('stash')
Progress.start('🤖 Generating stash description');
const diff = await git.diff();
const description = await aiProvider.generateCommitMessage(diff, {
const descResult = await aiProvider.generateCommitMessage(diff, {
conventional: false,
body: false
});
Progress.stop('');
const description = descResult.message || descResult;
await git.stash(['push', '-m', `WIP: ${description}`]);
Progress.success(`Stashed changes: "${description}"`);
@@ -791,6 +945,7 @@ program.command('version').alias('v')
.option('--list', 'List S4 tags (hides dev tags by default)')
.option('--prune', 'Prune old dev tags (keeps last 10)')
.option('--all', 'Show all tags (including dev) when listing')
.option('-u, --undo', 'Undo the last version bump (delete latest tag)')
.action(async (type, options) => {
await ensureRepo();
if (!versionCmd) initializeComponents();
@@ -864,28 +1019,28 @@ program.command('amend').alias('a')
}
});
async function printCommitLog(limit) {
const log = await git.log({ maxCount: limit });
const commits = [...log.all].reverse();
if (commits.length === 0) {
Progress.info('No commits found');
return;
}
commits.forEach((c, i) => {
console.log(`${color.cyan((i + 1).toString())}. ${color.yellow(c.hash.slice(0, 7))} ${c.message}`);
});
if (log.all.length >= limit) {
console.log(color.dim(`\n... showing last ${limit} commits (use --limit to see more)`));
}
}
program.command('list').alias('ls')
.description('Short numbered git log (oldest → newest)')
.option('--limit <n>', 'Limit number of commits', '20')
.action(async (cmdOptions) => {
await ensureRepo();
try {
const limit = parseInt(cmdOptions.limit) || 20;
const log = await git.log({ maxCount: limit });
const commits = [...log.all].reverse();
if (commits.length === 0) {
Progress.info('No commits found');
return;
}
commits.forEach((c, i) => {
console.log(`${color.cyan((i + 1).toString())}. ${color.yellow(c.hash.slice(0, 7))} ${c.message}`);
});
if (log.all.length >= limit) {
console.log(color.dim(`\n... showing last ${limit} commits (use --limit to see more)`));
}
await printCommitLog(parseInt(cmdOptions.limit) || 20);
} catch (e) {
handleError('List error', e);
}
@@ -925,32 +1080,37 @@ program.command('history').alias('h')
.action(async (cmdOptions) => {
await ensureRepo();
try {
const limit = parseInt(cmdOptions.limit) || 20;
const log = await git.log({ maxCount: limit });
const commits = [...log.all].reverse();
if (commits.length === 0) {
Progress.info('No commits found');
return;
}
commits.forEach((c, i) => {
console.log(`${color.cyan((i + 1).toString())}. ${color.yellow(c.hash.slice(0, 7))} ${c.message}`);
});
if (log.all.length >= limit) {
console.log(color.dim(`\n... showing last ${limit} commits (use --limit to see more)`));
}
await printCommitLog(parseInt(cmdOptions.limit) || 20);
} catch (e) {
handleError('History error', e);
}
});
program.command('branch <c> [name]').alias('b')
.description('Branch from commit/index')
program.command('branch [c] [name]').alias('b')
.description('List branches or branch from commit/index')
.action(async (c, name) => {
await ensureRepo();
try { const sha = await resolveCommit(c); const br = name || `branch-${sha.slice(0, 7)}`; await git.checkout(['-b', br, sha]); console.log(`Switched to branch ${br} at ${sha}`); }
try {
if (!c) {
// List branches
const branches = await git.branchLocal();
console.log(color.bold('\n🌿 Local Branches:\n'));
branches.all.forEach(b => {
if (b === branches.current) {
console.log(` ${color.green('* ' + b)}`);
} else {
console.log(` ${b}`);
}
});
console.log('');
} else {
// Create branch
const sha = await resolveCommit(c);
const br = name || `branch-${sha.slice(0, 7)}`;
await git.checkout(['-b', br, sha]);
console.log(`Switched to branch ${br} at ${sha}`);
}
}
catch (e) { handleError('Branch error', e); }
});
@@ -1530,7 +1690,7 @@ program.command('last')
// ===== SMART SYNC FIX COMMAND =====
program.command('fix')
program.command('fix').alias('f')
.description('Smart fix for branch sync issues (diverged, behind, ahead)')
.option('--local', 'Keep local changes, force push to remote')
.option('--remote', 'Keep remote changes, discard local')
@@ -1664,14 +1824,16 @@ program.command('fix')
if (behind > 0) {
try {
const behindLog = await git.log({ from: branch, to: remoteBranch, maxCount: 5 });
// symmetric: false → "branch..remoteBranch" (commits on remote only, not "branch...remoteBranch" which mixes both directions)
const behindLog = await git.log({ from: branch, to: remoteBranch, symmetric: false, maxCount: 5 });
aiContext += `Incoming commits (latest 5):\n${behindLog.all.map(c => `- ${c.message}`).join('\n')}\n\n`;
} catch (e) { }
}
if (ahead > 0) {
try {
const aheadLog = await git.log({ from: remoteBranch, to: branch, maxCount: 5 });
// symmetric: false → "remoteBranch..branch" (commits on local only)
const aheadLog = await git.log({ from: remoteBranch, to: branch, symmetric: false, maxCount: 5 });
aiContext += `My outgoing commits (latest 5):\n${aheadLog.all.map(c => `- ${c.message}`).join('\n')}\n`;
} catch (e) { }
}
@@ -1687,36 +1849,40 @@ program.command('fix')
Recommended Command: <command>
`;
// Use preferred provider or auto-resolve
const provider = aiProvider.resolveProvider(opts.provider);
if (provider === 'none') {
const heuristicRec = () => {
if (ahead > 0 && behind === 0) return 'Push (g push)';
if (behind > 0 && ahead === 0) return 'Pull (g pull)';
return 'Rebase (g fix --rebase)';
};
// Try each available provider in priority order, with full fallback chain
const providerChain = aiProvider.buildProviderChain(opts.provider || 'auto')
.filter(p => p !== 'local');
if (providerChain.length === 0) {
Progress.stop('');
console.log(color.yellow('No AI provider configured. Falling back to simple heuristics.'));
// ... heuristic fallback ...
let rec = '';
if (ahead > 0 && behind === 0) rec = 'Push (g push)';
else if (behind > 0 && ahead === 0) rec = 'Pull (g pull)';
else rec = 'Rebase (g fix --rebase)';
console.log(`Recommendation: ${rec}`);
console.log(`Recommendation: ${heuristicRec()}`);
return;
}
try {
const response = await aiProvider.generateWithProvider(provider, prompt, { temperature: 0.3 }); // Use generic provider method
Progress.stop('');
console.log(`\n${color.bold('🤖 AI Analysis:')}`);
console.log(response.trim());
} catch (e) {
Progress.stop('');
console.log(color.yellow('AI Analysis failed, falling back to heuristics.'));
// ... heuristic fallback code ...
let rec = '';
if (ahead > 0 && behind === 0) rec = 'Push (g push)';
else if (behind > 0 && ahead === 0) rec = 'Pull (g pull)';
else rec = 'Rebase (g fix --rebase)';
console.log(`Recommendation: ${rec}`);
let response = null;
for (const p of providerChain) {
try {
response = await aiProvider.generateWithProvider(p, prompt, { temperature: 0.3 });
break;
} catch { continue; }
}
Progress.stop('');
if (!response) {
console.log(color.yellow('AI providers unavailable. Falling back to heuristics.'));
console.log(`Recommendation: ${heuristicRec()}`);
return;
}
console.log(`\n${color.bold('🤖 AI Analysis:')}`);
console.log(response.trim());
return;
}
+132
View File
@@ -0,0 +1,132 @@
/**
* GIMS AI Interface Registry
*
* This module defines the "Tools" that GIMS exposes to AI systems (MCP, OpenAI, etc.).
* It serves as the Single Source of Truth for tool definitions and their schemas.
*/
const simpleGit = require('simple-git');
const { GitAnalyzer } = require('../git/analyzer');
const { S4Versioning } = require('../utils/s4');
const { ConfigManager } = require('../config/manager');
const { AIProviderManager } = require('./providers');
// Initialize shared instances
const git = simpleGit();
const gitAnalyzer = new GitAnalyzer(git);
const configManager = new ConfigManager();
const config = configManager.load();
const aiProvider = new AIProviderManager(config);
const s4 = new S4Versioning(git);
/**
* Tool Definitions
* Format:
* {
* name: "tool_name",
* description: "Description for the AI",
* inputSchema: { ...JSON Schema... },
* handler: async (args) => { ... implementation ... }
* }
*/
const tools = [
{
name: "get_status",
description: "Get enhanced git status with AI insights, file modification stats, and branch context. Use this to understand the current state of the repository.",
inputSchema: {
type: "object",
properties: {},
},
handler: async () => {
return await gitAnalyzer.getEnhancedStatus();
}
},
{
name: "analyze_history",
description: "Analyze recent commit history, including authors, conventions, and activity patterns.",
inputSchema: {
type: "object",
properties: {
limit: {
type: "number",
description: "Number of commits to analyze (default: 10)"
}
}
},
handler: async ({ limit = 10 }) => {
return await gitAnalyzer.analyzeCommitHistory(limit);
}
},
{
name: "version_info",
description: "Get current project version information using S4 versioning (Semantic + Date/Time).",
inputSchema: {
type: "object",
properties: {}
},
handler: async () => {
const currentVersion = await s4.getCurrentVersion();
if (!currentVersion) return { version: "0.0.0", source: "fallback" };
return { version: currentVersion, details: S4Versioning.parse(currentVersion) };
}
},
{
name: "generate_commit_message",
description: "Generate a high-quality commit message based on currently staged changes.",
inputSchema: {
type: "object",
properties: {
context: {
type: "string",
description: "Optional context or user instruction for the message generation"
}
}
},
handler: async ({ context }) => {
const rawDiff = await git.diff(['--cached', '--no-ext-diff']);
if (!rawDiff.trim()) {
return { error: "No staged changes to generate message for." };
}
// Pass pseudo-options resembling CLI opts
const opts = { conventional: config.conventional };
const message = await aiProvider.generateCommitMessage(rawDiff, opts);
// Handle object return from provider (some return { message, usedLocal })
const msgStr = typeof message === 'string' ? message : message.message;
return {
message: msgStr,
original_diff_size: rawDiff.length
};
}
},
{
name: "run_git_command",
description: "Execute a raw git command safely. Use this for standard git operations not covered by other tools.",
inputSchema: {
type: "object",
properties: {
command: {
type: "string",
description: "The full git command to run (e.g., 'log -n 5', 'branch --list')"
}
},
required: ["command"]
},
handler: async ({ command }) => {
// Safety check: block potentially destructive commands if needed,
// but for now we assume the agent is trusted or user-monitored.
// We'll strip 'git ' prefix if present.
const cleanCmd = command.replace(/^git\s+/, '').trim();
const args = cleanCmd.split(' ');
try {
const result = await git.raw(args);
return { output: result ? result.trim() : "Success" };
} catch (e) {
return { error: e.message };
}
}
}
];
module.exports = { tools };
+49 -38
View File
@@ -1,3 +1,5 @@
const fs = require('fs');
const path = require('path');
const { OpenAI } = require('openai');
const { GoogleGenAI } = require('@google/genai');
const { Progress } = require('../utils/progress');
@@ -9,31 +11,17 @@ const { color } = require('../utils/colors');
class AIProviderManager {
constructor(config = {}) {
this.config = config;
this.cache = new Map();
this.maxCacheSize = 100;
}
resolveProvider(preference = 'auto') {
if (preference === 'none') return 'none';
// Check if preferred provider's key is available
if (preference === 'openai' && process.env.OPENAI_API_KEY) return 'openai';
if (preference === 'gemini' && process.env.GEMINI_API_KEY) return 'gemini';
if (preference === 'groq' && process.env.GROQ_API_KEY) return 'groq';
// Fallback: try any available provider (priority: Gemini → OpenAI → Groq)
if (process.env.GEMINI_API_KEY) return 'gemini';
if (process.env.OPENAI_API_KEY) return 'openai';
if (process.env.GROQ_API_KEY) return 'groq';
return 'none';
this.cacheFile = path.join(
process.env.HOME || process.env.USERPROFILE || process.cwd(),
'.gims', 'cache.json'
);
}
getDefaultModel(provider) {
const defaults = {
'gemini': 'gemini-3-flash-preview', // Latest Gemini model
'openai': 'gpt-5.2-2025-12-11', // Latest GPT model
'groq': 'groq/compound' // Latest Groq model
'gemini': 'gemini-2.0-flash',
'openai': 'gpt-4o-mini',
'groq': 'llama-3.3-70b-versatile'
};
return defaults[provider] || '';
}
@@ -46,26 +34,36 @@ class AIProviderManager {
getFromCache(cacheKey) {
if (!this.config.cacheEnabled) return null;
return this.cache.get(cacheKey);
try {
if (!fs.existsSync(this.cacheFile)) return null;
const data = JSON.parse(fs.readFileSync(this.cacheFile, 'utf8'));
return data[cacheKey] || null;
} catch {
return null;
}
}
setCache(cacheKey, result, usedLocal = false) {
if (!this.config.cacheEnabled) return;
if (this.cache.size >= this.maxCacheSize) {
const firstKey = this.cache.keys().next().value;
this.cache.delete(firstKey);
}
this.cache.set(cacheKey, {
result,
usedLocal,
timestamp: Date.now()
});
try {
const dir = path.dirname(this.cacheFile);
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
let data = {};
if (fs.existsSync(this.cacheFile)) {
try { data = JSON.parse(fs.readFileSync(this.cacheFile, 'utf8')); } catch {}
}
const keys = Object.keys(data);
if (keys.length >= 100) {
const oldest = keys.sort((a, b) => (data[a].timestamp || 0) - (data[b].timestamp || 0));
oldest.slice(0, keys.length - 99).forEach(k => delete data[k]);
}
data[cacheKey] = { result, usedLocal, timestamp: Date.now() };
fs.writeFileSync(this.cacheFile, JSON.stringify(data));
} catch {}
}
async generateWithProvider(provider, prompt, options = {}) {
const { model = '', temperature = 0.3, maxTokens = 200 } = options;
const { model = '' } = options;
try {
switch (provider) {
@@ -79,7 +77,14 @@ class AIProviderManager {
throw new Error(`Unknown provider: ${provider}`);
}
} catch (error) {
throw new Error(`${provider} generation failed: ${error.message}`);
const msg = error.message || '';
if (msg.includes('429') || /rate.?limit/i.test(msg)) {
throw new Error(`${provider} rate limit hit — try again in a moment`);
}
if (msg.includes('401') || /invalid.api.key|api_key/i.test(msg)) {
throw new Error(`${provider} API key invalid — run: g setup --api-key ${provider}`);
}
throw new Error(`${provider} generation failed: ${msg}`);
}
}
@@ -135,8 +140,14 @@ class AIProviderManager {
verbose = false
} = options;
// Truncate oversized diffs before sending to AI
const maxDiffSize = this.config.maxDiffSize || 100000;
const truncatedDiff = diff.length > maxDiffSize
? diff.substring(0, maxDiffSize) + '\n... (diff truncated for AI)'
: diff;
// Check cache first
const cacheKey = this.getCacheKey(diff, { conventional, body });
const cacheKey = this.getCacheKey(truncatedDiff, { conventional, body });
const cached = this.getFromCache(cacheKey);
if (cached && Date.now() - cached.timestamp < 3600000) { // 1 hour cache
if (verbose) Progress.info('Using cached result');
@@ -148,12 +159,12 @@ class AIProviderManager {
for (const provider of providerChain) {
try {
if (provider === 'local') {
const result = await this.generateLocalHeuristic(diff, options);
const result = await this.generateLocalHeuristic(truncatedDiff, options);
this.setCache(cacheKey, result, true);
return { message: result, usedLocal: true };
}
const prompt = this.buildPrompt(diff, { conventional, body });
const prompt = this.buildPrompt(truncatedDiff, { conventional, body });
const result = await this.generateWithProvider(provider, prompt, options);
const cleaned = this.cleanCommitMessage(result, { body });
+43
View File
@@ -26,6 +26,11 @@ class VersionCommand {
return;
}
if (options.undo) {
await this.undoLastBump();
return;
}
// --- Main Bump Logic ---
// 1. Get current version from Git Tags (SSOT)
@@ -196,6 +201,44 @@ class VersionCommand {
console.log(color.dim('Kept last 10 dev tags + all stable tags.'));
}
async undoLastBump() {
Progress.start('Undoing last version bump...');
// 1. Get current version (the one to delete)
const currentVersion = await this.s4.getCurrentVersion();
if (!currentVersion) {
Progress.stop('');
console.log(color.yellow('No S4 version tags found to undo.'));
return;
}
// 2. Delete the tag
try {
await this.git.tag(['-d', currentVersion]);
Progress.stop('');
console.log(`${color.green('✔')} Deleted tag: ${color.cyan(currentVersion)}`);
} catch (e) {
Progress.error(`Failed to delete tag: ${e.message}`);
return;
}
// 3. Revert .env files to *previous* version
// Now that the latest tag is gone, getCurrentVersion will return the previous one
const previousVersion = await this.s4.getCurrentVersion() || '0.0.0';
if (previousVersion) {
console.log(`Reverting environment to previous version: ${color.dim(previousVersion)}`);
const updatedFiles = this.updateEnvFiles(previousVersion);
if (updatedFiles.length > 0) {
console.log(`${color.green('✔')} Updated ${updatedFiles.join(', ')}`);
}
}
console.log(color.dim('\nNote: If you already pushed the tag, you must verify deletion on remote:'));
console.log(` ${color.cyan(`git push --delete origin ${currentVersion}`)}`);
}
showInfo(versionStr) {
const parsed = S4Versioning.parse(versionStr);
if (!parsed) {
+6 -6
View File
@@ -164,14 +164,14 @@ class ConfigManager {
console.log(` ${color.cyan('g setup --api-key openai')} # High quality`);
console.log(` ${color.cyan('g setup --api-key groq')} # Ultra fast`);
console.log('\nOr set environment variables manually:');
console.log(' - OPENAI_API_KEY (gpt-5)');
console.log(' - GEMINI_API_KEY (gemini-2.5-flash)');
console.log(' - GROQ_API_KEY (groq/compound)');
console.log(' - OPENAI_API_KEY (gpt-4o-mini)');
console.log(' - GEMINI_API_KEY (gemini-2.0-flash)');
console.log(' - GROQ_API_KEY (llama-3.3-70b-versatile)');
} else {
console.log('Available providers with default models:');
if (hasGemini) console.log(` ${color.green('✓')} Google Gemini (gemini-2.5-flash)`);
if (hasOpenAI) console.log(` ${color.green('✓')} OpenAI (gpt-5)`);
if (hasGroq) console.log(` ${color.green('✓')} Groq (groq/compound)`);
if (hasGemini) console.log(` ${color.green('✓')} Google Gemini (gemini-2.0-flash)`);
if (hasOpenAI) console.log(` ${color.green('✓')} OpenAI (gpt-4o-mini)`);
if (hasGroq) console.log(` ${color.green('✓')} Groq (llama-3.3-70b-versatile)`);
}
const provider = await question(`\nPreferred provider (auto/openai/gemini/groq/none) [auto]: `) || 'auto';
+75
View File
@@ -0,0 +1,75 @@
[
{
"type": "function",
"function": {
"name": "get_status",
"description": "Get enhanced git status with AI insights, file modification stats, and branch context. Use this to understand the current state of the repository.",
"parameters": {
"type": "object",
"properties": {}
}
}
},
{
"type": "function",
"function": {
"name": "analyze_history",
"description": "Analyze recent commit history, including authors, conventions, and activity patterns.",
"parameters": {
"type": "object",
"properties": {
"limit": {
"type": "number",
"description": "Number of commits to analyze (default: 10)"
}
}
}
}
},
{
"type": "function",
"function": {
"name": "version_info",
"description": "Get current project version information using S4 versioning (Semantic + Date/Time).",
"parameters": {
"type": "object",
"properties": {}
}
}
},
{
"type": "function",
"function": {
"name": "generate_commit_message",
"description": "Generate a high-quality commit message based on currently staged changes.",
"parameters": {
"type": "object",
"properties": {
"context": {
"type": "string",
"description": "Optional context or user instruction for the message generation"
}
}
}
}
},
{
"type": "function",
"function": {
"name": "run_git_command",
"description": "Execute a raw git command safely. Use this for standard git operations not covered by other tools.",
"parameters": {
"type": "object",
"properties": {
"command": {
"type": "string",
"description": "The full git command to run (e.g., 'log -n 5', 'branch --list')"
}
},
"required": [
"command"
]
}
}
}
]
+94
View File
@@ -0,0 +1,94 @@
#!/usr/bin/env node
/**
* GIMS MCP Server
*
* Exposes GIMS capabilities as Model Context Protocol (MCP) tools.
* Usage: node mcp/index.js
*/
const { Server } = require("@modelcontextprotocol/sdk/server/index.js");
const { StdioServerTransport } = require("@modelcontextprotocol/sdk/server/stdio.js");
const {
CallToolRequestSchema,
ListToolsRequestSchema,
} = require("@modelcontextprotocol/sdk/types.js");
const { tools } = require('../bin/lib/ai/interface');
// Create the server
const server = new Server(
{
name: "gims-mcp-server",
version: require('../package.json').version,
},
{
capabilities: {
tools: {},
},
}
);
/**
* Handler for listing available tools
*/
server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: tools.map((tool) => ({
name: tool.name,
description: tool.description,
inputSchema: tool.inputSchema,
})),
};
});
/**
* Handler for calling tools
*/
server.setRequestHandler(CallToolRequestSchema, async (request) => {
const toolName = request.params.name;
const toolArgs = request.params.arguments;
const tool = tools.find((t) => t.name === toolName);
if (!tool) {
throw new Error(`Unknown tool: ${toolName}`);
}
try {
const result = await tool.handler(toolArgs);
// MCP expects content to be an array of text/image objects
return {
content: [
{
type: "text",
text: JSON.stringify(result, null, 2),
},
],
};
} catch (error) {
return {
content: [
{
type: "text",
text: `Error executing ${toolName}: ${error.message}`,
},
],
isError: true,
};
}
});
/**
* Start the server
*/
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("GIMS MCP Server running on stdio");
}
main().catch((error) => {
console.error("Server error:", error);
process.exit(1);
});
+958 -53
View File
File diff suppressed because it is too large. Load diff
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "gims",
"version": "0.8.2-dev.2+20260128.2346.9eaa681.main",
"version": "0.9.2",
"description": "Git Made Simple – AI‑powered git helper with smart insights, stats & code review",
"author": "S41R4J",
"license": "MIT",
@@ -33,6 +33,7 @@
},
"dependencies": {
"@google/genai": "1.5.1",
"@modelcontextprotocol/sdk": "^1.25.3",
"clipboardy": "^3.0.0",
"commander": "^11.1.0",
"openai": "^4.0.0",
+28
View File
@@ -0,0 +1,28 @@
const { OpenAI } = require('openai');
const process = require('process');
async function testOpenAI() {
console.log('Testing OpenAI connection...');
console.log('API Key present:', !!process.env.OPENAI_API_KEY);
console.log('Model:', 'gpt-5.2-2025-12-11');
try {
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
// Log the base URL to see if it's custom
console.log('Base URL:', openai.baseURL);
const response = await openai.chat.completions.create({
model: 'gpt-5.2-2025-12-11',
messages: [{ role: 'user', content: 'Say hello' }],
});
console.log('Success!');
console.log('Content:', response.choices[0].message.content);
} catch (error) {
console.error('ERROR OCCURRED:');
console.error(error);
}
}
testOpenAI();
+18
View File
@@ -0,0 +1,18 @@
const fs = require('fs');
const path = require('path');
const { tools } = require('../bin/lib/ai/interface');
const schema = tools.map(tool => ({
type: "function",
function: {
name: tool.name,
description: tool.description,
parameters: tool.inputSchema
}
}));
const outputPath = path.resolve(__dirname, '../bin/tools-schema.json');
fs.writeFileSync(outputPath, JSON.stringify(schema, null, 2));
console.log(`✅ Generated OpenAI-compatible tool schemas at: ${outputPath}`);
console.log(`Total tools: ${tools.length}`);