agentic-jujutsu

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Agentic Jujutsu - AI Agent Version Control

Agentic Jujutsu - AI Agent版本控制系统

Quantum-ready, self-learning version control designed for multiple AI agents working simultaneously without conflicts.
专为多个AI Agent无冲突协同工作设计的、支持抗量子攻击的自学习版本控制系统。

When to Use This Skill

何时使用该工具

Use agentic-jujutsu when you need:
  • ✅ Multiple AI agents modifying code simultaneously
  • ✅ Lock-free version control (23x faster than Git)
  • ✅ Self-learning AI that improves from experience
  • ✅ Quantum-resistant security for future-proof protection
  • ✅ Automatic conflict resolution (87% success rate)
  • ✅ Pattern recognition and intelligent suggestions
  • ✅ Multi-agent coordination without blocking
当你需要以下功能时,使用agentic-jujutsu
  • ✅ 多个AI Agent同时修改代码
  • ✅ 无锁版本控制(比Git快23倍)
  • ✅ 从经验中自我优化的AI系统
  • ✅ 抗量子攻击的安全防护,面向未来需求
  • ✅ 自动冲突解决(成功率87%)
  • ✅ 模式识别与智能建议
  • ✅ 多Agent协同无需阻塞

Quick Start

快速开始

Installation

安装

bash
npx agentic-jujutsu
bash
npx agentic-jujutsu

Basic Usage

基本使用

javascript
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}`);
javascript
const { JjWrapper } = require('agentic-jujutsu');

const jj = new JjWrapper();

// 基本操作
await jj.status();
await jj.newCommit('Add feature');
await jj.log(10);

// 自学习轨迹
const id = jj.startTrajectory('Implement authentication');
await jj.branchCreate('feature/auth');
await jj.newCommit('Add auth');
jj.addToTrajectory();
jj.finalizeTrajectory(0.9, 'Clean implementation');

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

Core Capabilities

核心功能

1. Self-Learning with ReasoningBank

1. 基于ReasoningBank的自学习

Track operations, learn patterns, and get intelligent suggestions:
javascript
// 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) + '%');
Validation (v2.3.1):
  • ✅ Tasks must be non-empty (max 10KB)
  • ✅ Success scores must be 0.0-1.0
  • ✅ Must have operations before finalizing
  • ✅ Contexts cannot be empty
追踪操作、学习模式并获取智能建议:
javascript
// 启动学习轨迹
const trajectoryId = jj.startTrajectory('Deploy to production');

// 执行操作(自动追踪)
await jj.execute(['git', 'push', 'origin', 'main']);
await jj.branchCreate('release/v1.0');
await jj.newCommit('Release v1.0');

// 将操作记录到轨迹
jj.addToTrajectory();

// 用成功分数(0.0-1.0)和评价完成轨迹
jj.finalizeTrajectory(0.95, 'Deployment successful, no issues');

// 后续:获取类似任务的AI驱动建议
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. Pattern Discovery

2. 模式发现

Automatically identify successful operation sequences:
javascript
// 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)}%`);
});
自动识别成功的操作序列:
javascript
// 获取已发现的模式
const patterns = JSON.parse(jj.getPatterns());

patterns.forEach(pattern => {
    console.log(`Pattern: ${pattern.name}`);
    console.log(`  成功率: ${(pattern.successRate * 100).toFixed(1)}%`);
    console.log(`  使用次数: ${pattern.observationCount}`);
    console.log(`  操作序列: ${pattern.operationSequence.join(' → ')}`);
    console.log(`  置信度: ${(pattern.confidence * 100).toFixed(1)}%`);
});

3. Learning Statistics

3. 学习统计

Track improvement over time:
javascript
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)}%`);
追踪随时间的优化情况:
javascript
const stats = JSON.parse(jj.getLearningStats());

console.log('学习进度:');
console.log(`  总轨迹数: ${stats.totalTrajectories}`);
console.log(`  发现的模式数: ${stats.totalPatterns}`);
console.log(`  平均成功率: ${(stats.avgSuccessRate * 100).toFixed(1)}%`);
console.log(`  优化率: ${(stats.improvementRate * 100).toFixed(1)}%`);
console.log(`  预测准确率: ${(stats.predictionAccuracy * 100).toFixed(1)}%`);

4. Multi-Agent Coordination

4. 多Agent协同

Multiple agents work concurrently without conflicts:
javascript
// 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`);
多个Agent可无冲突并发工作:
javascript
// Agent 1: 开发Agent
const dev = new JjWrapper();
dev.startTrajectory('Implement feature');
await dev.newCommit('Add feature X');
dev.addToTrajectory();
dev.finalizeTrajectory(0.85);

// Agent 2: 评审Agent(从Agent 1学习)
const reviewer = new JjWrapper();
const suggestion = JSON.parse(reviewer.getSuggestion('Review feature X'));

if (suggestion.confidence > 0.7) {
    console.log('高置信度方案:', suggestion.reasoning);
}

// Agent 3: 测试Agent(受益于前两者的经验)
const tester = new JjWrapper();
const similar = JSON.parse(tester.queryTrajectories('test feature', 5));
console.log(`找到${similar.length}种类似测试方案`);

5. Quantum-Resistant Security (v2.3.0+)

5. 抗量子安全(v2.3.0+)

Fast integrity verification with quantum-resistant cryptography:
javascript
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);
基于抗量子密码学的快速完整性验证:
javascript
const { generateQuantumFingerprint, verifyQuantumFingerprint } = require('agentic-jujutsu');

// 生成SHA3-512指纹(符合NIST FIPS 202标准)
const data = Buffer.from('commit-data');
const fingerprint = generateQuantumFingerprint(data);
console.log('Fingerprint:', fingerprint.toString('hex'));

// 验证完整性(耗时<1ms)
const isValid = verifyQuantumFingerprint(data, fingerprint);
console.log('Valid:', isValid);

// 为轨迹启用HQC-128加密
const crypto = require('crypto');
const key = crypto.randomBytes(32).toString('base64');
jj.enableEncryption(key);

6. Operation Tracking with AgentDB

6. 基于AgentDB的操作追踪

Automatic tracking of all operations:
javascript
// 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);
自动追踪所有操作:
javascript
// 操作会被自动追踪
await jj.status();
await jj.newCommit('Fix bug');
await jj.rebase('main');

// 获取操作统计
const stats = JSON.parse(jj.getStats());
console.log(`总操作数: ${stats.total_operations}`);
console.log(`成功率: ${(stats.success_rate * 100).toFixed(1)}%`);
console.log(`平均耗时: ${stats.avg_duration_ms.toFixed(2)}ms`);

// 查询最近的操作
const ops = jj.getOperations(10);
ops.forEach(op => {
    console.log(`${op.operationType}: ${op.command}`);
    console.log(`  耗时: ${op.durationMs}ms, 成功: ${op.success}`);
});

// 获取用户操作(排除快照)
const userOps = jj.getUserOperations(20);

Advanced Use Cases

高级使用场景

Use Case 1: Adaptive Workflow Optimization

场景1:自适应工作流优化

Learn and improve deployment workflows:
javascript
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'
    );
}
学习并优化部署工作流:
javascript
async function adaptiveDeployment(jj, environment) {
    // 基于过往部署记录获取AI建议
    const suggestion = JSON.parse(jj.getSuggestion(`Deploy to ${environment}`));
    
    console.log(`部署方案置信度: ${(suggestion.confidence * 100).toFixed(0)}%`);
    console.log(`预计耗时: ${suggestion.estimatedDurationMs}ms`);
    
    // 开始追踪
    jj.startTrajectory(`Deploy to ${environment}`);
    
    // 执行推荐的操作
    for (const op of suggestion.recommendedOperations) {
        console.log(`执行: ${op}`);
        await executeOperation(op);
    }
    
    jj.addToTrajectory();
    
    // 记录结果
    const success = await verifyDeployment();
    jj.finalizeTrajectory(
        success ? 0.95 : 0.5,
        success ? 'Deployment successful' : 'Issues detected'
    );
}

Use Case 2: Multi-Agent Code Review

场景2:多Agent代码评审

Coordinate review across multiple agents:
javascript
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;
}
协调多个Agent完成代码评审:
javascript
async function coordinatedReview(agents) {
    const reviews = await Promise.all(agents.map(async (agent) => {
        const jj = new JjWrapper();
        
        // 启动评审轨迹
        jj.startTrajectory(`Review by ${agent.name}`);
        
        // 获取评审方案的AI建议
        const suggestion = JSON.parse(jj.getSuggestion('Code 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 };
    }));
    
    // 汇总所有Agent的学习成果
    return reviews;
}

Use Case 3: Error Pattern Detection

场景3:错误模式检测

Learn from failures to prevent future issues:
javascript
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;
    }
}
从失败中学习以预防未来问题:
javascript
async function smartMerge(jj, branch) {
    // 查询类似的合并尝试
    const similar = JSON.parse(jj.queryTrajectories(`merge ${branch}`, 10));
    
    // 分析过往失败案例
    const failures = similar.filter(t => t.successScore < 0.5);
    
    if (failures.length > 0) {
        console.log('⚠️ 过往类似合并存在失败案例:');
        failures.forEach(f => {
            if (f.critique) {
                console.log(`  - ${f.critique}`);
            }
        });
    }
    
    // 获取AI推荐方案
    const suggestion = JSON.parse(jj.getSuggestion(`merge ${branch}`));
    
    if (suggestion.confidence < 0.7) {
        console.log('⚠️ 方案置信度较低,推荐步骤:');
        suggestion.recommendedOperations.forEach(op => console.log(`  - ${op}`));
    }
    
    // 追踪合并操作
    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;
    }
}

Use Case 4: Continuous Learning Loop

场景4:持续学习循环

Implement a self-improving agent:
javascript
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');
}
实现自我优化的Agent:
javascript
class SelfImprovingAgent {
    constructor() {
        this.jj = new JjWrapper();
    }
    
    async performTask(taskDescription) {
        // 获取AI建议
        const suggestion = JSON.parse(this.jj.getSuggestion(taskDescription));
        
        console.log(`任务: ${taskDescription}`);
        console.log(`AI置信度: ${(suggestion.confidence * 100).toFixed(1)}%`);
        console.log(`预计成功率: ${(suggestion.expectedSuccessRate * 100).toFixed(1)}%`);
        
        // 启动轨迹
        this.jj.startTrajectory(taskDescription);
        
        // 按推荐方案执行
        const startTime = Date.now();
        let success = false;
        
        try {
            for (const op of suggestion.recommendedOperations) {
                await this.execute(op);
            }
            success = true;
        } catch (err) {
            console.error('任务失败:', err.message);
        }
        
        const duration = Date.now() - startTime;
        
        // 记录学习成果
        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`
        );
        
        // 检查优化情况
        const stats = JSON.parse(this.jj.getLearningStats());
        console.log(`优化率: ${(stats.improvementRate * 100).toFixed(1)}%`);
        
        return success;
    }
    
    async execute(operation) {
        // 操作执行逻辑
    }
}

// 使用示例
const agent = new SelfImprovingAgent();

// Agent会随时间不断优化
for (let i = 1; i <= 10; i++) {
    console.log(`\n--- 第${i}次尝试 ---`);
    await agent.performTask('Deploy application');
}

API Reference

API参考

Core Methods

核心方法

MethodDescriptionReturns
new JjWrapper()
Create wrapper instanceJjWrapper
status()
Get repository statusPromise<JjResult>
newCommit(msg)
Create new commitPromise<JjResult>
log(limit)
Show commit historyPromise<JjCommit[]>
diff(from, to)
Show differencesPromise<JjDiff>
branchCreate(name, rev?)
Create branchPromise<JjResult>
rebase(source, dest)
Rebase commitsPromise<JjResult>
方法描述返回值
new JjWrapper()
创建包装器实例JjWrapper
status()
获取仓库状态Promise<JjResult>
newCommit(msg)
创建新提交Promise<JjResult>
log(limit)
显示提交历史Promise<JjCommit[]>
diff(from, to)
显示差异Promise<JjDiff>
branchCreate(name, rev?)
创建分支Promise<JjResult>
rebase(source, dest)
变基提交Promise<JjResult>

ReasoningBank Methods

ReasoningBank方法

MethodDescriptionReturns
startTrajectory(task)
Begin learning trajectorystring (trajectory ID)
addToTrajectory()
Add recent operationsvoid
finalizeTrajectory(score, critique?)
Complete trajectory (score: 0.0-1.0)void
getSuggestion(task)
Get AI recommendationJSON: DecisionSuggestion
getLearningStats()
Get learning metricsJSON: LearningStats
getPatterns()
Get discovered patternsJSON: Pattern[]
queryTrajectories(task, limit)
Find similar trajectoriesJSON: Trajectory[]
resetLearning()
Clear learned datavoid
方法描述返回值
startTrajectory(task)
启动学习轨迹字符串(轨迹ID)
addToTrajectory()
添加近期操作
finalizeTrajectory(score, critique?)
完成轨迹(分数范围0.0-1.0)
getSuggestion(task)
获取AI推荐方案JSON格式:DecisionSuggestion
getLearningStats()
获取学习指标JSON格式:LearningStats
getPatterns()
获取已发现的模式JSON格式:Pattern[]
queryTrajectories(task, limit)
查找类似轨迹JSON格式:Trajectory[]
resetLearning()
清除学习数据

AgentDB Methods

AgentDB方法

MethodDescriptionReturns
getStats()
Get operation statisticsJSON: Stats
getOperations(limit)
Get recent operationsJjOperation[]
getUserOperations(limit)
Get user operations onlyJjOperation[]
clearLog()
Clear operation logvoid
方法描述返回值
getStats()
获取操作统计JSON格式:Stats
getOperations(limit)
获取近期操作JjOperation[]
getUserOperations(limit)
仅获取用户操作JjOperation[]
clearLog()
清除操作日志

Quantum Security Methods (v2.3.0+)

量子安全方法(v2.3.0+)

MethodDescriptionReturns
generateQuantumFingerprint(data)
Generate SHA3-512 fingerprintBuffer (64 bytes)
verifyQuantumFingerprint(data, fp)
Verify fingerprintboolean
enableEncryption(key, pubKey?)
Enable HQC-128 encryptionvoid
disableEncryption()
Disable encryptionvoid
isEncryptionEnabled()
Check encryption statusboolean
方法描述返回值
generateQuantumFingerprint(data)
生成SHA3-512指纹Buffer(64字节)
verifyQuantumFingerprint(data, fp)
验证指纹布尔值
enableEncryption(key, pubKey?)
启用HQC-128加密
disableEncryption()
禁用加密
isEncryptionEnabled()
检查加密状态布尔值

Performance Characteristics

性能特性

MetricGitAgentic Jujutsu
Concurrent commits15 ops/s350 ops/s (23x)
Context switching500-1000ms50-100ms (10x)
Conflict resolution30-40% auto87% auto (2.5x)
Lock waiting50 min/day0 min (∞)
Quantum fingerprintsN/A<1ms
指标GitAgentic Jujutsu
并发提交15次/秒350次/秒(快23倍)
上下文切换500-1000ms50-100ms(快10倍)
自动冲突解决成功率30-40%87%(高2.5倍)
锁等待时间每天50分钟0分钟(无锁)
量子指纹生成不支持<1ms

Best Practices

最佳实践

1. Trajectory Management

1. 轨迹管理

javascript
// ✅ 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
javascript
// ✅ 推荐:使用有意义的任务描述
jj.startTrajectory('Implement user authentication with JWT');

// ❌ 不推荐:模糊的描述
jj.startTrajectory('fix stuff');

// ✅ 推荐:如实记录成功分数
jj.finalizeTrajectory(0.7, '功能可用但需要重构');

// ❌ 不推荐:始终设为1.0
jj.finalizeTrajectory(1.0, 'Perfect!'); // 会阻碍学习

2. Pattern Recognition

2. 模式识别

javascript
// ✅ 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
javascript
// ✅ 推荐:让模式自然形成
for (let i = 0; i < 10; i++) {
    jj.startTrajectory('Deploy feature');
    await deploy();
    jj.addToTrajectory();
    jj.finalizeTrajectory(wasSuccessful ? 0.9 : 0.5);
}

// ❌ 不推荐:不记录结果
await deploy(); // 无法积累学习数据

3. Multi-Agent Coordination

3. 多Agent协同

javascript
// ✅ 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();
}
javascript
// ✅ 推荐:并发操作
const agents = ['agent1', 'agent2', 'agent3'];
await Promise.all(agents.map(async (agent) => {
    const jj = new JjWrapper();
    // 每个Agent独立工作
    await jj.newCommit(`Changes by ${agent}`);
}));

// ❌ 不推荐:带锁的串行操作
for (const agent of agents) {
    await agent.waitForLock(); // 完全没必要!
    await agent.commit();
}

4. Error Handling

4. 错误处理

javascript
// ✅ 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
}
javascript
// ✅ 推荐:详细记录失败信息
try {
    await jj.execute(['complex-operation']);
    jj.finalizeTrajectory(0.9);
} catch (err) {
    jj.finalizeTrajectory(0.3, `失败原因: ${err.message}. 根本问题: ...`);
}

// ❌ 不推荐:静默失败
try {
    await jj.execute(['operation']);
} catch (err) {
    // 未从失败中学习
}

Validation Rules (v2.3.1+)

验证规则(v2.3.1+)

Task Description

任务描述

  • ✅ Cannot be empty or whitespace-only
  • ✅ Maximum length: 10,000 bytes
  • ✅ Automatically trimmed
  • ✅ 不能为空或仅含空白字符
  • ✅ 最大长度:10,000字节
  • ✅ 自动去除首尾空白

Success Score

成功分数

  • ✅ Must be finite (not NaN or Infinity)
  • ✅ Must be between 0.0 and 1.0 (inclusive)
  • ✅ 必须是有限数值(不能是NaN或无穷大)
  • ✅ 必须在0.0到1.0之间(包含边界值)

Operations

操作

  • ✅ Must have at least one operation before finalizing
  • ✅ 完成轨迹前必须至少执行一个操作

Context

上下文

  • ✅ Cannot be empty
  • ✅ Keys cannot be empty or whitespace-only
  • ✅ Keys max 1,000 bytes, values max 10,000 bytes
  • ✅ 不能为空
  • ✅ 键名不能为空或仅含空白字符
  • ✅ 键名最大1,000字节,值最大10,000字节

Troubleshooting

故障排查

Issue: Low Confidence Suggestions

问题:建议置信度低

javascript
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
}
javascript
const suggestion = JSON.parse(jj.getSuggestion('new task'));

if (suggestion.confidence < 0.5) {
    // 数据不足 - 检查学习统计
    const stats = JSON.parse(jj.getLearningStats());
    console.log(`需要更多数据,当前轨迹数: ${stats.totalTrajectories}`);
    
    // 建议:先记录5-10条轨迹
}

Issue: Validation Errors

问题:验证错误

javascript
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)));
}
javascript
try {
    jj.startTrajectory(''); // 空任务描述
} catch (err) {
    if (err.message.includes('Validation error')) {
        console.log('输入无效:', err.message);
        // 使用非空、有意义的任务描述
    }
}

try {
    jj.finalizeTrajectory(1.5); // 分数超出1.0
} catch (err) {
    // 将分数限制在0.0-1.0之间
    jj.finalizeTrajectory(Math.max(0, Math.min(1, score)));
}

Issue: No Patterns Discovered

问题:未发现任何模式

javascript
const patterns = JSON.parse(jj.getPatterns());

if (patterns.length === 0) {
    // Need more trajectories with >70% success
    // Record at least 3-5 successful trajectories
}
javascript
const patterns = JSON.parse(jj.getPatterns());

if (patterns.length === 0) {
    // 需要更多成功率>70%的轨迹
    // 至少记录3-5条成功轨迹
}

Examples

示例

Example 1: Simple Learning Workflow

示例1:简单学习工作流

javascript
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);
}
javascript
const { JjWrapper } = require('agentic-jujutsu');

async function learnFromWork() {
    const jj = new JjWrapper();
    
    // 开始追踪
    jj.startTrajectory('Add user profile feature');
    
    // 执行工作
    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');
    
    // 记录操作
    jj.addToTrajectory();
    
    // 记录结果
    jj.finalizeTrajectory(0.85, '功能完成,仍有少量样式问题');
    
    // 后续可获取建议
    const suggestion = JSON.parse(jj.getSuggestion('Add settings page'));
    console.log('AI建议:', suggestion.reasoning);
}

Example 2: Multi-Agent Swarm

示例2:多Agent集群

javascript
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);
}
javascript
async function agentSwarm(taskList) {
    const agents = taskList.map((task, i) => ({
        name: `agent-${i}`,
        jj: new JjWrapper(),
        task
    }));
    
    // 所有Agent并发工作(无冲突!)
    const results = await Promise.all(agents.map(async (agent) => {
        agent.jj.startTrajectory(agent.task);
        
        // 获取AI建议
        const suggestion = JSON.parse(agent.jj.getSuggestion(agent.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);
}

Related Documentation

相关文档

Version History

版本历史

  • v2.3.2 - Documentation updates
  • v2.3.1 - Validation fixes for ReasoningBank
  • v2.3.0 - Quantum-resistant security with @qudag/napi-core
  • v2.1.0 - Self-learning AI with ReasoningBank
  • v2.0.0 - Zero-dependency installation with embedded jj binary

Status: ✅ Production Ready License: MIT Maintained: Active
  • v2.3.2 - 文档更新
  • v2.3.1 - 修复ReasoningBank的验证问题
  • v2.3.0 - 集成@qudag/napi-core实现抗量子安全
  • v2.1.0 - 新增基于ReasoningBank的自学习AI
  • v2.0.0 - 零依赖安装,内置jj二进制文件

状态: ✅ 生产可用 许可证: MIT 维护状态: 持续维护