Coclico is an enterprise-grade Windows system management platform that combines real-time monitoring, workflow automation, deep system cleaning, and fully local artificial intelligence into a single, self-contained desktop application. Built on .NET 10 with the C# preview language version and the WPF-UI 4.2 design system, Coclico operates entirely offline -- executing all AI inference, telemetry analysis, and autonomous optimization on the local machine without any cloud dependency.
At its core, Coclico implements a continuous autonomous loop:
Observe (telemetry collection via DynamicTracer with EWMA and Isolation Forest anomaly detection),
Analyze (LLM-based cognitive decision-making backed by Roslyn AST analysis),
Act (AutoPatcher for validated code modifications, QoS priority adjustments), and
Validate (Digital Twin simulation ensuring cyclomatic complexity never increases).
This loop executes every 30 seconds through a lock-free 3-stage pipeline built on
System.Threading.Channels.
Version 1.0.4 (March 2026) represents a fully operational release across all architectural phases: dual-context LLamaSharp inference, Roslyn-powered source analysis with Halstead metrics, DPAPI-encrypted rollback snapshots, enterprise security policy enforcement, NDJSON audit trails with AI decision traceability, and a 28-node visual workflow automation editor.
Coclico addresses the need for a comprehensive, privacy-first Windows system management tool that consolidates capabilities typically spread across dozens of separate utilities: process monitoring, application inventory, automated workflows, disk cleanup, memory optimization, software installation, and AI-assisted system administration.
record types for thread-safe, allocation-efficient data flow.The application UI ships with 10 runtime-switchable localizations: French, English, German, Spanish, Italian, Japanese, Korean, Portuguese, Russian, and Chinese. Language changes take effect immediately without restarting the application.
| Layer | Technology | Version | Purpose |
|---|---|---|---|
| Runtime | .NET | 10.0 | Application framework, TieredPGO, ConcurrentGC |
| Language | C# | preview | Primary constructors, collection expressions, pattern matching |
| UI Framework | WPF + WPF-UI | 4.2.0 | Fluent Design system, dark/light themes |
| MVVM Toolkit | CommunityToolkit.Mvvm | 8.4.0 | ObservableObject, RelayCommand, source generators |
| Local AI | LLamaSharp + Backend.Cpu | 0.26.0 | GGUF model inference, dual-context isolation |
| AST Analysis | Microsoft.CodeAnalysis.CSharp | 4.12.0 | Roslyn syntax tree parsing, CC computation |
| Reactive | System.Reactive | 6.0.1 | Observable streams for ResourceGuard polling |
| Logging | Serilog + Serilog.Sinks.File | 4.2.0 / 6.0.0 | Structured rolling daily logs, 14-day retention |
| DI | Microsoft.Extensions.DependencyInjection | 10.0.0 | ValidateOnBuild, singleton/transient registration |
| Caching | Microsoft.Extensions.Caching.Memory | 10.0.0 | In-memory cache for installed programs (6h TTL) |
| System Access | System.Management | 10.0.0 | WMI queries for hardware telemetry |
| Services | System.ServiceProcess.ServiceController | 10.0.0 | Windows service state verification |
| Serialization | System.Text.Json | (built-in) | High-performance JSON, source-generated where applicable |
| Tests | xUnit + Moq | -- | Unit and integration testing |
The project file activates several .NET 10 performance features:
TieredPGO=true -- Profile-Guided Optimization with tiered recompilation for hot methods.TieredCompilation=true -- Rapid startup via Tier-0 JIT, background promotion to optimized Tier-1.OptimizationPreference=Speed -- Compiler preference for execution speed over code size.ConcurrentGarbageCollection=true -- Background GC on dedicated threads to minimize UI pauses.ServerGarbageCollection=false -- Client-mode GC optimized for desktop workstation latency profiles.
The App.OnExit method performs orderly disposal in a fixed sequence: ResourceGuard stop and dispose,
ThemeService dispose, AiChatService dispose (unloading the LLM model), ProcessWatcher dispose,
NetworkMonitor dispose, DynamicTracer final flush-to-disk, and finally ServiceContainer.Shutdown()
which disposes the underlying IServiceProvider and calls Log.CloseAndFlush().
Each disposal step is independently try-caught to ensure subsequent services are still properly released.
The DI container is managed by ServiceContainer, a static wrapper around a
Lazy<IServiceProvider> initialized with LazyThreadSafetyMode.ExecutionAndPublication.
This guarantees exactly-once initialization across all threads.
| Category | Lifetime | Registrations |
|---|---|---|
| Interface-bound Singletons | Singleton |
ISecurityPolicy -> SecurityPolicyServiceICacheService -> CacheServiceIDynamicTracer -> DynamicTracerServiceIResourceAllocator -> ResourceAllocatorServiceIRollbackService -> RollbackServiceISourceAnalyzer -> SourceAnalyzerServiceIStateValidator -> StateValidatorServiceICodePatcher -> CodePatcherServiceIOptimizationEngine -> OptimizationEngineServiceIAiService -> AiChatServiceIAuditLog -> AuditLogService
|
| Concrete Singletons | Singleton |
SettingsService, InstalledProgramsService,
ProfileService, ProcessWatcherService,
ThemeService, LocalizationService,
ResourceGuardService, NetworkMonitorService,
KeyboardShortcutsService, StartupService,
FeatureExecutionEngine, WorkflowService
|
| Transient Services | Transient |
CleaningService, InstallerService,
WorkflowService, StartupHealthService,
UserAccountService
|
Build-Time Validation -- The container is built with ValidateOnBuild = true,
which ensures all registered service dependencies are resolvable at startup. Any missing or circular dependency
causes an immediate, descriptive exception during ServiceContainer.Build() rather than a runtime
failure later.
ServiceContainer.GetRequired<T>() -- Returns the required service or throws InvalidOperationException.ServiceContainer.GetOptional<T>() -- Returns the service or null if not registered.ServiceContainer.CreateScope() -- Creates a new DI scope for scoped service resolution.ServiceContainer.Shutdown() -- Disposes the provider and flushes Serilog; replaces the lazy with a throwing sentinel.
Coclico follows the Model-View-ViewModel (MVVM) pattern using CommunityToolkit.Mvvm 8.4.0. Views are defined
in XAML under the Views/ directory, with corresponding ViewModels in ViewModels/.
Services are injected into ViewModels via constructor injection.
| View | ViewModel | Module |
|---|---|---|
| DashboardView.xaml | DashboardViewModel | System metrics dashboard |
| ProgramsView.xaml | (code-behind) | Application library |
| WorkflowPipelinesView.xaml | WorkflowPipelinesViewModel | Flow chain editor |
| InstallerView.xaml | (code-behind) | Winget GUI installer |
| CleaningView.xaml | CleaningViewModel | Disk cleanup |
| ScannerView.xaml | ScannerViewModel | Application audit |
| RamCleanerView.xaml | (code-behind) | Memory optimization |
| AiChatView.xaml | (code-behind) | AI chat assistant |
| SettingsView.xaml | SettingsViewModel | Application settings |
All UI-thread updates from background services use Dispatcher.InvokeAsync. The application
explicitly sets the WPF animation frame rate to 60 FPS via Timeline.DesiredFrameRateProperty
metadata override, and configures the minimum thread pool size to match Environment.ProcessorCount
for optimal throughput.
GCSettings.LatencyMode is set to SustainedLowLatency
at startup, dynamically adjusted by ResourceGuard between Interactive and SustainedLowLatency
based on pressure levels.Critical pressure, GCLargeObjectHeapCompactionMode.CompactOnce
is engaged for the next GC cycle.ArrayPool<byte>.Shared for buffer allocation
during reverse-reading of NDJSON files, avoiding GC pressure.FrozenSet<string> for O(1) amortized lookup with zero ongoing allocation.SearchValues<string>
for hardware-accelerated string matching on .NET 10.BoundedChannelOptions with
DropOldest policy, SingleReader=true, SingleWriter=true for lock-free
inter-stage communication.
Coclico exposes eight primary functional modules via a left-sidebar navigation. Each module is implemented
as a WPF UserControl with dedicated service layer support. All long-running operations are routed through
FeatureExecutionEngine.RunFeatureAsync, which provides circuit-breaker semantics, lifecycle
tracking, and telemetry recording.
The Dashboard provides a real-time overview of the host machine's health, refreshed every 3 seconds.
All metrics are collected via P/Invoke (GlobalMemoryStatusEx) and WMI queries without any
external process spawning.
| Metric | Source | Refresh Interval |
|---|---|---|
| CPU utilization (%) | PerformanceCounter / process delta | 3 seconds |
| RAM used / total (GB) | GlobalMemoryStatusEx P/Invoke | 3 seconds |
| Disk C: free / total | DriveInfo | 3 seconds |
| Windows uptime | Environment.TickCount64 | 3 seconds |
| Active process count | Process.GetProcesses() | 3 seconds |
| Installed application count | InstalledProgramsService cache | On load |
The Applications module maintains a comprehensive inventory of all software and games installed on the system. It aggregates data from eight distinct sources, each requiring a dedicated detection algorithm:
| # | Source | Detection Method |
|---|---|---|
| 1 | Windows Registry (HKLM + HKCU) | Uninstall key enumeration under SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall |
| 2 | Steam | VDF manifest parsing from steamapps library folders |
| 3 | Epic Games | Manifest JSON parsing from %ProgramData%\Epic\EpicGamesLauncher |
| 4 | GOG Galaxy | Database / registry key enumeration |
| 5 | Ubisoft Connect | Configuration file and registry detection |
| 6 | EA App | Local content descriptor parsing |
| 7 | Rockstar Games | Launcher metadata and registry keys |
| 8 | Microsoft Store (MSIX) | PackageManager API enumeration |
custom_apps_data.json).SearchValues<string> to exclude drivers, runtimes, SDKs, and other non-user-facing entries.
Flow Chains is a visual drag-and-drop automation editor that allows users to construct complex
multi-step workflows. Chains are persisted as JSON in %AppData%\Coclico\flow_chains.json
and can be triggered manually, via global hotkeys (Ctrl+(Alt+)Key), or on automatic intervals.
| Category | Nodes |
|---|---|
| Control Flow | Start, End, Condition, Loop, Parallel, Delay |
| Process Management | OpenApp, CloseApp, KillProcess, KillByMemory, SetProcessPriority |
| Command Execution | RunCommand, RunPowerShell |
| User Interaction | Notification, SendKeys, TriggerShortcut, ClipboardSet, Screenshot |
| Network & Web | HttpRequest, OpenUrl |
| File System | FileOperation, CompressFile, EmptyRecycleBin, CleanTemp |
| System | SystemCheck, RamClean, SetVolume, MuteAudio |
| Operator | Type | Description |
|---|---|---|
ProcessRunning | Process | True if named process is active |
ProcessNotRunning | Process | True if named process is not active |
FileExists | File System | True if file path exists |
FileNotExists | File System | True if file path does not exist |
TimeAfter | Temporal | True if current time is after specified time |
TimeBefore | Temporal | True if current time is before specified time |
CpuBelow | Resource | True if CPU usage is below threshold (%) |
CpuAbove | Resource | True if CPU usage is above threshold (%) |
RamBelow | Resource | True if RAM usage is below threshold (%) |
RamAbove | Resource | True if RAM usage is above threshold (%) |
Each PipelineStep supports an OnErrorAction enum controlling failure behavior:
ContinueNext (default) -- Skip the failed step and proceed to the next.StopChain -- Halt the entire chain immediately.SkipToEnd -- Jump to the End node, bypassing all remaining steps.
Additionally, each step supports configurable RetryCount (0--10) and TimeoutSeconds
parameters for resilient execution.
The Quick Installer provides a graphical interface to the Windows Package Manager (Winget), enabling one-click installation of curated software packages without requiring command-line interaction.
The Winget scope (Machine or User) is configurable via Settings. Software definitions are loaded from
an embedded software_list.json resource that ships with the application.
The Cleaning module provides both a standard Windows Disk Cleanup integration and a proprietary deep cleaning engine. Before execution, the engine estimates the recoverable space per category.
| # | Category | Target Paths |
|---|---|---|
| 1 | Windows Temp Files | %TEMP%, C:\Windows\Temp |
| 2 | Browser Caches | Chrome, Firefox, Edge local cache directories |
| 3 | System Logs | Windows event log archives, CBS logs |
| 4 | Recycle Bin | $Recycle.Bin |
| 5 | User Temp | %LOCALAPPDATA%\Temp |
| 6 | Thumbnail Cache | thumbcache_*.db files |
| 7 | Error Reports | Windows Error Reporting queue |
| 8 | Old Installers & Updates | SoftwareDistribution\Download |
| 9 | DNS Cache | In-memory DNS resolver cache |
| 10 | Prefetch | C:\Windows\Prefetch |
The deep cleaning mode performs iterative, multi-pass deletion with retry logic for locked files. Results
include per-category byte counts, file deletion counts, and elapsed time. The Windows Disk Cleanup utility
(cleanmgr.exe) is launched as a separate elevated process with BelowNormal priority
to avoid impacting system responsiveness.
The Scanner module performs a comprehensive audit of all installed applications, producing a detailed inventory with the following fields per application: name, version, publisher, estimated size, installation path, detection source, and installation date. Results are sortable and filterable. The scanning process uses the same multi-source detection engine as the Applications module (Section 4.2).
The RAM Cleaner module provides kernel-level memory optimization through direct Windows API calls via P/Invoke. It displays real-time RAM statistics (physical used/total, virtual commit charge, pagefile size) and offers manual or automated cleaning.
| DLL | Functions Used |
|---|---|
ntdll.dll | NtSetSystemInformation (MemoryPurge, StandbyList, ModifiedList) |
kernel32.dll | SetProcessWorkingSetSize, OpenProcess, CloseHandle, SetSystemFileCacheSize, GetProcessHeap, HeapCompact, GlobalMemoryStatusEx |
advapi32.dll | OpenProcessToken, LookupPrivilegeValue, AdjustTokenPrivileges, RegFlushKey |
dnsapi.dll | DnsFlushResolverCache |
iphlpapi.dll | FlushIpNetTable |
The following kernel-level operations are performed via NtSetSystemInformation:
SystemMemoryListInformation, command 2) -- Trims the working set of all processes.HeapCompact.
Privilege escalation is performed per-operation by acquiring SeDebugPrivilege and
SeIncreaseQuotaPrivilege through the AdjustTokenPrivileges API. The
automatic mode supports both interval-based triggers and threshold-based triggers (when RAM usage
exceeds a configurable percentage).
The AI Assistant is an in-application conversational interface powered by a local GGUF language model. It provides contextual help across all Coclico modules, answering user questions about features, guiding step-by-step through complex operations, and adapting its response language to match the user's input language. The assistant is described in full technical detail in Section 5.
Coclico implements a fully local LLM inference stack using LLamaSharp 0.26, the C# binding for
llama.cpp. The engine loads a single GGUF model file (resource/model/IA-support-chat.gguf)
and creates two isolated execution contexts from the same model weights. This dual-context architecture
eliminates contention between interactive user chat and background autonomous optimization tasks.
| Parameter | Chat Context | Engine Context |
|---|---|---|
| Context Size | 2048 tokens | 512 tokens |
| Batch Size | 256 | 128 |
| Thread Count | OptimalThreads (2..6) | OptimalThreads / 2 |
| Memory Map | Enabled | Enabled |
| Flash Attention | Enabled | Enabled |
| GPU Layer Attempts | [8, 0] (GPU first, CPU fallback) | [8, 0] |
Context reset is performed without blocking consumers through Interlocked.Exchange:
var newCtx = new ChatCtx(_model.CreateContext(params));
Interlocked.Exchange(ref _chatCtx, newCtx)?.Dispose();
This atomic swap ensures that any in-flight read of _chatCtx completes on the old context
while subsequent reads use the new one. The old context is disposed after the exchange. The chat context
automatically resets after 6 conversation turns to prevent context window saturation.
The chat executor maintains a sliding window of the last 4 conversation turns
(MaxMemoryTurns = 4), summarized into a compact memory block injected at session start.
User messages are truncated to 100 characters and AI responses to 150 characters within the memory block
to conserve context window budget. After every 6 turns (AutoResetAfterTurns = 6), the context
is silently reset with the memory block re-injected to prevent quality degradation.
The AI model consumes approximately 2.5 GB of RAM when loaded. To optimize resource usage on machines where the AI assistant is not continuously active, Coclico implements a configurable idle timeout mechanism:
OnIdleTimeout executes with Interlocked.CompareExchange
guard to prevent concurrent unload attempts._initLock, _chatSem,
_engineSem) in order, then disposes both contexts and the model weights.MemoryCleanerService.ForceGcCollect() to
immediately reclaim the freed native memory.InitializeAsync transparently reloads the model with
the same GPU-first, CPU-fallback strategy.Memory Impact -- The automatic unload releases approximately 2.5 GB of RAM after the
configured idle period. The reload latency is transparent to the user, as SendMessageAsync
internally calls InitializeAsync if the model is not loaded.
The AI assistant is augmented with a local RAG pipeline implemented in RagService. At startup,
all Markdown files in resource/docs/ are indexed using a hybrid scoring system:
#{1,3}). Each chunk retains its section title as metadata. Chunks smaller than 40 characters are discarded.SimpleStemmer.log((N - df + 0.5) / (df + 0.5) + 1).At query time, the RAG engine applies a dual-score ranking:
k1=1.5, b=0.75, normalized against the maximum BM25 score in the corpus.
The top-K results (default K=2, max 350 characters total) are injected into the LLM prompt
as a [Doc] context block, positioned between the system prompt and the user message.
| Parameter | Chat (User-Facing) | Engine (Background) |
|---|---|---|
| Max Tokens | 512 | 256 |
| Temperature | 0.4 | 0.1 |
| Top-P | 0.90 | 0.95 |
| Top-K | 30 | 10 |
| Repeat Penalty | 1.1 | 1.0 |
| Anti-Prompts | <|end|>, <|user|>, <|endoftext|>, User:, Assistant: | <|end|>, <|user|>, <|endoftext|> |
The engine context uses significantly lower temperature (0.1) and top-K (10) to produce deterministic, parseable JSON output. The chat context uses slightly higher creativity parameters for natural conversational responses.
The autonomous core represents Coclico's self-governing optimization subsystem. It continuously monitors system health, analyzes code quality, and applies validated improvements through a multi-stage pipeline with comprehensive safety gates. The core loop follows the Observe-Analyze-Act-Validate pattern described in the architecture vision.
The OptimizationEngineService implements a lock-free, channel-based pipeline that executes
every 30 seconds. The pipeline uses three concurrent Task stages communicating through
bounded channels with DropOldest semantics.
Gathers system metrics using MemoryCleanerService and DynamicTracerService:
If the AI model is loaded, the engine constructs a JSON-structured prompt containing the serialized
SystemMetrics record plus optional hotspot context from the SourceAnalyzer. The LLM is
instructed to respond exclusively in JSON with a fixed schema:
{
"ProcessId": 1234,
"ProcessName": "chrome",
"TargetPriority": "BelowNormal",
"Reason": "...",
"RcaSummary": "Root cause analysis...",
"NoAction": false
}
If the AI is unavailable or fails, the engine falls back to a deterministic scoring algorithm using
AdaptiveScorer. The scorer computes a weighted sum of normalized CPU, RAM, disk I/O, and
history features with self-adjusting weights:
score = wCPU * cpuScore + wRAM * ramScore + wDisk * diskScore + wHistory * histScore
Default weights: CPU=0.4, RAM=0.3, Disk=0.2, History=0.1. After each ineffective action, weights are adjusted (CPU weight increases, others decrease) and re-normalized to sum to 1.0.
Parses the JSON response, extracts the action, and applies it through the IResourceAllocator
interface. Before any priority change, a rollback snapshot is created. Critical system processes (system,
smss, csrss, wininit, winlogon, lsass, services, svchost, explorer, coclico) are protected from priority
modification.
The IsolationForestDetector implements the Liu et al. (2008) algorithm adapted for streaming
data. Configuration: 100 trees, subsample size of 64, anomaly threshold of 0.65. The forest is initially
fit after 20 observations and refitted every 50 observations from a rolling buffer of 500 samples.
When an anomaly is detected (score > 0.65), per-feature Z-scores are computed to identify which
metrics deviate beyond 2 standard deviations.
The SourceAnalyzerService performs static analysis on C# source files using the Roslyn
Microsoft.CodeAnalysis.CSharp library (version 4.12.0). It traverses the syntax tree of
every .cs file (excluding bin/ and obj/ directories) and computes
per-method complexity metrics.
| Metric | Algorithm | Formula / Description |
|---|---|---|
| Cyclomatic Complexity (CC) | McCabe, 1976 | Base 1 + increments for: if, while, for,
foreach, do, case, switch arm,
catch, ternary ?:, &&, || |
| Cognitive Complexity (CogCC) | SonarSource, 2016 | Increments for control flow structures with nesting penalty. else if does not
add nesting. Lambda and local function bodies add nesting depth. Same-operator logical chains
are counted once. |
| Halstead Volume (V) | Halstead, 1977 | V = N * log2(eta) where N = total operators + operands,
eta = distinct operators + distinct operands |
| Halstead Difficulty (D) | Halstead, 1977 | D = (eta1 / 2) * (n2 / eta2) |
| Halstead Effort (E) | Halstead, 1977 | E = D * V |
| Maintainability Index (MI) | SEI, adapted | MI = max(0, (171 - 5.2*ln(V) - 0.23*CC - 16.2*ln(LOC)) / 171 * 100) |
| CC Range | Base Severity | Line Count Promotion |
|---|---|---|
| 1--5 | Low | >80 lines: promoted to Medium |
| 6--10 | Medium | >80 lines: promoted to High |
| 11--20 | High | >80 lines: promoted to Critical |
| 21+ | Critical | No further promotion |
Methods with severity "Low" and fewer than 20 lines are excluded from hotspot reporting to focus attention on meaningful optimization targets. Hotspots are sorted by severity rank (descending), then by cyclomatic complexity (descending).
The StateValidatorService maintains an in-memory index of all C# source files, acting as a
"Digital Twin" of the codebase. It performs the following functions:
.cs file using Roslyn and records per-file snapshots with SHA-256 hashes (first 16 hex characters).When the AutoPatcher proposes a code modification, the Digital Twin simulates the change by computing a weighted improvement score across five normalized metrics:
score = 0.35 * normCC
+ 0.15 * normLines
+ 0.20 * normVolume
+ 0.15 * normDifficulty
+ 0.15 * normEffort
Each normalization is computed as the negative delta divided by the original value plus one, meaning
reductions in complexity yield positive scores. A patch is approved only if
score > 0.05 (the improvement threshold). This multi-dimensional gate ensures that the
cyclomatic complexity, code volume, and Halstead difficulty do not regress, even if one metric improves.
The CodePatcherService manages the lifecycle of AI-proposed code modifications, from
proposal through validation to application. It supports two operational modes:
When CodePatcherAuditOnly = true (the default), patches are validated by the Digital Twin but
not applied to disk. Instead, they are recorded as proposals in a pending queue. An authorized human
can then review, approve, or reject each proposal through the API:
GetPendingProposals() -- Returns all pending patch proposals.ApproveAndApplyAsync(proposal) -- Re-validates through the Digital Twin, creates a rollback snapshot, and applies the patch. Logs the approval with Actor: "Human".RejectProposalAsync(proposal, reason) -- Removes from pending and logs the rejection with the provided reason.SimulatePatch() computes the weighted improvement score.IRollbackService.CreateSnapshot() persists the entire file contents before modification.MethodReplacer.ReplaceMethod() uses Roslyn to locate the target method in the syntax tree and replace it, preserving surrounding code structure.File.WriteAllTextAsync() writes the patched source.The history buffer retains the last 100 patch results (applied, rejected, and proposed). The pending proposals queue is capped at 50 entries.
Coclico is designed as a strictly offline application. No telemetry, logs, AI inference data, or user
information is transmitted to any external server. The AI model runs entirely on-device using
llama.cpp via the LLamaSharp binding. All user data is stored under
%AppData%\Coclico\ and never leaves the machine.
The only outbound network activity is the optional update check service, which polls for new application versions every 5 minutes. This service can be disabled in settings.
The RollbackService provides a comprehensive state preservation mechanism for all
system-modifying operations. Every file write triggered by the autonomous core (AutoPatcher, QoS changes)
is preceded by a mandatory snapshot.
%AppData%\Coclico\snapshots\).ProtectedData.Protect() with DataProtectionScope.CurrentUser. Only the Windows user account that created the snapshot can decrypt it.CodePatcher.App.xaml.cs.OnStartup), creation timestamp, state type name, and serialized size in bytes.string CreateSnapshot<T>(string contextName, T state)
T? Rollback<T>(string snapshotId)
IReadOnlyList<SnapshotMetadata> GetHistory(int maxCount = 20)
void Delete(string snapshotId)
void Prune(TimeSpan olderThan)
The SecurityPolicyService enforces command-level security restrictions for all
Flow Chain operations. It maintains three categories of blocked patterns and one category of protected paths:
| Category | Count | Examples |
|---|---|---|
| CMD Patterns | 17 | format, rd /s /q, bcdedit, diskpart, sc delete, net user |
| PowerShell Patterns | 26 | invoke-expression, -encodedcommand, downloadstring, set-mppreference, [reflection.assembly]::load |
| PowerShell Wildcards | 1 | set-itemproperty.*hklm (regex, 100ms timeout) |
| Protected Paths | 9 | \windows\, \program files\, \system volume information\, \boot\, \efi\ |
Organizations can deploy a custom policy file at %AppData%\Coclico\security-policy.json.
The service loads this file at startup and merges its patterns with the hardcoded defaults using
HashSet.UnionWith(). The hardcoded defaults can never be removed, only supplemented.
After merging, all pattern sets are converted to FrozenSet<string> for O(1) lookup
performance. Regex wildcards are compiled with RegexOptions.Compiled and a 100ms execution
timeout to prevent ReDoS attacks.
bool IsCommandBlocked(string normalizedCmd)
bool IsPowerShellBlocked(string normalizedPs)
bool IsProtectedPath(string lowerCasePath)
The AuditLogService implements an append-only, Newline-Delimited JSON (NDJSON) audit trail.
Each entry is written to a daily file (audit-{yyyy-MM-dd}.log) under
%AppData%\Coclico\audit\.
record AuditEntry(
DateTimeOffset Timestamp,
string Actor, // "OptimizationEngine", "CodePatcher", "Human", ...
string Action, // "AiDecision", "PatchApplied", "ProposalRejected", ...
string Target, // "SystemMetrics", "App.xaml.cs::OnStartup", ...
bool Success,
string? Details,
AiDecisionContext? AiDecision // optional LLM prompt/response traceability
)
record AiDecisionContext(
string Prompt,
string RawResponse,
string DecisionMode // "Cognitive" or "Fallback"
)
SemaphoreSlim(1,1) ensures atomic, ordered writes.GetRecentAsync reads entries from the end of files using a block-based reverse reader with ArrayPool<byte>.Shared for zero-allocation buffering.AuditRetentionDays (configurable in Settings) are deleted.AiDecisionContext field, providing complete reproducibility of autonomous decisions.
Coclico uses Serilog 4.2.0 with the File sink 6.0.0 for structured, rolling daily log files.
Logs are written to %AppData%\Coclico\logs\coclico-{date}.log with a 14-day retention
policy. The output template includes millisecond-precision timestamps, three-character uppercase level
indicators, and the source context for precise log filtering.
Template: [{Timestamp:yyyy-MM-dd HH:mm:ss.fff} {Level:u3}] [{SourceContext}] {Message:lj}{NewLine}{Exception}
Minimum Level: Debug
Rolling Interval: Day
Retained Files: 14
Integration: Microsoft.Extensions.Logging via Serilog.Extensions.Logging 8.0.0
LoggingService.LogInfo(message) -- Informational events, startup milestones, cycle completions.LoggingService.LogError(message) -- Error conditions that are handled but notable.LoggingService.LogException(ex, context) -- Full exception with stack trace and caller context.
The DynamicTracerService provides application-level performance instrumentation with
statistical anomaly detection capabilities.
ConcurrentQueue-based ring buffer with a capacity of 2,000 snapshots.
Overflow evicts the oldest entry via TryDequeue.TDigest (compression=100,
Dunning & Ertl 2019 algorithm) for streaming P95 estimation without full-sort overhead.%AppData%\Coclico\telemetry\metrics-{date}.json.
Files older than 14 days are pruned.IDisposable BeginOperation(string name, string? category, IReadOnlyDictionary<string, object>? tags)
void Record(string name, TimeSpan elapsed, ...)
IReadOnlyList<MetricSnapshot> GetRecentMetrics(int maxCount = 100)
MetricAggregate? GetAggregate(string operationName) // Min, Max, Avg, P95, SampleCount
The BeginOperation method returns a disposable span that records elapsed time using
Stopwatch.GetTimestamp() and Stopwatch.GetElapsedTime() for high-resolution timing.
The Isolation Forest detector (IsolationForestDetector) processes multi-dimensional feature
vectors (CPU%, RAM%, DiskIO latency) from the OptimizationEngine:
| Parameter | Value | Description |
|---|---|---|
| Number of Trees | 100 | Ensemble size for averaging path lengths |
| Subsample Size | 64 | Points per tree at fit time |
| Anomaly Threshold | 0.65 | Score above which an observation is anomalous |
| Min Samples to Fit | 20 | Minimum buffer size before first forest construction |
| Max Buffer Size | 500 | Rolling window for forest refitting |
| Refit Interval | Every 50 observations | Forest is reconstructed to adapt to drift |
The anomaly score is computed as 2^(-avgPathLength / c(n)) where c(n) is the
average path length of an unsuccessful search in a BST: 2(ln(n-1) + 0.5772) - 2(n-1)/n.
Scores closer to 1.0 indicate higher anomaly likelihood.
The ResourceGuardService monitors Coclico's own resource footprint using
System.Reactive observables with a 2-second polling interval. It computes the application's
CPU usage (delta-based), working set, and private memory, then maps the overall system state to one of
four pressure levels:
| Level | Trigger Conditions | Actions |
|---|---|---|
| Normal | RAM < 70% AND AppWorkingSet < 300 MB | Reset high-streak counter. GC mode: Interactive. |
| Elevated | RAM >= 70% OR AppWorkingSet >= 300 MB | Decrement high-streak counter. GC mode: Interactive. |
| High | RAM >= 83% OR AppWorkingSet >= 550 MB | After 8 consecutive high readings: working set trim. GC mode: SustainedLowLatency. |
| Critical | RAM >= 93% OR AppWorkingSet >= 900 MB | After 4 consecutive readings: aggressive LOH compaction + working set trim (30s cooldown). GC mode: SustainedLowLatency. |
The service exposes a PressureChanged event that other services can subscribe to for adaptive
behavior (e.g., the OptimizationEngine could reduce its analysis scope under Critical pressure). Metric
collection runs on the Rx Scheduler.Default background thread, with UI property updates
dispatched to the WPF dispatcher via ObserveOn(DispatcherScheduler).
Coclico includes a companion marketing and documentation website built with modern web technologies, designed for performance, accessibility, and internationalization.
| Technology | Version | Purpose |
|---|---|---|
| Astro | 5.1+ | Static site generator with island architecture |
| Tailwind CSS | 3.4 | Utility-first CSS framework |
| TypeScript | 5.7 | Type-safe component logic |
| GSAP | 3.12.5 | High-performance scroll and entrance animations |
| Fuse.js | 7.0 | Fuzzy client-side search |
The website supports 4 languages with dedicated routing and locale files:
/fr/) -- Primary language/en/)/de/)/es/)
Translation strings are managed through TypeScript locale modules under src/i18n/locales/.
The root index.astro page handles locale detection and routing. Additional content sections
include dedicated pages for changelog, documentation, FAQ, guides, and wiki.
npm run dev # Local development server
npm run build # Production static build
npm run preview # Preview production build
npm run check # Astro type checking
| Requirement | Minimum | Recommended |
|---|---|---|
| Operating System | Windows 10 22H2 (Build 22621) | Windows 11 23H2+ |
| Runtime | .NET 10.0 Desktop Runtime | .NET 10.0 Desktop Runtime |
| RAM (without AI) | 4 GB | 8 GB |
| RAM (with AI loaded) | 8 GB | 16 GB |
| Disk Space | 500 MB (app + model) | 1 GB |
| CPU | x64, 4 cores | x64, 8+ cores (for optimal LLM threading) |
| GPU (optional) | Vulkan-compatible (if using GPU backend) | Any Vulkan 1.1+ GPU |
| Privileges | Administrator (required for WMI, memory ops, priority changes) | Administrator |
# Restore NuGet packages
dotnet restore
# Build the application
dotnet build Coclico/Coclico.csproj
# Run the application (requires admin elevation)
dotnet run --project Coclico/Coclico.csproj
# Run all tests
dotnet test
# Run specific test class
dotnet test --filter "FullyQualifiedName~ServiceCore"
An Inno Setup script (Coclico_Setup.iss) is included for producing a Windows installer.
The installer packages the compiled application, the GGUF model file, resource documentation, and
the .NET runtime prerequisite check.
| File / Directory | Path | Purpose |
|---|---|---|
settings.json | %AppData%\Coclico\ | Application settings (theme, language, AI config) |
flow_chains.json | %AppData%\Coclico\ | Flow Chain definitions |
custom_apps_data.json | %AppData%\Coclico\ | User-customized application names/categories |
manual_apps.json | %AppData%\Coclico\ | Manually added application entries |
avatar.png | %AppData%\Coclico\ | User profile avatar |
security-policy.json | %AppData%\Coclico\ | Enterprise security policy (optional) |
logs\ | %AppData%\Coclico\logs\ | Serilog daily rolling logs (14 days) |
audit\ | %AppData%\Coclico\audit\ | NDJSON audit trail |
snapshots\ | %AppData%\Coclico\snapshots\ | DPAPI-encrypted rollback snapshots |
telemetry\ | %AppData%\Coclico\telemetry\ | DynamicTracer metric dumps (14 days) |
Coclico/
+-- Coclico.slnx # Solution file
+-- CLAUDE.md # AI assistant project instructions
+-- README.md # English README
+-- README.fr.md # French README
+-- LICENSE # Open source
+-- Coclico_Setup.iss # Inno Setup installer script
+-- docs/ # Project documentation
+-- Coclico/ # Main application project
| +-- Coclico.csproj # Project file (.NET 10, WinExe)
| +-- App.xaml / App.xaml.cs # Application entry point
| +-- MainWindow.xaml / .cs # Shell window with navigation
| +-- AssemblyInfo.cs # Assembly metadata
| +-- app.manifest # UAC elevation manifest
| +-- Properties/ # Launch settings
| +-- Models/
| | +-- LaunchMode.cs # Startup mode enum
| | +-- WorkflowPipeline.cs # Pipeline, Step, Connection models
| +-- Views/
| | +-- DashboardView.xaml # System metrics dashboard
| | +-- ProgramsView.xaml # Application library
| | +-- WorkflowPipelinesView.xaml # Flow Chain visual editor
| | +-- InstallerView.xaml # Winget GUI
| | +-- CleaningView.xaml # Disk cleanup
| | +-- ScannerView.xaml # Application audit
| | +-- RamCleanerView.xaml # Memory optimization
| | +-- AiChatView.xaml # AI chat interface
| | +-- SettingsView.xaml # Application settings
| | +-- HelpView.xaml # Help / about
| | +-- ProfileWindow.xaml # User profile editor
| | +-- SplashWindow.xaml # Startup splash screen
| | +-- LauncherWindow.xaml # First-run configuration
| | +-- AdminPromptWindow.xaml # UAC elevation dialog
| | +-- AvatarCropWindow.xaml # Avatar image cropper
| | +-- RuleSelectionDialog.xaml # Flow Chain rule picker
| | +-- PipelineLink.cs # Visual link renderer
| +-- ViewModels/
| | +-- DashboardViewModel.cs
| | +-- CleaningViewModel.cs
| | +-- ScannerViewModel.cs
| | +-- SettingsViewModel.cs
| | +-- WorkflowPipelinesViewModel.cs
| +-- Services/
| | +-- ServiceContainer.cs # Static DI wrapper
| | +-- AiChatService.cs # Dual-context LLamaSharp
| | +-- IAiService.cs # AI service interface
| | +-- RagService.cs # BM25+Cosine RAG engine
| | +-- OptimizationEngineService.cs # 3-stage pipeline
| | +-- IOptimizationEngine.cs
| | +-- SourceAnalyzerService.cs # Roslyn AST analysis
| | +-- ISourceAnalyzer.cs
| | +-- StateValidatorService.cs # Digital Twin
| | +-- IStateValidator.cs
| | +-- CodePatcherService.cs # AutoPatcher
| | +-- ICodePatcher.cs
| | +-- DynamicTracerService.cs # Telemetry + TDigest
| | +-- IDynamicTracer.cs
| | +-- ResourceGuardService.cs # Pressure level monitor
| | +-- ResourceAllocatorService.cs # Process priority QoS
| | +-- IResourceAllocator.cs
| | +-- RollbackService.cs # DPAPI-encrypted snapshots
| | +-- IRollbackService.cs
| | +-- SecurityPolicyService.cs # FrozenSet policy engine
| | +-- ISecurityPolicy.cs
| | +-- AuditLogService.cs # NDJSON audit trail
| | +-- IAuditLog.cs
| | +-- FeatureExecutionEngine.cs # Circuit-breaker wrapper
| | +-- MemoryCleanerService.cs # P/Invoke RAM operations
| | +-- CleaningService.cs # Disk cleanup engine
| | +-- InstalledProgramsService.cs # 8-source app detection
| | +-- InstallerService.cs # Winget integration
| | +-- WorkflowService.cs # CRUD + execution
| | +-- SettingsService.cs # JSON settings persistence
| | +-- ThemeService.cs # Dark/light theme engine
| | +-- LocalizationService.cs # 10-language runtime switch
| | +-- ProfileService.cs # User profile management
| | +-- CacheService.cs # In-memory caching
| | +-- ICacheService.cs
| | +-- LoggingService.cs # Serilog facade
| | +-- NetworkMonitorService.cs # Network state tracking
| | +-- ProcessWatcherService.cs # Process lifecycle events
| | +-- StartupService.cs # Windows startup registration
| | +-- StartupHealthService.cs # Boot health diagnostics
| | +-- KeyboardShortcutsService.cs # Global hotkey registration
| | +-- ToastService.cs # WPF notification toasts
| | +-- TrayService.Win32.cs # System tray P/Invoke
| | +-- UpdateCheckService.cs # Version update polling
| | +-- UpdateManager.cs # Update download/apply
| | +-- UserAccountService.cs # Windows user account info
| | +-- SecretScanService.cs # Credential leak detection
| | +-- SecurityHelpers.cs # Privilege escalation utils
| | +-- SeverityClassifier.cs # Log severity mapping
| | +-- AiActionParser.cs # LLM response JSON parser
| | +-- OptimizationAction.cs # Action record type
| | +-- Algorithms/
| | +-- IsolationForestDetector.cs # Liu et al. 2008
| | +-- TDigest.cs # Dunning & Ertl 2019
| | +-- MethodReplacer.cs # Roslyn AST replacement
| | +-- SimpleStemmer.cs # Token stemmer for RAG
| +-- Converters/ # WPF value converters
| +-- Resources/
| | +-- icone/ # Application icons
| | +-- software_list.json # Winget package definitions
| +-- resource/
| +-- model/ # GGUF AI model file
| +-- docs/ # RAG knowledge base (Markdown)
+-- Coclico.Tests/ # xUnit + Moq test project
+-- Installer/ # Inno Setup resources
+-- website/ # Astro 5 companion website
+-- astro.config.mjs
+-- tailwind.config.mjs
+-- package.json
+-- tsconfig.json
+-- public/ # Static assets
+-- src/
+-- components/ # Astro/HTML components
+-- layouts/ # Page layouts
+-- pages/ # Route pages (fr, en, de, es)
+-- styles/ # Global CSS
+-- i18n/
+-- index.ts # i18n router
+-- locales/ # fr.ts, en.ts, de.ts, es.ts