Files
CxIDE/Agent/AgentMemory.swift
T
cx-git-agent c118996746 feat: CxIDE v1 — native macOS SwiftUI IDE with agentic AI assistant
- SwiftUI macOS app with C++17 code analysis engine (ObjC++ bridge)
- Agentic AI loop: LLM plans → tool calls → execution → feedback loop
- 15 agent tools: file ops, terminal, git, xcode build, code intel
- 7 persistent terminal tools with background session management
- Chat sidebar with agent step rendering and auto-apply
- NVIDIA NIM API integration (Llama 3.3 70B default)
- OpenAI tool_calls format with prompt-based fallback
- Code editor with syntax highlighting and multi-tab support
- File tree, console view, terminal view
- Git integration and workspace management
2026-04-21 16:05:52 -05:00

201 lines
5.5 KiB
Swift

// AgentMemory.swift
// CxSwiftAgent Cross-turn context memory for the coding agent.
//
// Mirrors CxCodingAgent::Memory (Perl) tracks file accesses,
// decisions, tasks, symbols, errors, and tool usage across turns.
import Foundation
actor AgentMemory {
private(set) var turn: Int = 0
private(set) var sessionId: String
private var fileContext: [String: FileAccess] = [:]
private var decisions: [Decision] = []
private var tasks: [AgentTask] = []
private var symbols: [String: SymbolInfo] = [:]
private var errors: [ErrorRecord] = []
private var turnSummaries: [TurnSummary] = []
private var toolUsage: [String: ToolUsageStats] = [:]
private let maxEntries = 50
struct FileAccess: Sendable {
let path: String
let action: String
let turn: Int
let summary: String
}
struct Decision: Sendable {
let decision: String
let reason: String
let turn: Int
}
struct AgentTask: Sendable {
let task: String
var status: String
let turn: Int
var result: String?
}
struct SymbolInfo: Sendable {
let name: String
let type: String
let file: String
let turn: Int
}
struct ErrorRecord: Sendable {
let error: String
let resolution: String?
let turn: Int
}
struct TurnSummary: Sendable {
let role: String
let content: String
let turn: Int
let toolCalls: Int
}
struct ToolUsageStats: Sendable {
var calls: Int = 0
var errors: Int = 0
var lastTurn: Int = 0
var totalMs: Double = 0
}
init(sessionId: String? = nil) {
self.sessionId = sessionId ?? UUID().uuidString.lowercased().replacingOccurrences(of: "-", with: "").prefix(16).description
}
// MARK: - Turn Management
func nextTurn() -> Int {
turn += 1
return turn
}
// MARK: - File Context
func recordFileAccess(path: String, action: String, summary: String = "") {
fileContext[path] = FileAccess(path: path, action: action, turn: turn, summary: summary)
}
func recentFiles(limit: Int = 10) -> [FileAccess] {
Array(fileContext.values.sorted { $0.turn > $1.turn }.prefix(limit))
}
func hasFileContext(_ path: String) -> Bool {
fileContext[path] != nil
}
var fileCount: Int { fileContext.count }
// MARK: - Decisions
func recordDecision(_ decision: String, reason: String) {
decisions.append(Decision(decision: decision, reason: reason, turn: turn))
compact(&decisions)
}
// MARK: - Tasks
func startTask(_ task: String) -> Int {
let index = tasks.count
tasks.append(AgentTask(task: task, status: "in_progress", turn: turn))
return index
}
func completeTask(_ index: Int, result: String) {
guard index < tasks.count else { return }
tasks[index].status = "completed"
tasks[index].result = result
}
func failTask(_ index: Int, error: String) {
guard index < tasks.count else { return }
tasks[index].status = "failed"
tasks[index].result = error
}
var activeTasks: [AgentTask] {
tasks.filter { $0.status == "in_progress" }
}
// MARK: - Symbols
func recordSymbol(name: String, type: String, file: String) {
symbols[name] = SymbolInfo(name: name, type: type, file: file, turn: turn)
}
// MARK: - Errors
func recordError(_ error: String, resolution: String? = nil) {
errors.append(ErrorRecord(error: error, resolution: resolution, turn: turn))
compact(&errors)
}
// MARK: - Tool Usage
func recordToolCall(name: String, durationMs: Double, success: Bool) {
var stats = toolUsage[name] ?? ToolUsageStats()
stats.calls += 1
if !success { stats.errors += 1 }
stats.lastTurn = turn
stats.totalMs += durationMs
toolUsage[name] = stats
}
// MARK: - Context Generation
func generateContext() -> String {
var parts: [String] = []
parts.append("Session: \(sessionId) | Turn: \(turn)")
if !fileContext.isEmpty {
let recent = recentFiles(limit: 5)
let files = recent.map { "\($0.action): \($0.path)" }.joined(separator: ", ")
parts.append("Recent files: \(files)")
}
if !activeTasks.isEmpty {
let active = activeTasks.map(\.task).joined(separator: ", ")
parts.append("Active tasks: \(active)")
}
if let lastErr = errors.last {
parts.append("Last error: \(lastErr.error)")
}
if !decisions.isEmpty {
let recent = decisions.suffix(3).map(\.decision).joined(separator: "; ")
parts.append("Recent decisions: \(recent)")
}
return parts.joined(separator: " | ")
}
func toDict() -> [String: Any] {
[
"session_id": sessionId,
"turn": turn,
"file_count": fileContext.count,
"decision_count": decisions.count,
"task_count": tasks.count,
"active_tasks": activeTasks.count,
"symbol_count": symbols.count,
"error_count": errors.count,
"tool_usage": toolUsage.mapValues { ["calls": $0.calls, "errors": $0.errors] },
]
}
// MARK: - Private
private func compact<T>(_ array: inout [T]) {
if array.count > maxEntries {
array = Array(array.suffix(maxEntries))
}
}
}