@bernierllc/refactoring-core
v0.3.0
Published
Audit trail management with soft-delete, mandatory change reasoning, rollback support, and refactoring session tracking for agentic refactoring workflows
Readme
@bernierllc/refactoring-core
Audit trail management with soft-delete, mandatory change reasoning, rollback support, and refactoring session tracking for agentic refactoring workflows
Installation
npm install @bernierllc/refactoring-coreOverview
The refactoring-core package provides a comprehensive system for tracking and managing work item modifications with:
- Mandatory Reasoning: Every change requires explanation of WHY it was made
- Soft-Delete Operations: Safe deletion with restoration capabilities
- Refactoring Sessions: Group related changes for batch tracking and rollback
- Complete Audit Trail: Full history of all changes with attribution
- Rollback Support: Undo individual changes or entire sessions
- Risk Assessment: Track change risk levels and confidence scores
Designed specifically for agentic refactoring workflows where AI agents must document their decision-making process for human review.
Features
- ✅ Session Management: Group related changes into refactoring sessions
- ✅ Mandatory Reasoning: All changes require detailed justification
- ✅ Soft-Delete: Delete items safely with restoration support
- ✅ Change Logging: Complete audit trail with attribution
- ✅ Rollback Operations: Undo individual changes or entire sessions
- ✅ Validation: Enforce reasoning quality and context appropriateness
- ✅ Batch Operations: Soft-delete or restore multiple items atomically
- ✅ Risk Tracking: Monitor high-risk changes requiring review
- ✅ Statistics & Reporting: Comprehensive audit trail reports
Quick Start
import { RefactoringManager } from '@bernierllc/refactoring-core';
import { WorkItemManager } from '@bernierllc/work-item-core';
import { MyChangeLogStorage } from './storage';
// Initialize manager
const workItemManager = new WorkItemManager(workItemStorage);
const changeLogStorage = new MyChangeLogStorage();
const manager = new RefactoringManager(workItemManager, changeLogStorage);
// Start a refactoring session
const session = await manager.startSession({
summary: 'Consolidate duplicate authentication work items',
description: 'Merging 3 separate auth tasks into single comprehensive item',
project_id: 'proj_123',
initiated_by: 'agent:claude',
});
const sessionId = session.data.id;
// Soft-delete duplicates with reasoning
await manager.softDelete({
work_item_id: 'item_auth_1',
reason: 'Duplicate of item_auth_master - functionality covered by consolidated item',
context: {
risk_level: 'low',
future_consideration: false,
related_item_id: 'item_auth_master',
},
refactoring_session_id: sessionId,
deleted_by: 'agent:claude',
});
// Complete session
await manager.completeSession(
sessionId,
'Successfully consolidated 3 auth items into 1 comprehensive work item'
);Core Concepts
Mandatory Reasoning
All changes MUST include reasoning that explains WHY the change was made:
// ❌ INVALID - Too vague
await manager.logChange({
work_item_id: 'item_1',
change_type: 'updated',
changed_fields: ['priority'],
old_values: { priority: 5 },
new_values: { priority: 9 },
change_reason: 'updated', // Too vague!
});
// ✅ VALID - Clear explanation
await manager.logChange({
work_item_id: 'item_1',
change_type: 'updated',
changed_fields: ['priority'],
old_values: { priority: 5 },
new_values: { priority: 9 },
change_reason: 'Elevated priority because feature is now blocking v1.0 launch',
});Refactoring Sessions
Group related changes for batch operations and rollback:
// Start session
const session = await manager.startSession({
summary: 'Cleanup deprecated features',
});
// Make multiple changes
await manager.softDelete({
work_item_id: 'item_1',
reason: 'Feature deprecated in v2.0',
refactoring_session_id: session.data.id,
});
await manager.softDelete({
work_item_id: 'item_2',
reason: 'Feature deprecated in v2.0',
refactoring_session_id: session.data.id,
});
// Complete session
await manager.completeSession(session.data.id);
// Or rollback entire session if needed
await manager.rollbackSession(
session.data.id,
'Features are still needed after further review'
);Soft-Delete
Safely delete items with option to restore:
// Soft-delete with future consideration
await manager.softDelete({
work_item_id: 'item_future',
reason: 'Feature not needed for v1.0 but may be revisited for v2.0',
context: {
risk_level: 'low',
future_consideration: true,
note_to_assignee: 'Good idea but out of scope - save for future sprint',
},
});
// Later, query items marked for future consideration
const futureItems = await manager.getDeletedItems({
future_consideration: true,
});
// Restore if needed
await manager.restore({
work_item_id: 'item_future',
reason: 'Including in v1.0 after all based on customer feedback',
});API Reference
RefactoringManager
Main class for refactoring operations.
Constructor
constructor(
workItemManager: WorkItemManager,
changeLogStorage: ChangeLogStorage,
versionStore?: VersionStore<WorkItem>,
config?: RefactoringConfig
)Parameters:
workItemManager: Interface to work item storage (from @bernierllc/work-item-core)changeLogStorage: Interface to change log storage (implement yourself)versionStore: Optional version store for snapshots (from @bernierllc/version-store)config: Optional configuration
Configuration Options:
interface RefactoringConfig {
minReasonLength?: number; // Default: 20
softDeleteRetentionDays?: number; // Default: 30
strictReasoning?: boolean; // Default: true
autoVersionSnapshot?: boolean; // Default: true
requireReviewHighRisk?: boolean; // Default: false
}Session Operations
startSession
Start a new refactoring session.
async startSession(input: StartSessionInput): Promise<RefactoringResult<RefactoringSession>>Input:
interface StartSessionInput {
summary: string; // REQUIRED - Overall goal
description?: string;
planning_session_id?: string;
project_id?: string;
initiated_by?: string;
metadata?: Record<string, unknown>;
}completeSession
Mark session as complete.
async completeSession(
sessionId: string,
summary?: string
): Promise<RefactoringResult<RefactoringSession>>getSession
Retrieve session details.
async getSession(
sessionId: string,
include_changes?: boolean
): Promise<RefactoringResult<RefactoringSession>>rollbackSession
Rollback entire session.
async rollbackSession(
sessionId: string,
reason: string
): Promise<RefactoringResult<RollbackResult>>Soft-Delete Operations
softDelete
Soft-delete work item with reasoning.
async softDelete(input: SoftDeleteInput): Promise<RefactoringResult<void>>Input:
interface SoftDeleteInput {
work_item_id: string;
reason: string; // REQUIRED - MANDATORY reasoning
context?: DeletionContext;
refactoring_session_id?: string;
deleted_by?: string;
}restore
Restore soft-deleted work item.
async restore(input: RestoreInput): Promise<RefactoringResult<void>>Input:
interface RestoreInput {
work_item_id: string;
reason: string; // REQUIRED - WHY restoring
refactoring_session_id?: string;
restored_by?: string;
}Change Logging
logChange
Log a work item change with reasoning.
async logChange(input: LogChangeInput): Promise<RefactoringResult<WorkItemChangeLog>>Input:
interface LogChangeInput {
work_item_id: string;
change_type: 'created' | 'updated' | 'deleted' | 'restored';
changed_fields: string[];
old_values?: Record<string, unknown>;
new_values?: Record<string, unknown>;
change_reason: string; // REQUIRED - MANDATORY reasoning
change_context?: ChangeContext;
changed_by?: string;
refactoring_session_id?: string;
is_refactor_change?: boolean;
}getChangeHistory
Get all changes for a work item.
async getChangeHistory(
workItemId: string,
include_rolled_back?: boolean
): Promise<RefactoringResult<WorkItemChangeLog[]>>Rollback Operations
canRollback
Check if a change can be rolled back.
async canRollback(
changeId: string
): Promise<RefactoringResult<ValidationResult>>rollbackChange
Rollback a single change.
async rollbackChange(
changeId: string,
reason: string
): Promise<RefactoringResult<void>>Query & Reporting
getDeletedItems
Get soft-deleted work items.
async getDeletedItems(
filters: DeletedItemFilters
): Promise<RefactoringResult<SoftDeletableWorkItem[]>>getAuditTrail
Get comprehensive audit trail report.
async getAuditTrail(
projectId?: string,
dateRange?: { from: Date; to: Date }
): Promise<RefactoringResult<AuditTrailReport>>getHighRiskChanges
Get changes marked as high risk.
async getHighRiskChanges(
filters?: ChangeLogFilters
): Promise<RefactoringResult<WorkItemChangeLog[]>>Batch Operations
softDeleteBatch
Soft-delete multiple items with shared reasoning.
async softDeleteBatch(
workItemIds: string[],
reason: string,
context?: DeletionContext
): Promise<RefactoringResult<void>>restoreBatch
Restore multiple items with shared reasoning.
async restoreBatch(
workItemIds: string[],
reason: string
): Promise<RefactoringResult<void>>Validation Functions
Standalone validation functions for reasoning and context:
validateReasoning
import { validateReasoning } from '@bernierllc/refactoring-core';
const validation = validateReasoning(
'Consolidating duplicate features',
'updated',
20, // minLength
true // strict
);
if (!validation.is_valid) {
console.error('Validation errors:', validation.errors);
}validateDeletionContext
import { validateDeletionContext } from '@bernierllc/refactoring-core';
const validation = validateDeletionContext({
risk_level: 'high',
note_to_assignee: 'Removing due to security concerns',
});
if (validation.warnings.length > 0) {
console.warn('Warnings:', validation.warnings);
}Storage Interface
Implement the ChangeLogStorage interface for your database:
import { ChangeLogStorage } from '@bernierllc/refactoring-core';
class PrismaChangeLogStorage implements ChangeLogStorage {
async saveChange(change: WorkItemChangeLog): Promise<void> {
await prisma.changeLog.create({ data: change });
}
async getChange(id: string): Promise<WorkItemChangeLog | null> {
return await prisma.changeLog.findUnique({ where: { id } });
}
// Implement other methods...
}Examples
Complete Refactoring Workflow
// Start session
const session = await manager.startSession({
summary: 'Consolidate authentication work items',
project_id: 'proj_auth',
initiated_by: 'agent:claude',
});
const sessionId = session.data.id;
// Log updates
await manager.logChange({
work_item_id: 'item_auth_master',
change_type: 'updated',
changed_fields: ['description', 'requirements'],
old_values: { description: 'Basic auth' },
new_values: { description: 'Comprehensive authentication system' },
change_reason: 'Merged requirements from 3 duplicate items into master',
refactoring_session_id: sessionId,
changed_by: 'agent:claude',
});
// Soft-delete duplicates
await manager.softDelete({
work_item_id: 'item_auth_1',
reason: 'Duplicate - merged into item_auth_master',
context: {
risk_level: 'low',
related_item_id: 'item_auth_master',
},
refactoring_session_id: sessionId,
deleted_by: 'agent:claude',
});
// Complete session
await manager.completeSession(
sessionId,
'Consolidated 3 auth items into 1 comprehensive work item'
);
// Get audit trail
const audit = await manager.getAuditTrail('proj_auth');
console.log(`Total changes: ${audit.data.total_changes}`);
console.log(`Sessions: ${audit.data.sessions.length}`);Rollback Workflow
// If human reviewer decides consolidation was wrong
const rollback = await manager.rollbackSession(
sessionId,
'Consolidation removed important context - restoring for review'
);
if (rollback.success) {
console.log(`Rolled back ${rollback.data.changes_rolled_back} changes`);
console.log(`Restored ${rollback.data.work_items_restored} work items`);
}High-Risk Change Tracking
// Log high-risk change
await manager.logChange({
work_item_id: 'item_critical',
change_type: 'updated',
changed_fields: ['security_requirements'],
old_values: { security_requirements: 'basic' },
new_values: { security_requirements: 'none' },
change_reason: 'Removing security requirements based on new architecture',
change_context: {
risk_level: 'high',
agent_confidence: 0.6,
review_required: true,
note_to_assignee: 'Please review - significant change to security posture',
},
changed_by: 'agent:claude',
});
// Query high-risk changes
const highRisk = await manager.getHighRiskChanges();
console.log(`Found ${highRisk.data.length} high-risk changes requiring review`);Integration Status
- Logger: Not applicable (core utility package)
- Docs-Suite: Ready - Complete API documentation with examples
- NeverHub: Not applicable (core utility package)
Dependencies
- None (pure TypeScript implementation)
Dev Dependencies
- TypeScript 5.0+
- Jest for testing
- ESLint for linting
Contributing
This package follows strict quality standards:
- 90%+ test coverage required
- Zero TypeScript errors (strict mode)
- Zero linting errors
- Comprehensive documentation
License
Copyright (c) 2025 Bernier LLC
This file is licensed to the client under a limited-use license. The client may use and modify this code only within the scope of the project it was delivered for. Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
See Also
- @bernierllc/work-item-core - Work item CRUD operations
- @bernierllc/version-store - Version history snapshots
- @bernierllc/planning-session-core - Planning session management
