mcpField
A
agentic-jujutsu

agentic-jujutsu

github.com/ruvnet开发80.0k1.2k 次安装今天更新
代码仓库

关于 agentic-jujutsu

agentic-jujutsu 是用于版本控制操作的 JavaScript 封装,面向需要协调多个 AI Agent 并行工作的团队。它会记录工作流程、提取模式并提供建议,也包含指纹生成和加密方法。

主要功能

  1. 01仓库状态、提交、历史、分支与变基
  2. 02记录操作和学习轨迹
  3. 03发现模式并提供工作流建议
  4. 04协调多个 Agent 并行工作
  5. 05SHA3-512 指纹与加密控制

适用场景

  1. 01协调多个 Agent 并行修改代码
  2. 02根据已记录结果改进部署工作流
  3. 03查找以往合并尝试中的模式

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/ruvnet/ruflo --skill agentic-jujutsu

安装后在 Claude Code 中输入/agentic-jujutsu确认已加载。

详细介绍

Agentic Jujutsu - AI Agent 版本控制

面向未来量子安全,具备自学习能力的版本控制系统,专为多个 AI Agent 同时协作且互不冲突而设计。

何时使用此技能

在以下情况下使用 agentic-jujutsu:

  • ✅ 多个 AI Agent 同时修改代码
  • ✅ 无锁版本控制(比 Git 快 23 倍)
  • ✅ 能从经验中不断改进的自学习 AI
  • ✅ 具备量子抗性安全,提供面向未来的保护
  • ✅ 自动冲突解决(成功率 87%)
  • ✅ 模式识别与智能建议
  • ✅ 多 Agent 协作,无需阻塞

快速入门

安装
npx agentic-jujutsu
基本用法
const { JjWrapper } = require('agentic-jujutsu');

const jj = new JjWrapper();

// Basic operations
await jj.status();
await jj.newCommit('Add feature');
await jj.log(10);

// Self-learning trajectory
const id = jj.startTrajectory('Implement authentication');
await jj.branchCreate('feature$auth');
await jj.newCommit('Add auth');
jj.addToTrajectory();
jj.finalizeTrajectory(0.9, 'Clean implementation');

// Get AI suggestions
const suggestion = JSON.parse(jj.getSuggestion('Add logout feature'));
console.log(`Confidence: ${suggestion.confidence}`);

核心能力

1. 使用 ReasoningBank 进行自学习

跟踪操作、学习模式并获取智能建议:

// Start learning trajectory
const trajectoryId = jj.startTrajectory('Deploy to production');

// Perform operations (automatically tracked)
await jj.execute(['git', 'push', 'origin', 'main']);
await jj.branchCreate('release$v1.0');
await jj.newCommit('Release v1.0');

// Record operations to trajectory
jj.addToTrajectory();

// Finalize with success score (0.0-1.0) and critique
jj.finalizeTrajectory(0.95, 'Deployment successful, no issues');

// Later: Get AI-powered suggestions for similar tasks
const suggestion = JSON.parse(jj.getSuggestion('Deploy to staging'));
console.log('AI Recommendation:', suggestion.reasoning);
console.log('Confidence:', (suggestion.confidence * 100).toFixed(1) + '%');
console.log('Expected Success:', (suggestion.expectedSuccessRate * 100).toFixed(1) + '%');

验证(v2.3.1):

  • ✅ 任务不能为空(最多 10KB)
  • ✅ 成功分数必须介于 0.0-1.0 之间
  • ✅ 完成前必须执行过操作
  • ✅ 上下文不能为空
2. 模式发现

自动识别成功的操作序列:

// Get discovered patterns
const patterns = JSON.parse(jj.getPatterns());

patterns.forEach(pattern => {
    console.log(`Pattern: ${pattern.name}`);
    console.log(`  Success rate: ${(pattern.successRate * 100).toFixed(1)}%`);
    console.log(`  Used ${pattern.observationCount} times`);
    console.log(`  Operations: ${pattern.operationSequence.join(' → ')}`);
    console.log(`  Confidence: ${(pattern.confidence * 100).toFixed(1)}%`);
});
3. 学习统计

跟踪随时间的改进情况:

const stats = JSON.parse(jj.getLearningStats());

console.log('Learning Progress:');
console.log(`  Total trajectories: ${stats.totalTrajectories}`);
console.log(`  Patterns discovered: ${stats.totalPatterns}`);
console.log(`  Average success: ${(stats.avgSuccessRate * 100).toFixed(1)}%`);
console.log(`  Improvement rate: ${(stats.improvementRate * 100).toFixed(1)}%`);
console.log(`  Prediction accuracy: ${(stats.predictionAccuracy * 100).toFixed(1)}%`);
4. 多 Agent 协调

多个 Agent 并发工作,互不冲突:

// Agent 1: Developer
const dev = new JjWrapper();
dev.startTrajectory('Implement feature');
await dev.newCommit('Add feature X');
dev.addToTrajectory();
dev.finalizeTrajectory(0.85);

// Agent 2: Reviewer (learns from Agent 1)
const reviewer = new JjWrapper();
const suggestion = JSON.parse(reviewer.getSuggestion('Review feature X'));

if (suggestion.confidence > 0.7) {
    console.log('High confidence approach:', suggestion.reasoning);
}

// Agent 3: Tester (benefits from both)
const tester = new JjWrapper();
const similar = JSON.parse(tester.queryTrajectories('test feature', 5));
console.log(`Found ${similar.length} similar test approaches`);
5. 量子抗性安全(v2.3.0+)

使用量子抗性加密技术快速验证完整性:

const { generateQuantumFingerprint, verifyQuantumFingerprint } = require('agentic-jujutsu');

// Generate SHA3-512 fingerprint (NIST FIPS 202)
const data = Buffer.from('commit-data');
const fingerprint = generateQuantumFingerprint(data);
console.log('Fingerprint:', fingerprint.toString('hex'));

// Verify integrity (<1ms)
const isValid = verifyQuantumFingerprint(data, fingerprint);
console.log('Valid:', isValid);

// HQC-128 encryption for trajectories
const crypto = require('crypto');
const key = crypto.randomBytes(32).toString('base64');
jj.enableEncryption(key);
6. 使用 AgentDB 跟踪操作

自动跟踪所有操作:

// Operations are tracked automatically
await jj.status();
await jj.newCommit('Fix bug');
await jj.rebase('main');

// Get operation statistics
const stats = JSON.parse(jj.getStats());
console.log(`Total operations: ${stats.total_operations}`);
console.log(`Success rate: ${(stats.success_rate * 100).toFixed(1)}%`);
console.log(`Avg duration: ${stats.avg_duration_ms.toFixed(2)}ms`);

// Query recent operations
const ops = jj.getOperations(10);
ops.forEach(op => {
    console.log(`${op.operationType}: ${op.command}`);
    console.log(`  Duration: ${op.durationMs}ms, Success: ${op.success}`);
});

// Get user operations (excludes snapshots)
const userOps = jj.getUserOperations(20);

高级用例

用例 1:自适应工作流优化

学习并改进部署工作流:

async function adaptiveDeployment(jj, environment) {
    // Get AI suggestion based on past deployments
    const suggestion = JSON.parse(jj.getSuggestion(`Deploy to ${environment}`));
    
    console.log(`Deploying with ${(suggestion.confidence * 100).toFixed(0)}% confidence`);
    console.log(`Expected duration: ${suggestion.estimatedDurationMs}ms`);
    
    // Start tracking
    jj.startTrajectory(`Deploy to ${environment}`);
    
    // Execute recommended operations
    for (const op of suggestion.recommendedOperations) {
        console.log(`Executing: ${op}`);
        await executeOperation(op);
    }
    
    jj.addToTrajectory();
    
    // Record outcome
    const success = await verifyDeployment();
    jj.finalizeTrajectory(
        success ? 0.95 : 0.5,
        success ? 'Deployment successful' : 'Issues detected'
    );
}
用例 2:多 Agent 代码审查

协调多个 Agent 进行审查:

async function coordinatedReview(agents) {
    const reviews = await Promise.all(agents.map(async (agent) => {
        const jj = new JjWrapper();
        
        // Start review trajectory
        jj.startTrajectory(`Review by ${agent.name}`);
        
        // Get AI suggestion for review approach
        const suggestion = JSON.parse(jj.getSuggestion('Code review'));
        
        // Perform review
        const diff = await jj.diff('@', '@-');
        const issues = await agent.analyze(diff);
        
        jj.addToTrajectory();
        jj.finalizeTrajectory(
            issues.length === 0 ? 0.9 : 0.6,
            `Found ${issues.length} issues`
        );
        
        return { agent: agent.name, issues, suggestion };
    }));
    
    // Aggregate learning from all agents
    return reviews;
}
用例 3:错误模式检测

从失败中学习,避免未来出现问题:

async function smartMerge(jj, branch) {
    // Query similar merge attempts
    const similar = JSON.parse(jj.queryTrajectories(`merge ${branch}`, 10));
    
    // Analyze past failures
    const failures = similar.filter(t => t.successScore < 0.5);
    
    if (failures.length > 0) {
        console.log('⚠️ Similar merges failed in the past:');
        failures.forEach(f => {
            if (f.critique) {
                console.log(`  - ${f.critique}`);
            }
        });
    }
    
    // Get AI recommendation
    const suggestion = JSON.parse(jj.getSuggestion(`merge ${branch}`));
    
    if (suggestion.confidence < 0.7) {
        console.log('⚠️ Low confidence. Recommended steps:');
        suggestion.recommendedOperations.forEach(op => console.log(`  - ${op}`));
    }
    
    // Execute merge with tracking
    jj.startTrajectory(`Merge ${branch}`);
    try {
        await jj.execute(['merge', branch]);
        jj.addToTrajectory();
        jj.finalizeTrajectory(0.9, 'Merge successful');
    } catch (err) {
        jj.addToTrajectory();
        jj.finalizeTrajectory(0.3, `Merge failed: ${err.message}`);
        throw err;
    }
}
用例 4:持续学习循环

实现自我改进的 Agent:

class SelfImprovingAgent {
    constructor() {
        this.jj = new JjWrapper();
    }
    
    async performTask(taskDescription) {
        // Get AI suggestion
        const suggestion = JSON.parse(this.jj.getSuggestion(taskDescription));
        
        console.log(`Task: ${taskDescription}`);
        console.log(`AI Confidence: ${(suggestion.confidence * 100).toFixed(1)}%`);
        console.log(`Expected Success: ${(suggestion.expectedSuccessRate * 100).toFixed(1)}%`);
        
        // Start trajectory
        this.jj.startTrajectory(taskDescription);
        
        // Execute with recommended approach
        const startTime = Date.now();
        let success = false;
        
        try {
            for (const op of suggestion.recommendedOperations) {
                await this.execute(op);
            }
            success = true;
        } catch (err) {
            console.error('Task failed:', err.message);
        }
        
        const duration = Date.now() - startTime;
        
        // Record learning
        this.jj.addToTrajectory();
        this.jj.finalizeTrajectory(
            success ? 0.9 : 0.4,
            success 
                ? `Completed in ${duration}ms using ${suggestion.recommendedOperations.length} operations`
                : `Failed after ${duration}ms`
        );
        
        // Check improvement
        const stats = JSON.parse(this.jj.getLearningStats());
        console.log(`Improvement rate: ${(stats.improvementRate * 100).toFixed(1)}%`);
        
        return success;
    }
    
    async execute(operation) {
        // Execute operation logic
    }
}

// Usage
const agent = new SelfImprovingAgent();

// Agent improves over time
for (let i = 1; i <= 10; i++) {
    console.log(`\n--- Attempt ${i} ---`);
    await agent.performTask('Deploy application');
}

API 参考

核心方法
方法描述返回值
new JjWrapper()创建包装器实例JjWrapper
status()获取仓库状态Promise
newCommit(msg)创建新提交Promise
log(limit)显示提交历史Promise<JjCommit[]>
diff(from, to)显示差异Promise
branchCreate(name, rev?)创建分支Promise
rebase(source, dest)变基提交Promise
ReasoningBank 方法
方法描述返回值
startTrajectory(task)开始学习轨迹string(轨迹 ID)
addToTrajectory()添加最近的操作void
finalizeTrajectory(score, critique?)完成轨迹(分数:0.0-1.0)void
getSuggestion(task)获取 AI 建议JSON: DecisionSuggestion
getLearningStats()获取学习指标JSON: LearningStats
getPatterns()获取已发现的模式JSON: Pattern[]
queryTrajectories(task, limit)查找相似轨迹JSON: Trajectory[]
resetLearning()清除已学习的数据void
AgentDB 方法
方法描述返回值
getStats()获取操作统计信息JSON: Stats
getOperations(limit)获取最近的操作JjOperation[]
getUserOperations(limit)仅获取用户操作JjOperation[]
clearLog()清除操作日志void
量子安全方法(v2.3.0+)
方法描述返回值
generateQuantumFingerprint(data)生成 SHA3-512 指纹Buffer(64 字节)
verifyQuantumFingerprint(data, fp)验证指纹boolean
enableEncryption(key, pubKey?)启用 HQC-128 加密void
disableEncryption()禁用加密void
isEncryptionEnabled()检查加密状态boolean

性能特征

指标GitAgentic Jujutsu
并发提交15 ops$s350 ops$s(23 倍)
上下文切换500-1000ms50-100ms(10 倍)
冲突解决30-40% 自动87% 自动(2.5 倍)
锁等待50 min$day0 min(∞)
量子指纹不适用<1ms

最佳实践

1. 轨迹管理
// ✅ Good: Meaningful task descriptions
jj.startTrajectory('Implement user authentication with JWT');

// ❌ Bad: Vague descriptions
jj.startTrajectory('fix stuff');

// ✅ Good: Honest success scores
jj.finalizeTrajectory(0.7, 'Works but needs refactoring');

// ❌ Bad: Always 1.0
jj.finalizeTrajectory(1.0, 'Perfect!'); // Prevents learning
2. 模式识别
// ✅ Good: Let patterns emerge naturally
for (let i = 0; i < 10; i++) {
    jj.startTrajectory('Deploy feature');
    await deploy();
    jj.addToTrajectory();
    jj.finalizeTrajectory(wasSuccessful ? 0.9 : 0.5);
}

// ❌ Bad: Not recording outcomes
await deploy(); // No learning
3. 多 Agent 协调
// ✅ Good: Concurrent operations
const agents = ['agent1', 'agent2', 'agent3'];
await Promise.all(agents.map(async (agent) => {
    const jj = new JjWrapper();
    // Each agent works independently
    await jj.newCommit(`Changes by ${agent}`);
}));

// ❌ Bad: Sequential with locks
for (const agent of agents) {
    await agent.waitForLock(); // Not needed!
    await agent.commit();
}
4. 错误处理
// ✅ Good: Record failures with details
try {
    await jj.execute(['complex-operation']);
    jj.finalizeTrajectory(0.9);
} catch (err) {
    jj.finalizeTrajectory(0.3, `Failed: ${err.message}. Root cause: ...`);
}

// ❌ Bad: Silent failures
try {
    await jj.execute(['operation']);
} catch (err) {
    // No learning from failure
}

验证规则(v2.3.1+)

任务描述
  • ✅ 不能为空或仅包含空白字符
  • ✅ 最大长度:10,000 字节
  • ✅ 自动去除首尾空白
成功分数
  • ✅ 必须是有限值(不能是 NaN 或 Infinity)
  • ✅ 必须介于 0.0 和 1.0 之间(含边界值)
操作
  • ✅ 最终确定前至少要有一个操作
上下文
  • ✅ 不能为空
  • ✅ 键不能为空或仅包含空白字符
  • ✅ 键最多 1,000 字节,值最多 10,000 字节

故障排除

问题:建议置信度低
const suggestion = JSON.parse(jj.getSuggestion('new task'));

if (suggestion.confidence < 0.5) {
    // Not enough data - check learning stats
    const stats = JSON.parse(jj.getLearningStats());
    console.log(`Need more data. Current trajectories: ${stats.totalTrajectories}`);
    
    // Recommend: Record 5-10 trajectories first
}
问题:验证错误
try {
    jj.startTrajectory(''); // Empty task
} catch (err) {
    if (err.message.includes('Validation error')) {
        console.log('Invalid input:', err.message);
        // Use non-empty, meaningful task description
    }
}

try {
    jj.finalizeTrajectory(1.5); // Score > 1.0
} catch (err) {
    // Use score between 0.0 and 1.0
    jj.finalizeTrajectory(Math.max(0, Math.min(1, score)));
}
问题:未发现任何模式
const patterns = JSON.parse(jj.getPatterns());

if (patterns.length === 0) {
    // Need more trajectories with >70% success
    // Record at least 3-5 successful trajectories
}

示例

示例 1:简单学习工作流
const { JjWrapper } = require('agentic-jujutsu');

async function learnFromWork() {
    const jj = new JjWrapper();
    
    // Start tracking
    jj.startTrajectory('Add user profile feature');
    
    // Do work
    await jj.branchCreate('feature$user-profile');
    await jj.newCommit('Add user profile model');
    await jj.newCommit('Add profile API endpoints');
    await jj.newCommit('Add profile UI');
    
    // Record operations
    jj.addToTrajectory();
    
    // Finalize with result
    jj.finalizeTrajectory(0.85, 'Feature complete, minor styling issues remain');
    
    // Next time, get suggestions
    const suggestion = JSON.parse(jj.getSuggestion('Add settings page'));
    console.log('AI suggests:', suggestion.reasoning);
}
示例 2:多 Agent 集群
async function agentSwarm(taskList) {
    const agents = taskList.map((task, i) => ({
        name: `agent-${i}`,
        jj: new JjWrapper(),
        task
    }));
    
    // All agents work concurrently (no conflicts!)
    const results = await Promise.all(agents.map(async (agent) => {
        agent.jj.startTrajectory(agent.task);
        
        // Get AI suggestion
        const suggestion = JSON.parse(agent.jj.getSuggestion(agent.task));
        
        // Execute task
        const success = await executeTask(agent, suggestion);
        
        agent.jj.addToTrajectory();
        agent.jj.finalizeTrajectory(success ? 0.9 : 0.5);
        
        return { agent: agent.name, success };
    }));
    
    console.log('Results:', results);
}

相关文档

  • NPM 包:https:/$npmjs.com$package$agentic-jujutsu
  • GitHub:https:/$github.com$ruvnet$agentic-flow$tree$main$packages$agentic-jujutsu
  • 完整 README:参见软件包 README.md
  • 验证指南:docs/VALIDATION_FIXES_v2.3.1.md
  • AgentDB 指南:docs/AGENTDB_GUIDE.md

版本历史

  • v2.3.2 - 文档更新
  • v2.3.1 - 修复 ReasoningBank 的验证问题
  • v2.3.0 - 使用 @qudag$napi-core 实现抗量子安全
  • v2.1.0 - 使用 ReasoningBank 实现自学习 AI
  • v2.0.0 - 使用内置 jj 二进制文件实现零依赖安装

状态:✅ 可用于生产环境 许可证:MIT 维护状态:活跃

评论

支持 Markdown