Coclico
Technical Reference Document
Version 1.0.4
March 2026

Enterprise-Grade Windows System Management,
Automation, and Autonomous Optimization Platform
Open Source Technical Documentation — coclico-cy
2026 Coclico
.NET 10 · C# Preview · WPF-UI 4.2 · LLamaSharp 0.26 · Roslyn 4.12

Table of Contents

1. Executive Summary

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.

Runtime .NET 10, C# preview, TieredPGO, ConcurrentGC
AI Inference LLamaSharp 0.26, dual-context, ~2.5 GB VRAM/RAM
Automation 28 node types, 10 condition operators
Security Zero Cloud, DPAPI, FrozenSet policy, NDJSON audit

2. General Overview

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.

Design Principles

Supported Languages

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.

3. Technical Architecture

3.1 Technology Stack

LayerTechnologyVersionPurpose
Runtime.NET10.0Application framework, TieredPGO, ConcurrentGC
LanguageC#previewPrimary constructors, collection expressions, pattern matching
UI FrameworkWPF + WPF-UI4.2.0Fluent Design system, dark/light themes
MVVM ToolkitCommunityToolkit.Mvvm8.4.0ObservableObject, RelayCommand, source generators
Local AILLamaSharp + Backend.Cpu0.26.0GGUF model inference, dual-context isolation
AST AnalysisMicrosoft.CodeAnalysis.CSharp4.12.0Roslyn syntax tree parsing, CC computation
ReactiveSystem.Reactive6.0.1Observable streams for ResourceGuard polling
LoggingSerilog + Serilog.Sinks.File4.2.0 / 6.0.0Structured rolling daily logs, 14-day retention
DIMicrosoft.Extensions.DependencyInjection10.0.0ValidateOnBuild, singleton/transient registration
CachingMicrosoft.Extensions.Caching.Memory10.0.0In-memory cache for installed programs (6h TTL)
System AccessSystem.Management10.0.0WMI queries for hardware telemetry
ServicesSystem.ServiceProcess.ServiceController10.0.0Windows service state verification
SerializationSystem.Text.Json(built-in)High-performance JSON, source-generated where applicable
TestsxUnit + Moq--Unit and integration testing

Compiler & Runtime Optimizations

The project file activates several .NET 10 performance features:

3.2 Application Lifecycle

App.OnStartup() | +-- EnsureRunAsAdmin() -----------> UAC prompt if not elevated | -> AdminPromptWindow dialog | -> Process.Start(Verb="runas") | +-- GCSettings.LatencyMode = SustainedLowLatency +-- ThreadPool.SetMinThreads(cpuCount, cpuCount) +-- Timeline.DesiredFrameRate = 60 | +-- ServiceContainer.Build(configure) | | | +-- Serilog.Logger configured (rolling daily, 14 files) | +-- AddMemoryCache() | +-- AddHttpClient() | +-- Interface bindings: ISecurityPolicy, ICacheService, IDynamicTracer, | | IResourceAllocator, IRollbackService, ISourceAnalyzer, IStateValidator, | | ICodePatcher, IOptimizationEngine, IAiService, IAuditLog | +-- Concrete singletons: SettingsService, ProfileService, ThemeService, | | LocalizationService, ResourceGuardService, NetworkMonitorService, ... | +-- Transients: CleaningService, InstallerService, WorkflowService, ... | +-- BuildServiceProvider(ValidateOnBuild=true) | +-- SplashWindow.Show() + RunStartupAsync() +-- AuditLog.Prune(retentionDays) +-- FirstRun? -> LauncherWindow (Normal / Minimized / Tray) +-- MainWindow.Show() +-- ThemeService.ApplyCurrentSettings() +-- SplashWindow.Close() +-- MemoryCleanerService.TrimSelfWorkingSet() [background] +-- UpdateCheckService.Start() [every 5 minutes]

Shutdown Sequence

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.

3.3 Dependency Injection Container

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.

Service Registration Categories

CategoryLifetimeRegistrations
Interface-bound Singletons Singleton ISecurityPolicy -> SecurityPolicyService
ICacheService -> CacheService
IDynamicTracer -> DynamicTracerService
IResourceAllocator -> ResourceAllocatorService
IRollbackService -> RollbackService
ISourceAnalyzer -> SourceAnalyzerService
IStateValidator -> StateValidatorService
ICodePatcher -> CodePatcherService
IOptimizationEngine -> OptimizationEngineService
IAiService -> AiChatService
IAuditLog -> 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.

API Surface

3.4 MVVM Pattern & UI Architecture

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 Mapping

ViewViewModelModule
DashboardView.xamlDashboardViewModelSystem metrics dashboard
ProgramsView.xaml(code-behind)Application library
WorkflowPipelinesView.xamlWorkflowPipelinesViewModelFlow chain editor
InstallerView.xaml(code-behind)Winget GUI installer
CleaningView.xamlCleaningViewModelDisk cleanup
ScannerView.xamlScannerViewModelApplication audit
RamCleanerView.xaml(code-behind)Memory optimization
AiChatView.xaml(code-behind)AI chat assistant
SettingsView.xamlSettingsViewModelApplication 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.

3.5 Performance Tuning

4. Functional Modules

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.

4.1 Dashboard

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.

Displayed Metrics

MetricSourceRefresh Interval
CPU utilization (%)PerformanceCounter / process delta3 seconds
RAM used / total (GB)GlobalMemoryStatusEx P/Invoke3 seconds
Disk C: free / totalDriveInfo3 seconds
Windows uptimeEnvironment.TickCount643 seconds
Active process countProcess.GetProcesses()3 seconds
Installed application countInstalledProgramsService cacheOn load

4.2 Applications

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:

#SourceDetection Method
1Windows Registry (HKLM + HKCU)Uninstall key enumeration under SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
2SteamVDF manifest parsing from steamapps library folders
3Epic GamesManifest JSON parsing from %ProgramData%\Epic\EpicGamesLauncher
4GOG GalaxyDatabase / registry key enumeration
5Ubisoft ConnectConfiguration file and registry detection
6EA AppLocal content descriptor parsing
7Rockstar GamesLauncher metadata and registry keys
8Microsoft Store (MSIX)PackageManager API enumeration

Features

4.3 Flow Chains

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.

Node Types (28 total)

CategoryNodes
Control FlowStart, End, Condition, Loop, Parallel, Delay
Process ManagementOpenApp, CloseApp, KillProcess, KillByMemory, SetProcessPriority
Command ExecutionRunCommand, RunPowerShell
User InteractionNotification, SendKeys, TriggerShortcut, ClipboardSet, Screenshot
Network & WebHttpRequest, OpenUrl
File SystemFileOperation, CompressFile, EmptyRecycleBin, CleanTemp
SystemSystemCheck, RamClean, SetVolume, MuteAudio

Condition Operators (10 total)

OperatorTypeDescription
ProcessRunningProcessTrue if named process is active
ProcessNotRunningProcessTrue if named process is not active
FileExistsFile SystemTrue if file path exists
FileNotExistsFile SystemTrue if file path does not exist
TimeAfterTemporalTrue if current time is after specified time
TimeBeforeTemporalTrue if current time is before specified time
CpuBelowResourceTrue if CPU usage is below threshold (%)
CpuAboveResourceTrue if CPU usage is above threshold (%)
RamBelowResourceTrue if RAM usage is below threshold (%)
RamAboveResourceTrue if RAM usage is above threshold (%)

Error Handling

Each PipelineStep supports an OnErrorAction enum controlling failure behavior:

Additionally, each step supports configurable RetryCount (0--10) and TimeoutSeconds parameters for resilient execution.

4.4 Quick Installer

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.

Software Categories

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.

4.5 System Cleaning

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.

Cleaning Categories (10 total)

#CategoryTarget Paths
1Windows Temp Files%TEMP%, C:\Windows\Temp
2Browser CachesChrome, Firefox, Edge local cache directories
3System LogsWindows event log archives, CBS logs
4Recycle Bin$Recycle.Bin
5User Temp%LOCALAPPDATA%\Temp
6Thumbnail Cachethumbcache_*.db files
7Error ReportsWindows Error Reporting queue
8Old Installers & UpdatesSoftwareDistribution\Download
9DNS CacheIn-memory DNS resolver cache
10PrefetchC:\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.

4.6 Scanner

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).

4.7 RAM Cleaner

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.

P/Invoke API Surface

DLLFunctions Used
ntdll.dllNtSetSystemInformation (MemoryPurge, StandbyList, ModifiedList)
kernel32.dllSetProcessWorkingSetSize, OpenProcess, CloseHandle, SetSystemFileCacheSize, GetProcessHeap, HeapCompact, GlobalMemoryStatusEx
advapi32.dllOpenProcessToken, LookupPrivilegeValue, AdjustTokenPrivileges, RegFlushKey
dnsapi.dllDnsFlushResolverCache
iphlpapi.dllFlushIpNetTable

Memory Operations

The following kernel-level operations are performed via NtSetSystemInformation:

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).

4.8 AI Assistant

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.

5. Local AI Engine

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.

5.1 Dual-Executor Architecture

LLamaWeights (single model file, shared weights) | +------------+------------+ | | Chat Context Engine Context (2048 token window) (512 token window) | | InteractiveExecutor InteractiveExecutor | | _chatSem (1,1) _engineSem (1,1) | | AiChatView OptimizationEngine (user conversation) (system prompts, JSON)

Context Specifications

ParameterChat ContextEngine Context
Context Size2048 tokens512 tokens
Batch Size256128
Thread CountOptimalThreads (2..6)OptimalThreads / 2
Memory MapEnabledEnabled
Flash AttentionEnabledEnabled
GPU Layer Attempts[8, 0] (GPU first, CPU fallback)[8, 0]

Immutable Context Swap Pattern

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.

Short-Term Memory

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.

5.2 Automatic Memory Release

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:

  1. After each inference operation (chat or engine), a timer is reset to the configured idle period (default: 5 minutes).
  2. When the timer fires, OnIdleTimeout executes with Interlocked.CompareExchange guard to prevent concurrent unload attempts.
  3. The unload sequence acquires all three semaphores (_initLock, _chatSem, _engineSem) in order, then disposes both contexts and the model weights.
  4. A forced GC collect is triggered via MemoryCleanerService.ForceGcCollect() to immediately reclaim the freed native memory.
  5. On the next user interaction, 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.

5.3 Retrieval-Augmented Generation (RAG)

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:

Indexing Pipeline

  1. Chunking -- Documents are split at Markdown headers (#{1,3}). Each chunk retains its section title as metadata. Chunks smaller than 40 characters are discarded.
  2. Tokenization -- Text is lowercased, split on non-word boundaries (including accented characters), filtered through a stop-word list, and stemmed using a custom SimpleStemmer.
  3. TF-IDF Vectorization -- Term Frequency (TF) and Inverse Document Frequency (IDF, BM25 variant) vectors are computed per chunk. The IDF formula uses the BM25 smoothing: log((N - df + 0.5) / (df + 0.5) + 1).
  4. Pre-computed Norms -- Cosine similarity norms are pre-computed at index time to avoid runtime square-root operations.

Search Pipeline

At query time, the RAG engine applies a dual-score ranking:

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.

5.4 Inference Parameters

ParameterChat (User-Facing)Engine (Background)
Max Tokens512256
Temperature0.40.1
Top-P0.900.95
Top-K3010
Repeat Penalty1.11.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.

6. Autonomous Core

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.

6.1 OptimizationEngine -- 3-Stage Pipeline

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.

Stage 1: COLLECT Stage 2: DECIDE Stage 3: EXECUTE (every 30s) (per metric batch) (per decision) +-------------------+ +-------------------+ +-------------------+ | CollectMetrics() | -----> | AI or Fallback | -----> | Parse JSON | | - CPU % | Channel | decision engine | Channel | - SetPriority | | - RAM used/total | (1 cap) | - BuildPrompt() | (1 cap) | - CreateSnapshot | | - Top 5 processes | | - SendSystemPrmpt | | - AuditLog | | - EWMA anomalies | | - Audit trail | | - Report | | - P95 latency | +-------------------+ +-------------------+ +-------------------+

Stage 1: Collect

Gathers system metrics using MemoryCleanerService and DynamicTracerService:

Stage 2: Decide

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.

Stage 3: Execute

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.

Anomaly Detection: Isolation Forest

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.

6.2 SourceAnalyzer -- Roslyn AST Analysis

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.

Computed Metrics

MetricAlgorithmFormula / 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)

Severity Classification

CC RangeBase SeverityLine Count Promotion
1--5Low>80 lines: promoted to Medium
6--10Medium>80 lines: promoted to High
11--20High>80 lines: promoted to Critical
21+CriticalNo 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).

6.3 Digital Twin (StateValidator)

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:

Indexing

Patch Simulation

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.

6.4 AutoPatcher (CodePatcher)

The CodePatcherService manages the lifecycle of AI-proposed code modifications, from proposal through validation to application. It supports two operational modes:

Audit-Only Mode (Default Enterprise)

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:

Patch Application Pipeline

  1. Digital Twin Validation -- SimulatePatch() computes the weighted improvement score.
  2. Source Drift Detection -- Verifies the original method source still exists in the current file contents via string containment check.
  3. Rollback Snapshot -- IRollbackService.CreateSnapshot() persists the entire file contents before modification.
  4. AST-Based Replacement -- MethodReplacer.ReplaceMethod() uses Roslyn to locate the target method in the syntax tree and replace it, preserving surrounding code structure.
  5. Disk Write -- File.WriteAllTextAsync() writes the patched source.
  6. Audit Trail -- A full audit entry is logged with the action type, actor, target, success status, and delta metrics.

The history buffer retains the last 100 patch results (applied, rejected, and proposed). The pending proposals queue is capped at 50 entries.

7. Security

7.1 Zero Cloud Architecture

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.

7.2 Rollback Service & DPAPI Encryption

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.

Architecture

Rollback API

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)

7.3 Security Policy Engine

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:

Default Blocked Patterns (Hardcoded, Non-Suppressible)

CategoryCountExamples
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\

Enterprise Policy Merge

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.

Runtime Verification API

bool IsCommandBlocked(string normalizedCmd)
bool IsPowerShellBlocked(string normalizedPs)
bool IsProtectedPath(string lowerCasePath)

7.4 Audit Log (NDJSON)

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\.

Audit Entry Schema

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"
)

Implementation Details

8. Telemetry & Observability

8.1 Structured Logging (Serilog)

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.

Log Configuration

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

Logging Conventions

8.2 DynamicTracer -- EWMA & Isolation Forest

The DynamicTracerService provides application-level performance instrumentation with statistical anomaly detection capabilities.

Metric Collection

API Surface

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.

Anomaly Detection Pipeline

The Isolation Forest detector (IsolationForestDetector) processes multi-dimensional feature vectors (CPU%, RAM%, DiskIO latency) from the OptimizationEngine:

ParameterValueDescription
Number of Trees100Ensemble size for averaging path lengths
Subsample Size64Points per tree at fit time
Anomaly Threshold0.65Score above which an observation is anomalous
Min Samples to Fit20Minimum buffer size before first forest construction
Max Buffer Size500Rolling window for forest refitting
Refit IntervalEvery 50 observationsForest 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.

8.3 ResourceGuard -- Pressure Levels

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:

LevelTrigger ConditionsActions
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).

9. Website

Coclico includes a companion marketing and documentation website built with modern web technologies, designed for performance, accessibility, and internationalization.

Technology Stack

TechnologyVersionPurpose
Astro5.1+Static site generator with island architecture
Tailwind CSS3.4Utility-first CSS framework
TypeScript5.7Type-safe component logic
GSAP3.12.5High-performance scroll and entrance animations
Fuse.js7.0Fuzzy client-side search

Internationalization

The website supports 4 languages with dedicated routing and locale files:

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.

Build & Deploy

npm run dev      # Local development server
npm run build    # Production static build
npm run preview  # Preview production build
npm run check    # Astro type checking

10. Prerequisites & Deployment

System Requirements

RequirementMinimumRecommended
Operating SystemWindows 10 22H2 (Build 22621)Windows 11 23H2+
Runtime.NET 10.0 Desktop Runtime.NET 10.0 Desktop Runtime
RAM (without AI)4 GB8 GB
RAM (with AI loaded)8 GB16 GB
Disk Space500 MB (app + model)1 GB
CPUx64, 4 coresx64, 8+ cores (for optimal LLM threading)
GPU (optional)Vulkan-compatible (if using GPU backend)Any Vulkan 1.1+ GPU
PrivilegesAdministrator (required for WMI, memory ops, priority changes)Administrator

Build Instructions

# 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"

Deployment Artifacts

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.

User Data Locations

File / DirectoryPathPurpose
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)

Appendix A: Directory Structure

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