Page 1 of 2

Antigravity as bugs solver and tech support

Posted: Tue Feb 03, 2026 9:30 am
by Antonio Linares

We usually consider Google Antigravity as a powerfull IDE to develop code using AI, but you can use it to find and solve bugs too! :idea:

We have been searching a XBrowse GDI+ resources leak for several weeks and it was Antigravity who finally found the bugs and solved them :wink:

Solemos considerar a Google Antigravity como un IDE potente para desarrollar código usando IA, ¡pero también puedes usarlo para encontrar y solucionar errores! 💡

Estuvimos buscando una fuga de recursos GDI+ en XBrowse durante varias semanas y fue Antigravity quien finalmente encontró los fallos y los resolvió 😉


Re: Antigravity as bugs solver and tech support

Posted: Tue Feb 03, 2026 2:54 pm
by Otto

Dear Antonio,

very interesting. Could you please have the source code that I posted here reviewed by Antigravity for me? Since it will become the basis of my development, their opinion would be very important to me.

Many thanks in advance,
Otto

viewtopic.php?t=46306


Re: Antigravity as bugs solver and tech support

Posted: Wed Feb 04, 2026 5:29 am
by Antonio Linares

Dear Otto,

I encourage you to install Antigravity and test it for yourself

A big hug


Re: Antigravity as bugs solver and tech support

Posted: Tue Feb 24, 2026 6:30 pm
by Otto

Dear Antonio,
Following your advice, I’m now setting up my environment—just realized I can use my local Ollama server for this!
I’ve got a high-end Linux machine ready (Ryzen 9 7950X, RTX 3090, 64GB RAM) and will also test it on my mobile setup. Excited to see how it handles my current source code. A second effect is that I’ll also get more hands-on experience with Linux.

Best regards,
Otto


Re: Antigravity as bugs solver and tech support

Posted: Tue Feb 24, 2026 7:04 pm
by Antonio Linares

Dear Otto,

Local Ollama does not provide Gemini 3.1

You can legally get 28 days free Gemini 3.1 this way:
viewtopic.php?t=46301


Re: Antigravity as bugs solver and tech support

Posted: Sat Feb 28, 2026 4:34 pm
by Otto

Dear Antonio,

Your example of Antigravity resolving the XBrowse GDI+ leak made me reflect more broadly on how AI should ideally be integrated into everyday FiveWin / Harbour development.

It made me reflect more broadly on how AI should ideally be integrated into everyday FiveWin / Harbour development.

From my experiments so far, I tend to see two possible directions:
A structured two-step workflow
AI assists in generating or improving code
AI reviews the result (compatibility, edge cases, memory handling, maintainability)

A more agentic model, where AI actively explores, diagnoses and solves issues with greater autonomy.

My current working assumption is:
Productivity = (Output Quality × Speed) – Mental Overhead
In legacy-heavy environments like ours, mental overhead and debugging cost often matter more than automation level itself.

Since you are clearly exploring the agentic direction, I am genuinely curious how a production-ready Antigravity workflow would look in a typical FiveWin scenario.

For example, could we take yunus.prg from the samples and demonstrate a reproducible, end-to-end agentic workflow around it?
Not as a conceptual demo, but as something developers here could realistically adopt in their daily work.

I believe a concrete, production-oriented example would help the community better understand the practical advantages and limitations.

I would be very interested in your view on this.

Best regards

Otto


Re: Antigravity as bugs solver and tech support

Posted: Sun Mar 01, 2026 5:12 am
by Antonio Linares

Dear Otto,

As a curiosity I already provided yunus.prg to AI some months ago and AI generated a SQL version of it:

samples\misc\yunus.prg // based on DBFs
samples\misc\yunusm.prg // based on MariaDB

AI did all the work :wink: :idea:

I keep investigating what is the right way to build a SKILL for an Agent. I love how DeepWiki analizes a repo and I would love to have a SKILL.md that allows AI to do the same work. I am asking different AIs about it, but they don't provide the same answer.


Re: Antigravity as bugs solver and tech support

Posted: Sun Mar 01, 2026 7:29 am
by Otto

Dear Antonio,

thank you — very interesting that you already used yunus.prg as a test case.

It seems yunus has become a kind of sparring partner for all of us when experimenting with new architectures and AI approaches.

I also keep coming back to yunus from the FiveWin samples whenever I want to validate a migration idea or a structural concept.

For reference, this is the thread where I used it for the HTP migration:

viewtopic.php?t=46195

In the course of that migration work, I introduced a small architectural pattern on the PHP side (a strict SSOT request adapter -
viewtopic.php?p=284125&hilit=ssot#p284125 ) to normalize and secure all incoming data before business logic runs.

Interestingly, this reduced ambiguity significantly — something that might also be relevant when thinking about defining a consistent SKILL for an agent. Clear entry structure seems to matter a lot.

I will install Antigravity in the next days and experiment with it myself.
I’m sure I will come back here with more focused and practical questions once I have some hands-on experience.

Best regards,
Otto


Re: Antigravity as bugs solver and tech support

Posted: Sun Mar 01, 2026 10:06 am
by Antonio Linares

.agent\skill\deepwiki\SKILL.md

---
name: code-deep-analysis

description: Performs deep analysis of code repositories like DeepWiki. Use it to examine project structure, identify technologies, analyze architecture, detect design patterns, evaluate code quality, and generate exhaustive technical documentation. Ideal for understanding unknown codebases, performing technical due diligence, or documenting existing projects.

Deep Code Analysis Skill

This skill allows you to analyze code repositories exhaustively, generating a complete understanding of the project similar to what DeepWiki offers. The analysis includes structure, architecture, technologies, patterns, and code quality.

When to Use This Skill

  • When you need to understand an unknown codebase
  • To perform technical due diligence on projects
  • When documenting existing software architectures
  • To identify technical debt and improvement opportunities
  • When evaluating the overall quality of a project
  • To generate automatic code documentation

How to Run the Analysis

Phase 1: Initial Exploration

  1. Identify the project type

    • Detect the main programming language
    • Identify the framework(s) used
    • Determine the application type (web, mobile, CLI, API, etc.)
  2. Map the directory structure

    • List all top-level directories
    • Identify organizational patterns (DDD, MVC, Clean Architecture, etc.)
    • Locate main configuration files
  3. Examine configuration files

    • package.json, pyproject.toml, Cargo.toml, pom.xml, etc.
    • Build files: webpack.config.js, tsconfig.json, Makefile
    • Container configuration: Dockerfile, docker-compose.yml

Phase 2: Technology Analysis

  1. Main technology stack

    • Languages and versions used
    • Backend and frontend frameworks
    • Databases and caching systems
    • Message queues and external services
  2. Critical dependencies

    • Main libraries and their purpose
    • Dependencies with known vulnerabilities
    • Outdated or unmaintained packages
  3. Development tools

    • Linters and formatters used
    • Testing systems
    • CI/CD tools
    • Task runners and bundlers

Phase 3: Architecture Analysis

  1. Architectural patterns

    • Identify whether it uses MVC, MVP, MVVM, Clean Architecture, Hexagonal, etc.
    • Detect design patterns used (Factory, Observer, Strategy, etc.)
    • Identify specific architectures (microservices, serverless, monolith)
  2. Component structure

    • Main modules and their responsibilities
    • Dependencies between components
    • Application entry and exit points
    • Communication patterns between components
  3. Data flow

    • How information flows through the system
    • APIs and contracts between modules
    • Integrations with external services

Phase 4: Code Analysis

  1. Overall quality

    • Readability and maintainability
    • Cyclomatic complexity
    • Code duplication
    • Function and module length
  2. Good patterns identified

    • SOLID principles applied
    • Dependency injection
    • Consistent error handling
    • Logging and monitoring
    • Data validation
  3. Areas for improvement

    • Code smells detected
    • Frequent anti-patterns
    • Lack of documentation in critical functions
    • Insufficient testing coverage

Phase 5: Testing and Quality

  1. Testing strategy

    • Types of tests implemented (unit, integration, e2e)
    • Testing frameworks used
    • Current code coverage
    • Testing patterns employed
  2. CI/CD

    • Continuous integration pipeline
    • Deployment stages
    • Branching strategies
    • Release workflow

Phase 6: Report Generation

  1. Report structure

    • Executive summary
    • System architecture
    • Complete technology stack
    • Code quality analysis
    • Findings and recommendations
    • Structure diagrams (when possible)
  2. Output format

    • Structured Markdown
    • Clear and navigable sections
    • Code examples when relevant
    • Actionable recommendations

Decision Tree

Code: Select all | Expand

Does the project have multiple services?
├── Yes → Identify inter-service communication (REST, gRPC, Message Queue)
└── No → Analyze as a monolithic application

Is there existing documentation?
├── Yes → Compare with actual implementation
└── No → Generate documentation based on code

Does the project have tests?
├── Yes → Analyze coverage and quality
└── No → Flag as a critical area for improvement

Output Format

The analysis should generate a structured report with the following sections:

Code: Select all | Expand

# Deep Analysis of [Project Name]

## Executive Summary
[Brief description of the project and its main characteristics]

## Technology Stack
- **Language**: [version]
- **Framework**: [version]
- **Database**: [type and version]
- **Other components**: [list]

## Project Structure
[Description of directory organization]

## Architecture
[Identified patterns and architecture description]

## Code Analysis
### Overall Quality
[Score and relevant metrics]

### Identified Patterns
[List of design patterns found]

### Areas for Improvement
[Issues found with suggestions]

## Testing
[Current state of tests and coverage]

## Recommendations
[Prioritized list of recommended actions]

Usage Examples

Full analysis of an unknown project

Code: Select all | Expand

Analyze the repository at /workspace/my-project as DeepWiki would

Focus on a specific aspect

Code: Select all | Expand

Perform an architecture analysis of the project focusing on design patterns

Comparison with best practices

Code: Select all | Expand

Evaluate the code quality comparing with clean code principles

Metrics to Collect

  • Number of files per language
  • Total lines of code
  • Maximum directory depth
  • Number of direct dependencies
  • Test coverage (if applicable)
  • Average cyclomatic complexity
  • Average number of functions/classes per file

Available Helper Scripts

The skill includes optional scripts that can be used during the analysis:

  • analyze-structure.sh: Analyzes the directory structure and generates a tree
  • detect-tech-stack.py: Detects technologies based on configuration files
  • calculate-metrics.py: Calculates code metrics (lines, complexity, etc.)

Run with --help to see usage options.


Re: Antigravity as bugs solver and tech support

Posted: Sun Mar 01, 2026 10:08 am
by Antonio Linares

Example of use (skill used from Antigravity):

analiza este repo usando el skill deepwiki

Análisis Profundo de FiveWin for Harbour (FWH)

Resumen Ejecutivo

FiveWin for Harbour (FWH) es un framework profesional de desarrollo de aplicaciones GUI nativas para Windows, escrito en Harbour/xHarbour (capa OOP de alto nivel) y C/C++ (capa de acceso a la API de Windows). Desarrollado por FiveTech Software desde 1993, es una de las bibliotecas GUI más maduras y completas del ecosistema xBase, con más de 30 años de desarrollo continuo.

El proyecto implementa un sistema de clases orientado a objetos con 256 clases que encapsulan controles Windows, servicios de red, inteligencia artificial, bases de datos, informes, y gráficos. La versión actual es FWH 25.12 y soporta compiladores Borland C++, MSVC (32/64 bits), y el compilador llvm-clang.

[!IMPORTANT]
El repositorio contiene 791 archivos fuente, 3,487 archivos de ejemplo, y un historial de cambios ([whatsnew.txt](file:///c:/fwteam/whatsnew.txt)) de 25,865 líneas que documenta más de 30 años de evolución.


Stack Tecnológico

ComponenteTecnologíaDetalles
Lenguaje principalHarbour / xHarbourCompilador xBase compatible con Clipper
Lenguaje de bajo nivelC / C++Wrappers directos a Windows API
PreprocesadorCH (Clipper Header)Sistema de macros xTranslate/xCommand
Sistema de compilaciónMakefiles (NMake)[fwh.mak](file:///c:/fwteam/fwh.mak), [fwh64.mak](file:///c:/fwteam/fwh64.mak), [fwhg.mak](file:///c:/fwteam/fwhg.mak), etc.
Compiladores C soportadosBCC32, MSVC, llvm-clang32 y 64 bits
Plataforma destinoWindows (Win32/Win64/WinCE)Nativo, no requiere runtime
Versión actualFWH 25.12Copyright 1993-2023+
Control de versionesGitCon [.gitignore](file:///c:/fwteam/.gitignore)

Dependencias Externas Integradas

  • GDI+ — Gráficos avanzados (gradientes, alpha blending, anti-aliasing)
  • WebView2 — Motor web Chromium embedded (Edge)
  • Scintilla — Editor de código embebido
  • libcurl — Conectividad HTTP/HTTPS para APIs
  • MySQL/MariaDB — Conectores nativos de base de datos
  • HaruPDF — Generación de PDF
  • OLE/ActiveX — Automatización COM

Estructura del Proyecto

Code: Select all | Expand

c:\fwteam\
├── source/                    # Código fuente principal (~791 archivos)
│   ├── classes/    (256 PRG)  # Clases OOP: controles, ventanas, browses
│   ├── function/   (146 C)    # Funciones utilitarias en C
│   ├── winapi/     (162 C)    # Wrappers directos a Win32 API
│   ├── internal/   (178 C/PRG/CPP) # Internals: ActiveX, GDI+, WebView2
│   └── ceclasses/  (50 PRG)   # Versión para Windows CE/Mobile
├── include/        (102 CH/H) # Headers y definiciones de preprocesador
├── samples/        (~3,487)   # Ejemplos organizados por categoría
│   ├── ai/         (56)       # Ejemplos de IA: OpenAI, Ollama, Gemini...
│   ├── ui/         (474)      # Componentes UI: browses, panels, scrolls
│   ├── database/   (20)       # Ejemplos de bases de datos
│   ├── webview/    (106)      # WebView2 y web scraping
│   ├── graphics/   (60)       # Gráficos y canvas
│   ├── EasyReport/ (353)      # Sistema de informes EasyReport
│   ├── MyRpt/      (289)      # Sistema de informes MyRpt
│   ├── FiveUI/     (287)      # UI components framework
│   └── misc/       (489)      # Ejemplos varios
├── lib/            (70)       # Bibliotecas compiladas (.lib, .def)
├── bitmaps/        (1,121)    # Recursos gráficos (BMP, PNG)
├── icons/          (403)      # Iconos para aplicaciones
├── cursors/        (62)       # Cursores personalizados
├── dll/            (28)       # DLLs auxiliares
├── docs/           (70)       # Documentación técnica
├── mysql/          (48)       # Conectores MySQL/MariaDB
├── makes/          (16)       # Makefiles auxiliares
├── manual/         (17)       # Manual de referencia
├── visual/         (26)       # Diseñador visual de diálogos
├── sounds/         (14)       # Archivos de sonido
├── whatsnew.txt    (25,865 ln)# Historial completo de cambios
└── fwh.mak                   # Makefile principal

Arquitectura

Patrón Arquitectónico

FWH implementa una arquitectura en capas con un modelo orientado a objetos (OOP) basado en el paradigma xBase de Clipper, combinando:

  1. Capa de aplicación: Código del usuario en Harbour con preprocesador
  2. Capa de clases FWH: 256 clases con herencia profunda
  3. Capa de funciones utilitarias: 146 funciones en C
  4. Capa de wrappers Win32 API: 162 archivos C de acceso directo al OS
  5. Windows API: El sistema operativo subyacente
graph TD A["Aplicación del usuario<br/>(Harbour + FiveWin.ch)"] --> B["Clases FWH<br/>(256 clases OOP)"] A --> C["Preprocesador CH<br/>(xTranslate/xCommand)"] C --> B B --> D["Funciones C<br/>(146 archivos)"] B --> E["Win32 API Wrappers<br/>(162 archivos)"] D --> F["Windows API"] E --> F B --> G["GDI+ / WebView2<br/>ActiveX / COM"] G --> F

Jerarquía de Clases Principal

classDiagram class TWindow { +hWnd +bInit, bPainted, bResized +oMenu, oBar, oMsgBar +New() +Activate() +HandleEvent() +End() } class TControl { +nId +oWnd } class TDialog { +lModal, lCentered +Activate() +Initiate() } class TMdiFrame class TMdiChild class TXBrowse { +19,420 líneas +aArrayData +SetArray() +SetRDD() +EditCell() } class TGet class TButton class TComboBox class TListBox class TPanel class TToolBar class TBitmap class TRibbon TWindow <|-- TControl TWindow <|-- TDialog TWindow <|-- TMdiFrame TWindow <|-- TMdiChild TControl <|-- TXBrowse TControl <|-- TGet TControl <|-- TButton TControl <|-- TComboBox TControl <|-- TListBox TControl <|-- TPanel TControl <|-- TToolBar TControl <|-- TBitmap TControl <|-- TRibbon

Sistema de Preprocesador xBase

Una característica distintiva de FWH es su extenso uso del preprocesador de Harbour a través de archivos [.ch](file:///c:/fwteam/include/ini.ch). El archivo principal [fivewin.ch](file:///c:/fwteam/include/fivewin.ch) (2,433 líneas) define cientos de comandos de alto nivel que se traducen a llamadas de métodos:

Code: Select all | Expand

// Así escribe el desarrollador:
DEFINE DIALOG oDlg TITLE "Mi Diálogo" SIZE 400, 300

@ 2, 3 BUTTON oBtn PROMPT "Aceptar" ACTION MsgInfo("Hola") OF oDlg

ACTIVATE DIALOG oDlg CENTERED

// El preprocesador traduce a:
oDlg := TDialog():New(,,,,,"Mi Diálogo",,,,,,,,,,400,300)
oBtn := TButton():New(2,3,"Aceptar",oDlg,{||MsgInfo("Hola")},...)
oDlg:Activate(,,,,.T.)

Análisis de Componentes Principales

1. Controles GUI (120 clases)

ComponenteArchivoLíneasDescripción
TWindow[window.prg](file:///c:/fwteam/source/classes/window.prg)4,470Clase base de todas las ventanas
TXBrowse[xbrowse.prg](file:///c:/fwteam/source/classes/xbrowse.prg)19,420Browse avanzado (el más complejo del framework)
TDialog[dialog.prg](file:///c:/fwteam/source/classes/dialog.prg)1,348Diálogos modales y no modales
TGet[tget.prg](file:///c:/fwteam/source/ceclasses/tget.prg)—Control de edición con soporte Unicode/UTF-8
TRibbontribbon.prg—Barra de cinta estilo Office
TWebView2twebview2.prg—Control web basado en Edge Chromium
TTreeViewttreevie.prg—Árboles jerárquicos con edición
TScintillascintila.prg—Editor de código con syntax highlighting

2. Inteligencia Artificial (10 clases)

FWH es pionero en integrar IA directamente en un framework GUI tradicional:

ClaseArchivoAPI
TOpenAItopenai.prgOpenAI GPT + Vision
TOllamatollama.prgOllama (LLMs locales) + Agents
TGeminitgemini.prgGoogle Gemini
TDeepSeektdeepseek.prgDeepSeek
TChatGPT[chatgpt.prg](file:///c:/fwteam/samples/ai/chatgpt.prg)ChatGPT
TKimitkimi.prgMoonshot Kimi
TGroktgrok.prgxAI Grok
TNeuralNettneuralnet.prgRedes neuronales
Transformer[transformer.prg](file:///c:/fwteam/samples/ai/transformer.prg)Transformers (Attention is All You Need)
TEmbeddingstembeddings.prgEmbeddings vectoriales

[!TIP]
El proyecto incluye operaciones de matrices en C ([matrixes.c](file:///c:/fwteam/source/function/matrixes.c), [fwmatrix.c](file:///c:/fwteam/source/function/fwmatrix.c)) con 17+ funciones para álgebra lineal, optimizadas para uso con redes neuronales y transformers.

3. Bases de Datos (15 clases)

ComponenteDescripción
FWMariaConnectionConector nativo MariaDB/MySQL (389KB en [fwmaria.prg](file:///c:/fwteam/source/internal/fwmaria.prg))
TDatabaseAbstracción para DBF/RDD
TODBCConectividad ODBC
TRecordSetADO RecordSet
TDBComboCombo box con datos de base de datos
FWRowSetRowset genérico para datos tabulares

4. Informes y PDF

ComponenteDescripción
FWPDFGeneración nativa de PDF (HaruPDF)
TReport/EasyReportSistema visual de informes
TPrinterImpresión directa
MyRptSistema alternativo de reporting

5. Comunicaciones y Web

ComponenteDescripción
TSocketSockets TCP/IP
TWebServerServidor web embebido
TWebClientCliente HTTP
TWebSocketWebSockets
TFTPCliente FTP
TSmtp/TPop3Email SMTP y POP3
TOAuthAutenticación OAuth2
TOutlookMail / TGmailEmail via Office365 y Gmail

6. Gráficos y Multimedia

ComponenteDescripción
GDI+Dibujo avanzado via gdipfwh.cpp y gdiplus.cpp
TGraphGráficos de datos
TImageVisor de imágenes con alpha
TVideoReproducción de video
TWebcamCaptura de webcam
TAnimateAnimaciones GIF

Métricas del Proyecto

MétricaValor
Archivos PRG (Harbour)256 en classes + 50 en ceclasses + extras
Archivos C197+ en function/winapi + 35 en internal
Archivos C++9 (GDI+, ActiveX, WebView, .NET)
Headers (CH/H)102 archivos
Archivo más grande[xbrowse.prg](file:///c:/fwteam/source/classes/xbrowse.prg) — 19,420 líneas (620 KB)
Header principal[fivewin.ch](file:///c:/fwteam/include/fivewin.ch) — 2,433 líneas (108 KB)
WebView header[webview.h](file:///c:/fwteam/source/internal/webview.h) — 82 KB
Fwmaria.prg389 KB (conector MariaDB más completo)
Total samples3,487 archivos
Profundidad máx. directorios5 niveles
Historial de cambios25,865 líneas (1993-2026)
Bitmaps / iconos incluidos1,121 + 403 + 62 cursores
Bibliotecas generadas7 (FiveH.lib, FiveHC.lib, y variantes 32/64)

Análisis de Calidad de Código

Fortalezas ✅

  1. Consistencia de nombrado: Todas las clases siguen el patrón T{NombreClase} (TWindow, TDialog, TXBrowse), un estándar heredado de Turbo Pascal / Borland.

  2. Documentación exhaustiva en [whatsnew.txt](file:///c:/fwteam/whatsnew.txt): Cada cambio está documentado con fecha, tipo (Fix/Enhancement/New), enlace al foro, y créditos al contribuidor.

  3. Sistema de preprocesador bien diseñado: Los comandos xCommand/xTranslate proporcionan una DSL (Domain Specific Language) que simplifica enormemente la sintaxis.

  4. Amplia cobertura de ejemplos: 3,487 archivos de ejemplo cubriendo virtualmente toda la funcionalidad.

  5. Soporte multi-compilador: El mismo código compila con BCC32, MSVC (32/64), llvm-clang, Harbour y xHarbour.

  6. Integración moderna: A pesar de sus 30+ años, el proyecto integra WebView2, OAuth2, múltiples APIs de IA, GDI+, y soporte Unicode/UTF-8.

  7. Funciones de "Clean Code" (líneas 57-79 de [fivewin.ch](file:///c:/fwteam/include/fivewin.ch)): Macros como IsArray(), IsString(), IsNum(), IsNil() que mejoran legibilidad.

Áreas de Mejora ⚠️

  1. Archivos monolíticos: [xbrowse.prg](file:///c:/fwteam/source/classes/xbrowse.prg) con 19,420 líneas y [fwmaria.prg](file:///c:/fwteam/source/internal/fwmaria.prg) con 389 KB son extremadamente grandes. Consideration de refactoring en módulos más pequeños.

  2. Nomenclatura inconsistente en archivos: Mezcla de convenciones (camelCase, lowercase, abreviaciones): ttreevie.prg vs twebview2.prg vs [btnbmp.prg](file:///c:/fwteam/source/classes/btnbmp.prg).

  3. Ausencia de tests automatizados: No se detectó un framework de testing unitario ni carpeta de tests automatizados.

  4. Documentación API limitada: Aunque existen 70 documentos en docs/, falta documentación inline sistemática en la mayoría de clases.

  5. Hardcoded paths: El Makefile contiene rutas como c:\vc98\bin\ que limitan portabilidad.

  6. Directorios de objetos vacíos: Múltiples directorios objh, objhc, objhm, etc. que se crean dinámicamente.


Testing y QA

AspectoEstado
Tests unitarios❌ No detectados
Tests de integración❌ No detectados
Tests E2E❌ No detectados
Framework de testingNo implementado
CI/CD PipelineNo detectado
Linters/FormattersNo detectados
CoverageN/A

[!WARNING]
La ausencia de tests automatizados es la debilidad más significativa del proyecto. La verificación se realiza mediante los 3,487 ejemplos y el feedback de la comunidad en los foros.

Estrategia de Branching y Releases

  • El proyecto usa Git pero sin evidencia de ramas feature/release
  • Los releases se identifican por fecha en whatsnew.txt y por la versión en fivewin.ch

Patrones de Diseño Identificados

PatrónImplementación
Template MethodTWindow:HandleEvent() — los subclases sobrescriben métodos específicos
ObserverCodeblocks (bInit, bPainted, bResized) como callbacks de eventos
FactoryComandos del preprocesador que invocan ::New() y ::ReDefine()
CompositeTWindow:aControls[] — arreglo de controles hijos dentro de ventanas
StrategybSkip, bGoTop, bGoBottom en TXBrowse para navegación configurable
AdapterWrappers C que adaptan Win32 API al modelo Harbour
Facadefivewin.ch actúa como fachada simplificando toda la API
MediatorTDialog:HandleEvent() media entre controles hijos
CommandCodeblocks asignados a botones: ACTION {|| MsgInfo("Hola") }
BridgeSeparación PRG (abstracción) / C (implementación nativa)

Innovaciones Destacadas

1. Integración de IA (2024-2026)

FWH es posiblemente el único framework xBase con soporte nativo para:

  • 7+ APIs de IA (OpenAI, Gemini, Ollama, DeepSeek, Kimi, Grok, ChatGPT)
  • Implementación de Transformers desde cero (basado en "Attention is All You Need")
  • Redes neuronales y embeddings vectoriales
  • Agentes AI con soporte de herramientas (tools/functions)

2. Operaciones Matriciales en C

17+ funciones de álgebra lineal optimizadas en C para uso con redes neuronales, incluyendo multiplicación de matrices, softmax, backpropagation, y gradient clipping.

3. WebView2 Nativo

Integración completa del motor Chromium de Edge, permitiendo crear aplicaciones híbridas desktop/web.

4. Soporte Unicode/UTF-8 Completo

Soporte para codepages asiáticos (Big5, GB2312, Thai), conversión automática ANSI↔Unicode, y API Unicode (MessageBoxW).


Recomendaciones

Prioridad Alta 🔴

  1. Implementar tests automatizados: Crear un framework de testing básico para las clases core
  2. Refactorizar archivos monolíticos: Dividir xbrowse.prg (19K líneas) en módulos más manejables

Prioridad Media 🟡

  1. Estandarizar nomenclatura de archivos: Unificar convención de nombrado
  2. Mejorar documentación inline: Agregar documentación de métodos al estilo JavaDoc
  3. Implementar CI/CD: Pipeline automatizado para compilación y verificación en cada commit

Prioridad Baja 🟢

  1. Eliminar rutas hardcoded: Parametrizar paths de compiladores en Makefiles
  2. Agregar archivos .editorconfig: Estandarizar formato de código
  3. Crear guía de contribución: CONTRIBUTING.md con estándares de código

Conclusión

FiveWin for Harbour es un framework maduro, extenso y activamente mantenido que ha evolucionado notablemente desde su creación en 1993. Su fortaleza principal radica en la productividad que ofrece al desarrollador a través de su sistema de preprocesador DSL y la amplísima biblioteca de clases. La reciente integración de múltiples APIs de IA demuestra una capacidad de innovación poco común en frameworks con más de 3 décadas de historia.

El proyecto se beneficiaría significativamente de la adopción de prácticas modernas de ingeniería de software como testing automatizado, CI/CD, y documentación API sistemática, pero su comunidad activa y la calidad de los ejemplos proporcionan una base sólida para cualquier desarrollador que trabaje con el framework.

Puntuación Global de Calidad: 7.5/10

  • Funcionalidad: ⭐⭐⭐⭐⭐ (9/10)
  • Documentación: ⭐⭐⭐ (6/10)
  • Mantenibilidad: ⭐⭐⭐ (6/10)
  • Innovación: ⭐⭐⭐⭐⭐ (9/10)
  • Testing: ⭐⭐ (3/10)
  • Arquitectura: ⭐⭐⭐⭐ (8/10)

Re: Antigravity as bugs solver and tech support

Posted: Sun Mar 01, 2026 10:28 am
by Antonio Linares

Enhanced version:

SKILL.md

Code: Select all | Expand

---
name: code-deep-analysis
description: Performs deep analysis of code repositories like DeepWiki. Use it to examine project structure, identify technologies, analyze architecture, detect design patterns, evaluate code quality, and generate exhaustive technical documentation. Supports three operation modes - RAG (contextual analysis), Deep Research (multi-turn investigation), and Simple Chat (direct technical responses). Ideal for understanding unknown codebases, performing technical due diligence, or documenting existing projects.
schema_version: "1.0"
category: code-analysis
version: 1.0.0
---

# Deep Code Analysis Skill

This skill allows you to analyze code repositories exhaustively, generating a complete understanding of the project similar to what DeepWiki offers. The analysis includes structure, architecture, technologies, patterns, and code quality.

It operates in **three modes**: contextual RAG analysis, multi-turn Deep Research, and direct Simple Chat — each with specific behaviors and focus levels suited to different investigation needs.

---

## When to Use This Skill

- When you need to understand an unknown codebase
- To perform technical due diligence on projects
- When documenting existing software architectures
- To identify technical debt and improvement opportunities
- When evaluating the overall quality of a project
- To generate automatic code documentation
- For deep, focused investigation of a specific functionality
- For technical audit of a specific file or module
- For iterative evaluation of an implementation
- To generate a consolidated technical conclusion

---

## Inputs

| Parameter | Type | Required | Description |
|---|---|---|---|
| `repo_path` | string | **yes** | Local path or URL of the repository to analyze |
| `repo_name` | string | **yes** | Name of the repository |
| `user_query` | string | **yes** | Specific question or topic to investigate within the repository |
| `mode` | string | no | Operation mode: `rag`, `deep_research`, or `simple_chat` (auto-detected if omitted) |
| `conversation_history` | object | no | Structured history of previous conversation to maintain continuity in multi-turn investigations |
| `contexts` | list | no | Relevant file fragments retrieved via semantic search |
| `research_iteration` | integer | no | Current iteration number in Deep Research mode |
| `language_name` | string | no | Language explicitly requested by the user for the response |

## Outputs

| Parameter | Type | Description |
|---|---|---|
| `response` | string | Structured Markdown response with technical analysis, iterative research, or final conclusion depending on the active mode |

---

## Operation Modes

This skill operates in three main modes, each with specific behavior:

| Mode | Purpose | Iterations | Focus Level |
|---|---|---|---|
| **RAG** | Contextual response based on files | 1 | High |
| **Deep Research** | Deep multi-turn investigation | Multiple | Very High |
| **Simple Chat** | Direct technical response | 1 | Specific |

---

### Mode 1: RAG (Contextual Analysis)

**Role:** You are a code assistant that answers user questions on a repository. You receive the user query, relevant context from files, and past conversation history.

**Purpose:** Answer specific questions using the user's query, context retrieved from files, and conversation history.

**Behavior:**
- Automatically detects the language of the query
- Responds in the same language
- If a specific language is requested, it takes priority over the query language
- Uses structured Markdown
- Organizes information with headings and lists
- Cites file paths using `inline code` formatting
- For code blocks, use triple backticks with language specification (` ```harbour `, ` ```c `, ` ```javascript `, etc.)
- Use `##` headings for major sections
- Use bullet points or numbered lists where appropriate
- Format tables using markdown table syntax when presenting structured data
- Use **bold** and *italic* for emphasis

**Context Processing:**
The RAG mode processes information in this order:
1. System prompt (role and formatting rules)
2. Conversation history (previous Q&A turns, if any)
3. Retrieved contexts (file fragments with file paths)
4. Current user prompt

**Strict Rules:**
- Do NOT include ` ```markdown ` fences at the beginning or end of the answer
- Start the response directly with the content
- Think step by step and ensure the answer is well-structured and visually organized
- The content will already be rendered as markdown, so just provide the raw markdown content
- Maintain clear visual organization

---

### Mode 2: Deep Research (Multi-Turn Investigation)

Designed for deep, strictly focused investigation across multiple iterations.

**Role:** You are an expert code analyst examining a repository. You are conducting a multi-turn Deep Research process to thoroughly investigate the specific topic in the user's query. Your goal is to provide detailed, focused information EXCLUSIVELY about this topic.

#### First Iteration

**Guidelines:**
- This is the first iteration of a multi-turn research process focused EXCLUSIVELY on the user's query
- Start the response with `## Research Plan`
- Outline the approach to investigating this specific topic
- If the topic is about a specific file or feature (like "Dockerfile"), focus ONLY on that file or feature
- Clearly state the specific topic being researched to maintain focus throughout all iterations
- Identify the key aspects that need to be researched
- Provide initial findings based on the information available
- End with `## Next Steps` indicating what will be investigated in the next iteration
- Do NOT provide a final conclusion yet — this is just the beginning of the research
- Do NOT include general repository information unless directly relevant to the query
- Remember that this topic will be maintained across all research iterations

**Restrictions:**
- Do NOT deviate from the specific topic
- Do NOT include irrelevant general information
- NEVER respond with just "Continue the research" as an answer — always provide substantive research findings
- Do NOT respond with empty messages
- Focus EXCLUSIVELY on the specific topic being researched — do not drift to related topics
- The research MUST directly address the original question

**Style:**
- Be concise but thorough
- Use markdown formatting to improve readability
- Cite specific files and code sections when relevant

#### Intermediate Iterations

**Guidelines:**
- CAREFULLY review the conversation history to understand what has been researched so far
- The response MUST build on previous research iterations — do NOT repeat information already covered
- Identify gaps or areas that need further exploration related to this specific topic
- Focus on one specific aspect that needs deeper investigation in this iteration
- Start the response with `## Research Update {iteration_number}`
- Clearly explain what is being investigated in this iteration
- Provide new insights that weren't covered in previous iterations
- Maintain continuity with previous research iterations — this is a continuous investigation
- Do NOT include general repository information unless directly relevant to the query
- If the topic is about a specific file or feature (like "Dockerfile"), focus ONLY on that file or feature

If it is the penultimate iteration (e.g., iteration 3 of 4), prepare a synthesis for closure in the next iteration.

**Restrictions:**
- Do NOT deviate from the main focus — focus EXCLUSIVELY on the specific topic
- NEVER respond with just "Continue the research" as an answer — always provide substantive research findings
- The research MUST directly address the original question

**Style:**
- Be concise but thorough
- Focus on providing new information, not repeating what's already been covered
- Use markdown formatting to improve readability
- Cite specific files and code sections when relevant

#### Final Iteration

**Guidelines:**
- This is the final iteration of the research process
- CAREFULLY review the entire conversation history to understand all previous findings
- Synthesize ALL findings from previous iterations into a comprehensive conclusion
- Start with `## Final Conclusion`
- The conclusion MUST directly address the original question
- Stay STRICTLY focused on the specific topic — do not drift to related topics
- Include specific code references and implementation details related to the topic
- Highlight the most important discoveries and insights about this specific functionality
- Provide a complete and definitive answer to the original question
- Ensure the conclusion builds on and references key findings from previous iterations
- If the topic is about a specific file or feature (like "Dockerfile"), focus ONLY on that file or feature
- May include actionable recommendations or insights when appropriate

**Forbidden:**
- Deviating to related topics
- Responding with "Continue the research" as an answer — always provide a complete conclusion
- Responding with open or incomplete phrases
- Including general repository information unless directly relevant to the query

**Style:**
- Be concise but thorough
- Use markdown formatting to improve readability
- Cite specific files and code sections when relevant
- Structure the response with clear headings
- End with actionable insights or recommendations when appropriate

---

### Mode 3: Simple Chat (Direct Response)

**Role:** You are an expert code analyst providing direct, concise, and accurate information about code repositories. You NEVER start responses with markdown headers or code fences.

Direct technical response mode.

**Characteristics:**
- Answer the user's question directly without ANY preamble or filler phrases
- Do NOT include any rationale, explanation, or extra comments before the answer
- Do NOT start with preambles like "Okay, here's a breakdown" or "Here's an explanation"
- Do NOT start with markdown headers like `## Analysis of...` or any file path references
- Do NOT start with ` ```markdown ` code fences
- Do NOT end the response with ` ``` ` closing fences
- Do NOT start by repeating or acknowledging the question
- JUST START with the direct answer to the question
- Start with the most relevant information that directly addresses the user's query

**Anti-pattern example (DO NOT do this):**
```## Analysis of `source/classes/xbrowse.prg`

This file contains...```
Instead, just start directly with:
```TXBrowse is a powerful data grid control that supports...```

**Style:**
- Format the response with proper markdown including headings, lists, and code blocks WITHIN the answer (not wrapping it)
- For code analysis, organize the response with clear sections
- Think step by step and structure the answer logically
- Use concise, direct language
- Prioritize accuracy over verbosity
- When showing code, include line numbers and file paths when relevant
- Use markdown formatting to improve readability
- Be precise and technical when discussing code
- The response language should match the user's query language

---

## How to Run the Analysis

### Phase 1: Initial Exploration

1. **Identify the project type**
   - Detect the main programming language
   - Identify the framework(s) used
   - Determine the application type (web, mobile, CLI, API, desktop, library, etc.)

2. **Map the directory structure**
   - List all top-level directories
   - Identify organizational patterns (DDD, MVC, Clean Architecture, layered, etc.)
   - Locate main configuration files
   - Measure directory depth and breadth

3. **Examine configuration files**
   - package.json, pyproject.toml, Cargo.toml, pom.xml, Makefile, .hbp, etc.
   - Build files: webpack.config.js, tsconfig.json, Makefile, .bat/.sh scripts
   - Container configuration: Dockerfile, docker-compose.yml
   - IDE/editor configuration: .editorconfig, .vscode/, .agent/

### Phase 2: Technology Analysis

1. **Main technology stack**
   - Languages and versions used
   - Backend and frontend frameworks
   - Databases and caching systems
   - Message queues and external services
   - AI/ML integrations

2. **Critical dependencies**
   - Main libraries and their purpose
   - Dependencies with known vulnerabilities
   - Outdated or unmaintained packages
   - Internal vs external dependency ratio

3. **Development tools**
   - Linters and formatters used
   - Testing systems
   - CI/CD tools
   - Task runners and bundlers
   - Build system complexity

### Phase 3: Architecture Analysis

1. **Architectural patterns**
   - Identify whether it uses MVC, MVP, MVVM, Clean Architecture, Hexagonal, etc.
   - Detect design patterns used (Factory, Observer, Strategy, Composite, Bridge, etc.)
   - Identify specific architectures (microservices, serverless, monolith)
   - Map class inheritance hierarchies

2. **Component structure**
   - Main modules and their responsibilities
   - Dependencies between components
   - Application entry and exit points
   - Communication patterns between components
   - Coupling and cohesion assessment

3. **Data flow**
   - How information flows through the system
   - APIs and contracts between modules
   - Integrations with external services
   - Event/callback patterns

### Phase 4: Code Analysis

1. **Overall quality**
   - Readability and maintainability
   - Cyclomatic complexity
   - Code duplication
   - Function and module length
   - Naming conventions consistency

2. **Good patterns identified**
   - SOLID principles applied
   - Dependency injection
   - Consistent error handling
   - Logging and monitoring
   - Data validation
   - Documentation coverage

3. **Areas for improvement**
   - Code smells detected
   - Frequent anti-patterns
   - Lack of documentation in critical functions
   - Insufficient testing coverage
   - Monolithic files needing refactoring
   - Hardcoded values or paths

### Phase 5: Testing and Quality

1. **Testing strategy**
   - Types of tests implemented (unit, integration, e2e)
   - Testing frameworks used
   - Current code coverage
   - Testing patterns employed
   - Sample/example coverage as implicit testing

2. **CI/CD**
   - Continuous integration pipeline
   - Deployment stages
   - Branching strategies
   - Release workflow
   - Build automation level

### Phase 6: Report Generation

1. **Report structure**
   - Executive summary
   - System architecture (with Mermaid diagrams when possible)
   - Complete technology stack
   - Component breakdown by category
   - Quantitative metrics table
   - Code quality analysis with scoring
   - Design patterns identified
   - Notable innovations
   - Findings and recommendations (prioritized)

2. **Output format**
   - Structured Markdown
   - Clear and navigable sections
   - Code examples when relevant
   - Actionable recommendations
   - Mermaid diagrams for architecture and class hierarchies
   - Tables for metrics and comparisons

---

## Decision Tree

```What mode should be used?
├── Specific question about a file/function → RAG Mode
├── Broad investigation requiring depth → Deep Research Mode
└── Quick technical question → Simple Chat Mode

Does the project have multiple services?
├── Yes → Identify inter-service communication (REST, gRPC, Message Queue)
└── No → Analyze as a monolithic application

Is there existing documentation?
├── Yes → Compare with actual implementation
└── No → Generate documentation based on code

Does the project have tests?
├── Yes → Analyze coverage and quality
└── No → Flag as a critical area for improvement

Is the codebase multi-language?
├── Yes → Analyze each language layer separately, then map interactions
└── No → Focus on single-language patterns and idioms```

---

## Output Format

The analysis should generate a structured report with the following sections:

```markdown# Deep Analysis of [Project Name]

## Executive Summary
[Brief description of the project and its main characteristics]

## Technology Stack
- **Language**: [version]
- **Framework**: [version]
- **Database**: [type and version]
- **Other components**: [list]

## Project Structure
[Description of directory organization]

## Architecture
[Identified patterns and architecture description]
[Mermaid diagrams for class hierarchy and data flow]

## Component Breakdown
### [Category 1] (~N classes/modules)
| Component | File | Description |
|---|---|---|

### [Category 2]
...

## Quantitative Metrics
| Metric | Value |
|---|---|

## Code Analysis
### Overall Quality
[Score and relevant metrics]

### Identified Patterns
[List of design patterns found]

### Areas for Improvement
[Issues found with suggestions]

## Testing
[Current state of tests and coverage]

## Notable Innovations
[Unique or remarkable features of the project]

## Recommendations
### High Priority 🔴
### Medium Priority 🟡
### Low Priority 🟢

## Conclusion
[Global quality score with breakdown by category]```

---

## Language Handling

The skill:
- Detects the language of the user's query automatically
- Responds in the SAME language as the user's query
- **IMPORTANT:** If a specific language is requested in the prompt, that language takes priority over the detected query language
- Maintains linguistic consistency across ALL iterations in Deep Research mode
- Never switches language mid-iteration
- Code comments and technical terms may remain in the original language of the codebase

---

## Formatting Rules

All responses must:
- Use structured Markdown with proper syntax for all formatting
- For code blocks, use triple backticks with language specification (` ```harbour `, ` ```c `, ` ```javascript `, etc.)
- Use `##` headings for major sections
- Use bullet points or numbered lists where appropriate
- Format tables using markdown table syntax when presenting structured data
- Use **bold** and *italic* for emphasis
- Reference file paths as `inline code`
- Maintain visual clarity
- Use Mermaid diagrams for architecture visualization when possible
- Include emoji indicators for priority levels (🔴🟡🟢)

**Critical formatting constraints:**
1. Do NOT include ` ```markdown ` fences at the beginning or end of the answer
2. Start the response directly with the content
3. The content will already be rendered as markdown, so just provide the raw markdown content
4. Think step by step and ensure the answer is well-structured and visually organized

---

## Focus Enforcement

The skill guarantees:
- Exclusive focus on the queried topic
- Continuity in multi-turn investigations
- Technical coherence between iterations
- Avoidance of topic drift
- Responses directly aligned with the original question
- If the topic is about a specific file or feature, ONLY that file or feature is analyzed
- General repository information is excluded unless directly relevant to the query
- NEVER responds with just filler phrases like "Continue the research" — always provides substantive findings
- Cross-references previous iteration findings to build a coherent narrative

---

## Usage Examples

### Full analysis of an unknown project
```Analyze the repository at /workspace/my-project as DeepWiki would```

### Focus on a specific aspect
```Perform an architecture analysis of the project focusing on design patterns```

### Comparison with best practices
```Evaluate the code quality comparing with clean code principles```

### Deep research on a specific module
```Investigate the database connectivity layer in depth using Deep Research mode```

### Quick question about a file
```What does the TXBrowse class do and what are its main methods?```

---

## Metrics to Collect

- Number of files per language
- Total lines of code
- Maximum directory depth
- Number of direct dependencies
- Test coverage (if applicable)
- Average cyclomatic complexity
- Average number of functions/classes per file
- Largest files by line count
- Class inheritance depth
- Number of samples/examples

---

## Prompt Template Reference

For integration with embedding/RAG pipelines, the context processing follows this template structure:

```<START_OF_SYS_PROMPT>
{system_prompt}
{output_format_str}
<END_OF_SYS_PROMPT>

{# If conversation history exists #}
<START_OF_CONVERSATION_HISTORY>
{for each dialog_turn in conversation_history}
  {turn_number}.
  User: {user_query}
  You: {assistant_response}
{end for}
<END_OF_CONVERSATION_HISTORY>

{# If file contexts are provided #}
<START_OF_CONTEXT>
{for each context in contexts}
  {index}.
  File Path: {context.file_path}
  Content: {context.text}
{end for}
<END_OF_CONTEXT>

<START_OF_USER_PROMPT>
{user_input}
<END_OF_USER_PROMPT>```

**Deep Research iterations** use role/guidelines/style blocks:

```<role>
  Expert analyst identity, repository info, language constraint, iteration context
</role>

<guidelines>
  Iteration-specific behavioral rules (first / intermediate / final)
</guidelines>

<style>
  Output formatting preferences (concise, markdown, citations)
</style>```

This structure ensures consistent behavior whether the skill is invoked as a standalone agent, integrated with a semantic search engine, or orchestrated through a multi-turn pipeline.

---

## Available Helper Scripts

The skill includes optional Harbour scripts that can be used during the analysis:

- **analyze-structure.prg**: Analyzes the directory structure and generates a tree with file counts and sizes
- **detect-tech-stack.prg**: Detects technologies based on file extensions and configuration files
- **calculate-metrics.prg**: Calculates code metrics (lines per language, file counts, directory depth)

### analyze-structure.prg

```harbour/*
 * Directory Structure Analyzer
 * Usage: analyze-structure <path> [max_depth]
 * Generates a visual tree of the directory structure
 */

#include "directry.ch"

FUNCTION Main( cPath, cMaxDepth )

   LOCAL nMaxDepth := 3

   DEFAULT cPath     := "."
   DEFAULT cMaxDepth := "3"

   nMaxDepth := Val( cMaxDepth )

   ? "Directory Structure Analysis"
   ? Replicate( "=", 40 )
   ? ""

   AnalyzeDir( cPath, 0, nMaxDepth )

RETURN NIL

STATIC FUNCTION AnalyzeDir( cPath, nLevel, nMaxDepth )

   LOCAL aFiles, aFile
   LOCAL nFiles := 0, nDirs := 0
   LOCAL cIndent := Replicate( "  ", nLevel )

   IF nLevel > nMaxDepth
      RETURN NIL
   ENDIF

   aFiles := Directory( cPath + "\*.*", "D" )

   FOR EACH aFile IN aFiles
      IF aFile[ F_NAME ] == "." .OR. aFile[ F_NAME ] == ".."
         LOOP
      ENDIF

      IF "D" $ aFile[ F_ATTR ]
         nDirs++
         ? cIndent + "[DIR] " + aFile[ F_NAME ]
         AnalyzeDir( cPath + "\" + aFile[ F_NAME ], nLevel + 1, nMaxDepth )
      ELSE
         nFiles++
      ENDIF
   NEXT

   ? cIndent + "  (" + LTrim( Str( nFiles ) ) + " files, " + ;
     LTrim( Str( nDirs ) ) + " subdirs)"

RETURN NIL```

### detect-tech-stack.prg

```harbour/*
 * Technology Stack Detector
 * Usage: detect-tech-stack <path>
 * Detects programming languages and frameworks from file extensions
 * and configuration files
 */

FUNCTION Main( cPath )

   LOCAL aExtensions := {}
   LOCAL aTechFiles  := { ;
      { "package.json",     "Node.js / JavaScript" }, ;
      { "pyproject.toml",   "Python"               }, ;
      { "Cargo.toml",       "Rust"                  }, ;
      { "pom.xml",          "Java (Maven)"          }, ;
      { "build.gradle",     "Java (Gradle)"         }, ;
      { "Makefile",         "Make build system"     }, ;
      { "Dockerfile",       "Docker"                }, ;
      { "docker-compose.yml", "Docker Compose"      }, ;
      { ".hbp",             "Harbour"               }, ;
      { "fivewin.ch",       "FiveWin for Harbour"   }, ;
      { "tsconfig.json",    "TypeScript"            }, ;
      { "webpack.config.js","Webpack"               }, ;
      { "go.mod",           "Go"                    }, ;
      { "CMakeLists.txt",   "CMake"                 }, ;
      { ".csproj",          "C# / .NET"             }  ;
   }

   DEFAULT cPath := "."

   ? "Technology Stack Detection"
   ? Replicate( "=", 40 )
   ? ""

   // Detect by config files
   ? "## Detected Technologies"
   DetectByConfigFiles( cPath, aTechFiles )

   ? ""
   ? "## Languages by Extension"
   CountByExtension( cPath, aExtensions )

RETURN NIL

STATIC FUNCTION DetectByConfigFiles( cPath, aTechFiles )

   LOCAL aItem

   FOR EACH aItem IN aTechFiles
      IF File( cPath + "\" + aItem[ 1 ] ) .OR. ;
         File( cPath + "\include\" + aItem[ 1 ] )
         ? "  [✓] " + aItem[ 2 ] + " (" + aItem[ 1 ] + ")"
      ENDIF
   NEXT

RETURN NIL

STATIC FUNCTION CountByExtension( cPath, aExtensions )

   LOCAL aLangs := { ;
      { ".prg", "Harbour/xBase", 0 }, ;
      { ".c",   "C",             0 }, ;
      { ".cpp", "C++",           0 }, ;
      { ".h",   "C/C++ Header",  0 }, ;
      { ".ch",  "Clipper Header", 0 }, ;
      { ".js",  "JavaScript",    0 }, ;
      { ".ts",  "TypeScript",    0 }, ;
      { ".py",  "Python",        0 }, ;
      { ".rb",  "Ruby",          0 }, ;
      { ".go",  "Go",            0 }, ;
      { ".rs",  "Rust",          0 }, ;
      { ".java","Java",          0 }, ;
      { ".cs",  "C#",            0 }, ;
      { ".bat", "Batch script",  0 }, ;
      { ".sh",  "Shell script",  0 }, ;
      { ".md",  "Markdown",      0 }, ;
      { ".html","HTML",          0 }, ;
      { ".css", "CSS",           0 }  ;
   }
   LOCAL aItem

   CountFilesRecursive( cPath, aLangs )

   FOR EACH aItem IN aLangs
      IF aItem[ 3 ] > 0
         ? "  " + PadR( aItem[ 2 ], 20 ) + LTrim( Str( aItem[ 3 ] ) ) + " files"
      ENDIF
   NEXT

RETURN NIL

STATIC FUNCTION CountFilesRecursive( cPath, aLangs )

   LOCAL aFiles, aFile, aItem, cExt

   aFiles := Directory( cPath + "\*.*", "D" )

   FOR EACH aFile IN aFiles
      IF aFile[ F_NAME ] == "." .OR. aFile[ F_NAME ] == ".."
         LOOP
      ENDIF
      IF "D" $ aFile[ F_ATTR ]
         IF aFile[ F_NAME ] != ".git"
            CountFilesRecursive( cPath + "\" + aFile[ F_NAME ], aLangs )
         ENDIF
      ELSE
         cExt := Lower( SubStr( aFile[ F_NAME ], RAt( ".", aFile[ F_NAME ] ) ) )
         FOR EACH aItem IN aLangs
            IF cExt == aItem[ 1 ]
               aItem[ 3 ]++
               EXIT
            ENDIF
         NEXT
      ENDIF
   NEXT

RETURN NIL```

### calculate-metrics.prg

```harbour/*
 * Code Metrics Calculator
 * Usage: calculate-metrics <path>
 * Calculates lines of code, file counts, and complexity estimates
 */

#include "directry.ch"

STATIC nTotalLines  := 0
STATIC nTotalFiles  := 0
STATIC nMaxDepth    := 0
STATIC nLargestFile := 0
STATIC cLargestName := ""

FUNCTION Main( cPath )

   LOCAL aCodeExts := { ".prg", ".c", ".cpp", ".h", ".ch", ".js", ".ts", ;
                        ".py", ".go", ".rs", ".java", ".cs" }

   DEFAULT cPath := "."

   ? "Code Metrics Report"
   ? Replicate( "=", 40 )
   ? ""

   ProcessDir( cPath, aCodeExts, 0 )

   ? ""
   ? "## Summary"
   ? "  Total source files:  " + LTrim( Str( nTotalFiles ) )
   ? "  Total lines of code: " + LTrim( Str( nTotalLines ) )
   ? "  Max directory depth: " + LTrim( Str( nMaxDepth ) )
   ? "  Largest file:        " + cLargestName + ;
     " (" + LTrim( Str( nLargestFile ) ) + " lines)"

   IF nTotalFiles > 0
      ? "  Avg lines per file:  " + LTrim( Str( Int( nTotalLines / nTotalFiles ) ) )
   ENDIF

RETURN NIL

STATIC FUNCTION ProcessDir( cPath, aCodeExts, nDepth )

   LOCAL aFiles, aFile, cExt, nLines

   IF nDepth > nMaxDepth
      nMaxDepth := nDepth
   ENDIF

   aFiles := Directory( cPath + "\*.*", "D" )

   FOR EACH aFile IN aFiles
      IF aFile[ F_NAME ] == "." .OR. aFile[ F_NAME ] == ".."
         LOOP
      ENDIF
      IF "D" $ aFile[ F_ATTR ]
         IF aFile[ F_NAME ] != ".git" .AND. aFile[ F_NAME ] != "node_modules"
            ProcessDir( cPath + "\" + aFile[ F_NAME ], aCodeExts, nDepth + 1 )
         ENDIF
      ELSE
         cExt := Lower( SubStr( aFile[ F_NAME ], RAt( ".", aFile[ F_NAME ] ) ) )
         IF AScan( aCodeExts, cExt ) > 0
            nTotalFiles++
            nLines := CountLines( cPath + "\" + aFile[ F_NAME ] )
            nTotalLines += nLines
            IF nLines > nLargestFile
               nLargestFile := nLines
               cLargestName := cPath + "\" + aFile[ F_NAME ]
            ENDIF
         ENDIF
      ENDIF
   NEXT

RETURN NIL

STATIC FUNCTION CountLines( cFile )

   LOCAL nHandle, cLine, nCount := 0

   nHandle := FOpen( cFile )

   IF nHandle >= 0
      DO WHILE ! HB_FEof( nHandle )
         cLine := HB_FReadLine( nHandle )
         nCount++
      ENDDO
      FClose( nHandle )
   ENDIF

RETURN nCount```

Run any of these scripts with Harbour: `hbrun analyze-structure.prg <path>`

Re: Antigravity as bugs solver and tech support

Posted: Sun Mar 01, 2026 10:37 am
by Antonio Linares

Análisis Profundo de FiveWin para Harbour (FWH)

Resumen Ejecutivo

FiveWin para Harbour (FWH) es un framework de desarrollo de aplicaciones Windows con más de 30 años de historia (desde 1993), desarrollado por FiveTech Software. Es una de las bibliotecas de GUI para Windows más maduras y completas del ecosistema Harbour/xBase, diseñada para crear aplicaciones de escritorio empresariales nativas de Windows.

El proyecto actual (versión FWH 25.12) es una base de código masiva que comprende aproximadamente 700+ archivos fuente en Harbour (.prg) y C/C++, con 256 clases de GUI, 3,487+ archivos de ejemplo, y soporte para arquitecturas de 32 y 64 bits. Notablemente, en los últimos años se ha integrado soporte para IA (ChatGPT, Ollama, Gemini, DeepSeek, Kimi, Transformers) y tecnologías web modernas (WebView2).


Stack Tecnológico

ComponenteTecnologíaVersión/Notas
Lenguaje PrincipalHarbour / xBaseCompatible con Harbour y xHarbour
Lenguaje SecundarioC / C++Win32 API bindings, GDI+
API del SOWin32 APIWindows NT/2000/XP/7/8/10/11
GráficosGDI / GDI+[gdipfwh.cpp](file:///c:/fwteam/source/winapi/gdipfwh.cpp), [gdiplus.cpp](file:///c:/fwteam/source/winapi/gdiplus.cpp)
CompiladoresBorland BCC32, MSVC, LLVM-ClangMulti-compilador
Build SystemNMake / Makefiles[fwh.mak](file:///c:/fwteam/fwh.mak), [fw64.mak](file:///c:/fwteam/fw64.mak), etc.
Base de DatosDBF, MySQL/MariaDB, PostgreSQL, ODBC, ADOMúltiples backends
WebWebView2, WebSockets, HTTP ServerChromium embebido
IA/MLOpenAI, Ollama, Gemini, DeepSeek, Kimi, TransformerAPI curl + implementación nativa
PDFharuPDF, FWPDFGeneración nativa
CorreoSMTP, POP3, OAuth2, Gmail, OutlookSoporte moderno OAuth

Estructura del Proyecto

Code: Select all | Expand

c:\fwteam\
├── source/                    # Código fuente principal (~693 archivos)
│   ├── classes/               # 256 clases Harbour (.prg) - GUI, controles, AI
│   ├── ceclasses/             # 50 clases Windows CE
│   ├── function/              # 147 funciones de utilidad (C + Harbour)
│   ├── winapi/                # 162 wrappers Win32 API (C + Harbour)
│   └── internal/              # 78+ archivos internos (C/C++ + Harbour)
├── include/                   # 102 archivos de cabecera (.ch, .h)
│   └── fivewin.ch             # Cabecera principal (2,433 líneas, 108KB)
├── samples/                   # ~3,487 archivos de ejemplo
│   ├── ai/                    # 56 ejemplos de IA
│   ├── ui/                    # 474+ ejemplos de interfaz
│   ├── web/webview/           # 106+ ejemplos web
│   ├── database/              # Ejemplos de base de datos
│   └── ...                    # 56 subdirectorios temáticos
├── lib/                       # 70 archivos de bibliotecas compiladas
├── bitmaps/                   # 1,121 recursos gráficos
├── icons/                     # 403 iconos
├── cursors/                   # 62 cursores
├── docs/                      # 70 archivos de documentación
├── manual/                    # 17 archivos del manual
├── mysql/                     # 48 archivos MySQL
├── makes/                     # 16 makefiles alternativos
├── dll/                       # 28 DLLs
├── whatsnew.txt               # Registro de cambios (25,865 líneas, 1.1MB)
└── *.mak                      # Makefiles principales (9 variantes)

Arquitectura

Patrón Arquitectónico Principal

FWH sigue una arquitectura orientada a objetos basada en una jerarquía de clases con herencia profunda, combinada con un preprocessador de comandos DSL que traduce sintaxis declarativa xBase a llamadas OOP.

classDiagram class TWindow { +hWnd +oWnd +nTop, nLeft, nBottom, nRight +aControls[] +oMenu +oMsgBar +Paint() +HandleEvent() +Resize() +End() } class TDialog { +Activate() +Redefine() } class TMdiFrame { +oWndClient } class TControl { +nId +bSetGet +bWhen +bValid +Refresh() } class TXBrowse { +aCols[] +oRs / cAlias +SaveState() +ResetState() +ToXlsx() } class TGet { +VarGet() +VarPut() +Picture } class TBar { +aControls[] } class TMenu { +aItems[] } TWindow <|-- TDialog TWindow <|-- TMdiFrame TWindow <|-- TControl TControl <|-- TXBrowse TControl <|-- TGet TControl <|-- TComboBox TControl <|-- TListBox TControl <|-- TCheckBox TControl <|-- TButton TControl <|-- TBtnBmp TControl <|-- TRichEdit5 TControl <|-- TPanel TWindow *-- TBar TWindow *-- TMenu TWindow *-- TMsgBar

Capas de la Arquitectura

graph TD A["Capa de Aplicación(Archivos .prg del usuario)"] --> B B["Capa de Comandos DSL(fivewin.ch - preprocessador)"] --> C C["Capa de Clases Harbour(source/classes/*.prg)"] --> D D["Capa de Funciones Utilidad(source/function/*.prg + *.c)"] --> E E["Capa Win32 API Wrapper(source/winapi/*.c)"] --> F F["Win32 API / GDI / GDI+(Windows OS)"]
C --> G["Capa Interna(source/internal/*.c + *.cpp)"] G --> F

Sistema de Preprocessador de Comandos (DSL)

Una de las innovaciones más distintivas de FWH es su sistema de comandos basado en preprocessador definido en [fivewin.ch](file:///c:/fwteam/include/fivewin.ch) (108KB, 2,433 líneas). Este sistema traduce una sintaxis declarativa legible:

Code: Select all | Expand

@ 10, 10 BUTTON oBtn PROMPT "Click Me" ;
   SIZE 100, 30 ;
   ACTION MsgInfo("Hello!") ;
   OF oDlg

A las correspondientes llamadas OOP internas:

Code: Select all | Expand

oBtn := TButton():New( 10, 10, "Click Me", oDlg, ;
   {|| MsgInfo("Hello!")}, 100, 30, ... )

Este DSL cubre todos los controles de la biblioteca: ventanas, diálogos, botones, gets, combos, listboxes, xbrowse, menús, ribbons, barras, y más.


Desglose de Componentes

Controles UI (150 clases)

ComponenteArchivoTamañoDescripción
TXBrowse[xbrowse.prg](file:///c:/fwteam/source/classes/xbrowse.prg)621 KBGrid de datos avanzado, el más grande del framework
TGet[tget.prg](file:///c:/fwteam/source/classes/tget.prg)165 KBControl GET mejorado (edición de campos)
TFGet[fget.prg](file:///c:/fwteam/source/classes/fget.prg)154 KBVariante GET con funcionalidad extendida
TWindow[window.prg](file:///c:/fwteam/source/classes/window.prg)131 KBClase base de ventanas
TGraph[tgraph.prg](file:///c:/fwteam/source/classes/tgraph.prg)113 KBGráficos y charts
TEReport[tereport.prg](file:///c:/fwteam/source/classes/tereport.prg)96 KBEasy Report
TRichEdit5[triched5.prg](file:///c:/fwteam/source/classes/triched5.prg)101 KBControl RichEdit moderno
TMenu[menu.prg](file:///c:/fwteam/source/classes/menu.prg)99 KBSistema de menús
TDataRow[datarow.prg](file:///c:/fwteam/source/classes/datarow.prg)90 KBManejo de datos por registro
TWBrowse[wbrowse.prg](file:///c:/fwteam/source/classes/wbrowse.prg)84 KBBrowse de base de datos clásico
TScintilla[scintila.prg](file:///c:/fwteam/source/classes/scintila.prg)176 KBEditor de código con Scintilla
TRibbon[tribbon.prg](file:///c:/fwteam/source/classes/tribbon.prg)72 KBRibbon UI à la Office

Clases de IA (10 clases)

ComponenteArchivoDescripción
TChatGPT[chatgpt.prg](file:///c:/fwteam/source/classes/chatgpt.prg)Integración con OpenAI Chat API
TOpenAI[topenai.prg](file:///c:/fwteam/source/classes/topenai.prg)API OpenAI con Vision
TOllama[tollama.prg](file:///c:/fwteam/source/classes/tollama.prg)LLMs locales via Ollama + Agents
TGemini[tgemini.prg](file:///c:/fwteam/source/classes/tgemini.prg)Google Gemini AI
TDeepSeek[tdeepseek.prg](file:///c:/fwteam/source/classes/tdeepseek.prg)DeepSeek AI
TKimi[tkimi.prg](file:///c:/fwteam/source/classes/tkimi.prg)Moonshot Kimi AI
Transformer[transformer.prg](file:///c:/fwteam/source/classes/transformer.prg)Implementación nativa de Transformers
TNeuralNet[tneuralnet.prg](file:///c:/fwteam/source/classes/tneuralnet.prg)Red neuronal nativa
TEmbeddings[tembeddings.prg](file:///c:/fwteam/source/classes/tembeddings.prg)Vectores de embeddings

Conectividad y Redes (20 clases)

ComponenteArchivoDescripción
TSocket[tsocket.prg](file:///c:/fwteam/source/classes/tsocket.prg)Sockets TCP/IP
TWebServer[twebserv.prg](file:///c:/fwteam/source/classes/twebserv.prg)Servidor HTTP
TWebView2[twebview2.prg](file:///c:/fwteam/source/classes/twebview2.prg)Chromium embebido
TWebSocket[twebsock.prg](file:///c:/fwteam/source/classes/twebsock.prg)WebSockets
TFTP[tftp.prg](file:///c:/fwteam/source/classes/tftp.prg) / [tftpserv.prg](file:///c:/fwteam/source/classes/tftpserv.prg)Cliente/Servidor FTP
TSMTP[tsmtp.prg](file:///c:/fwteam/source/classes/tsmtp.prg)Envío de correos SMTP
TPOP3[tpop3.prg](file:///c:/fwteam/source/classes/tpop3.prg)Lectura de correos POP3
TOAuth[oauth.prg](file:///c:/fwteam/source/classes/oauth.prg)Autenticación OAuth2
TGmail[gmail.prg](file:///c:/fwteam/source/classes/gmail.prg)Integración Gmail
TOutlookMail[outlookmail.prg](file:///c:/fwteam/source/classes/outlookmail.prg)Integración Outlook

Base de Datos (15 componentes)

ComponenteArchivoDescripción
TDatabase[database.prg](file:///c:/fwteam/source/classes/database.prg)Abstracción DBF
FWMaria[fwmaria.prg](file:///c:/fwteam/source/internal/fwmaria.prg) (390KB)MariaDB/MySQL client (el más grande en internal)
TODBC[todbc.prg](file:///c:/fwteam/source/classes/todbc.prg)Conectividad ODBC
TRecSet[trecset.prg](file:///c:/fwteam/source/classes/trecset.prg)ADO RecordSet
TDbODBC[tdbodbc.prg](file:///c:/fwteam/source/classes/tdbodbc.prg)ODBC DBF-compatible
TDict[tdict.prg](file:///c:/fwteam/source/classes/tdict.prg)Data Dictionary
TArrData[tarrdata.prg](file:///c:/fwteam/source/classes/tarrdata.prg)Arrays como datos

Métricas Cuantitativas

MétricaValor
Archivos fuente (.prg)460+
Archivos fuente (.c/.cpp)240+
Archivos de cabecera (.ch/.h)102
Clases Harbour256 (desktop) + 50 (Windows CE)
Archivos de ejemplo3,487
Líneas en whatsnew.txt25,865
Tamaño fivewin.ch108 KB (2,433 líneas)
Archivo fuente más grande[xbrowse.prg](file:///c:/fwteam/source/classes/xbrowse.prg) (621 KB)
Makefiles9 variantes (32/64-bit, BCC/MSVC/xHarbour)
Años de desarrollo33 años (1993-2026)
Versión actualFWH 25.12
Bibliotecas generadasFiveH.lib, FiveHC.lib + variantes 32/64

Análisis de Código

Calidad General: ⭐⭐⭐⭐ (8/10)

Fortalezas:

  • 🟢 Consistencia excepcional: 30+ años manteniendo convenciones de nombres y patrones
  • 🟢 DSL expresivo: El preprocessador de comandos crea una experiencia RAD muy productiva
  • 🟢 Cobertura exhaustiva: Cubre prácticamente todos los controles Win32 y APIs modernas
  • 🟢 Retrocompatibilidad: El código de hace 20 años sigue funcionando
  • 🟢 Documentación por ejemplos: 3,487+ archivos de ejemplo (cobertura implícita excepcional)
  • 🟢 Innovación continua: Integración de IA, WebView2, OAuth2 en 2024-2026

Áreas a mejorar:

  • 🟡 Archivos monolíticos: [xbrowse.prg](file:///c:/fwteam/source/classes/xbrowse.prg) tiene 621KB — candidato a refactorización
  • 🟡 FWMaria ([fwmaria.prg](file:///c:/fwteam/source/internal/fwmaria.prg)) con 390KB en internal/ es extremadamente grande
  • 🟡 Sin tests unitarios formales: La cobertura de tests se basa en los 3,487+ samples
  • 🟡 Documentación inline: Algunos archivos C carecen de documentación de funciones

Patrones de Diseño Identificados

PatrónUsoEjemplo
Template MethodExtensoTWindow define flujo, subclases override
ObserverExtensoSistema de eventos bAction, bWhen, bValid
CompositeExtensoaControls[] en TWindow/TControl
FactoryParcialNew() y Redefine() como factorías
StrategyExtensoCode blocks como bSetGet, bAction
BridgeExtensoHarbour ↔ C via HB_FUNC()
DecoratorParcialSkins, GDI+ rendering overlays
CommandExtensoPreprocessador DSL traduce comandos a objetos
FacadeExtensoAPI simplificada sobre Win32 API compleja

Testing

Estrategia de Testing

FWH utiliza un enfoque de testing basado en ejemplos (implicit testing via samples):

TipoCoberturaNotas
Ejemplos/Samples3,487 archivosDemostración y validación funcional
Tests unitariosNo formalSin framework de testing unitario
Tests de integraciónVia samplesPrueban combinaciones de componentes
Tests de regresiónVia whatsnew.txtLos fixes documentan los bugs resueltos

CI/CD

  • Sin pipeline CI/CD automatizado: El build se realiza con scripts [.bat](file:///c:/fwteam/mfwh.bat) y makefiles
  • Build multi-compilador: Scripts para BCC32, MSVC 32/64, xHarbour, LLVM-Clang
  • Estrategia de releases: Mensuales, documentadas exhaustivamente en [whatsnew.txt](file:///c:/fwteam/whatsnew.txt)

Innovaciones Notables

  1. 🤖 Integración de IA nativa: FWH es probablemente el único framework xBase con clases nativas para ChatGPT, Ollama, Gemini, DeepSeek, Kimi y Transformers, incluyendo soporte de Agents y Neural Networks implementadas en C puro ([fwmatrix.c](file:///c:/fwteam/source/function/fwmatrix.c), [matrixes.c](file:///c:/fwteam/source/function/matrixes.c))

  2. 📝 DSL preprocessador: El sistema #xcommand / #xtranslate en [fivewin.ch](file:///c:/fwteam/include/fivewin.ch) crea un lenguaje específico del dominio que es simultáneamente legible y potente, anticipándose décadas a las tendencias actuales de DSLs

  3. 🌐 WebView2 integrado: Soporte de Chromium embebido con web scraping, permitiendo interfaces híbridas nativas + web

  4. 📊 Clase Transformer nativa: Implementación completa de la arquitectura "Attention is All You Need" de Google, con operaciones de matrices optimizadas en C

  5. 🔐 OAuth2 moderno: Integración OAuth para Gmail y Outlook365, manteniendo relevancia con autenticación moderna

  6. 📱 Windows CE: Mantenimiento de una línea completa de 50 clases para dispositivos móviles Windows CE


Recomendaciones

Alta Prioridad 🔴

  • Refactorizar [xbrowse.prg](file:///c:/fwteam/source/classes/xbrowse.prg) (621KB): Dividir en módulos más pequeños (rendering, edición, datos, exportación)
  • Refactorizar [fwmaria.prg](file:///c:/fwteam/source/internal/fwmaria.prg) (390KB): Separar funciones de conexión, queries, schema management

Media Prioridad 🟡

  • Implementar tests unitarios: Crear un framework de testing básico con hbtest o similar
  • Documentación API: Generar documentación automática desde los archivos .ch con los comandos disponibles
  • Modernizar build: Considerar migrar a HBP (Harbour Project) como sistema de build unificado

Baja Prioridad 🟢

  • Consolidar archivos internos: Algunos archivos C pequeños en winapi/ podrían combinarse
  • Agregar CI: Configurar pipeline de build automático para detectar regresiones
  • Unificar clases de IA: Crear una interfaz común TLLM para todas las clases de IA

Conclusión

Puntuación Global: 8.2 / 10

CategoríaPuntuaciónPeso
Completitud funcional9.5/10Alta
Calidad del código7.5/10Alta
Arquitectura8.0/10Alta
Documentación7.0/10Media
Testing6.5/10Media
Innovación9.0/10Media
Retrocompatibilidad9.5/10Alta
Mantenibilidad7.5/10Alta
Evolución activa9.0/10Alta

FWH es un proyecto excepcional dado su alcance, longevidad y relevancia continua. La adición de funcionalidades de IA, WebView2, OAuth2 moderno y la implementación de Transformers demuestra una visión de futuro notable. Su principal desafío es la escala de algunos archivos monolíticos, pero su coherencia arquitectónica de 30+ años es remarcable.


Re: Antigravity as bugs solver and tech support

Posted: Sun Mar 01, 2026 10:44 am
by Antonio Linares

Skills are a very powerful extension to AI engines.

We need to practise building Skills so we can take advantage of them :wink: :idea:


Re: Antigravity as bugs solver and tech support

Posted: Sun Mar 01, 2026 10:56 am
by Antonio Linares

Enhanced version:

SKILL.md

Code: Select all | Expand

---
name: code-deep-analysis
description: Performs deep analysis of code repositories like DeepWiki. Use it to examine project structure, identify technologies, analyze architecture, detect design patterns, evaluate code quality, and generate exhaustive technical documentation. Supports three operation modes - RAG (contextual analysis), Deep Research (multi-turn investigation), and Simple Chat (direct technical responses). Ideal for understanding unknown codebases, performing technical due diligence, or documenting existing projects.
schema_version: "1.0"
category: code-analysis
version: 1.0.0
---

# Deep Code Analysis Skill

This skill allows you to analyze code repositories exhaustively, generating a complete understanding of the project similar to what DeepWiki offers. The analysis includes structure, architecture, technologies, patterns, and code quality.

It operates in **three modes**: contextual RAG analysis, multi-turn Deep Research, and direct Simple Chat — each with specific behaviors and focus levels suited to different investigation needs.

---

## When to Use This Skill

- When you need to understand an unknown codebase
- To perform technical due diligence on projects
- When documenting existing software architectures
- To identify technical debt and improvement opportunities
- When evaluating the overall quality of a project
- To generate automatic code documentation
- For deep, focused investigation of a specific functionality
- For technical audit of a specific file or module
- For iterative evaluation of an implementation
- To generate a consolidated technical conclusion

---

## Inputs

| Parameter | Type | Required | Description |
|---|---|---|---|
| `repo_path` | string | **yes** | Local path or URL of the repository to analyze |
| `repo_name` | string | **yes** | Name of the repository |
| `user_query` | string | **yes** | Specific question or topic to investigate within the repository |
| `mode` | string | no | Operation mode: `rag`, `deep_research`, or `simple_chat` (auto-detected if omitted) |
| `conversation_history` | object | no | Structured history of previous conversation to maintain continuity in multi-turn investigations |
| `contexts` | list | no | Relevant file fragments retrieved via semantic search |
| `research_iteration` | integer | no | Current iteration number in Deep Research mode |
| `language_name` | string | no | Language explicitly requested by the user for the response |

## Outputs

| Parameter | Type | Description |
|---|---|---|
| `response` | string | Structured Markdown response with technical analysis, iterative research, or final conclusion depending on the active mode |

---

## Operation Modes

This skill operates in three main modes, each with specific behavior:

| Mode | Purpose | Iterations | Focus Level |
|---|---|---|---|
| **RAG** | Contextual response based on files | 1 | High |
| **Deep Research** | Deep multi-turn investigation | Multiple | Very High |
| **Simple Chat** | Direct technical response | 1 | Specific |

---

### Mode 1: RAG (Contextual Analysis)

**Role:** You are a code assistant that answers user questions on a repository. You receive the user query, relevant context from files, and past conversation history.

**Purpose:** Answer specific questions using the user's query, context retrieved from files, and conversation history.

**Behavior:**
- Automatically detects the language of the query
- Responds in the same language
- If a specific language is requested, it takes priority over the query language
- Uses structured Markdown
- Organizes information with headings and lists
- Cites file paths using `inline code` formatting
- For code blocks, use triple backticks with language specification (` ```harbour `, ` ```c `, ` ```javascript `, etc.)
- Use `##` headings for major sections
- Use bullet points or numbered lists where appropriate
- Format tables using markdown table syntax when presenting structured data
- Use **bold** and *italic* for emphasis

**Context Processing:**
The RAG mode processes information in this order:
1. System prompt (role and formatting rules)
2. Conversation history (previous Q&A turns, if any)
3. Retrieved contexts (file fragments with file paths)
4. Current user prompt

**Strict Rules:**
- Do NOT include ` ```markdown ` fences at the beginning or end of the answer
- Start the response directly with the content
- Think step by step and ensure the answer is well-structured and visually organized
- The content will already be rendered as markdown, so just provide the raw markdown content
- Maintain clear visual organization

---

### Mode 2: Deep Research (Multi-Turn Investigation)

Designed for deep, strictly focused investigation across multiple iterations.

**Role:** You are an expert code analyst examining a repository. You are conducting a multi-turn Deep Research process to thoroughly investigate the specific topic in the user's query. Your goal is to provide detailed, focused information EXCLUSIVELY about this topic.

#### First Iteration

**Guidelines:**
- This is the first iteration of a multi-turn research process focused EXCLUSIVELY on the user's query
- Start the response with `## Research Plan`
- Outline the approach to investigating this specific topic
- If the topic is about a specific file or feature (like "Dockerfile"), focus ONLY on that file or feature
- Clearly state the specific topic being researched to maintain focus throughout all iterations
- Identify the key aspects that need to be researched
- Provide initial findings based on the information available
- End with `## Next Steps` indicating what will be investigated in the next iteration
- Do NOT provide a final conclusion yet — this is just the beginning of the research
- Do NOT include general repository information unless directly relevant to the query
- Remember that this topic will be maintained across all research iterations

**Restrictions:**
- Do NOT deviate from the specific topic
- Do NOT include irrelevant general information
- NEVER respond with just "Continue the research" as an answer — always provide substantive research findings
- Do NOT respond with empty messages
- Focus EXCLUSIVELY on the specific topic being researched — do not drift to related topics
- The research MUST directly address the original question

**Style:**
- Be concise but thorough
- Use markdown formatting to improve readability
- Cite specific files and code sections when relevant

#### Intermediate Iterations

**Guidelines:**
- CAREFULLY review the conversation history to understand what has been researched so far
- The response MUST build on previous research iterations — do NOT repeat information already covered
- Identify gaps or areas that need further exploration related to this specific topic
- Focus on one specific aspect that needs deeper investigation in this iteration
- Start the response with `## Research Update {iteration_number}`
- Clearly explain what is being investigated in this iteration
- Provide new insights that weren't covered in previous iterations
- Maintain continuity with previous research iterations — this is a continuous investigation
- Do NOT include general repository information unless directly relevant to the query
- If the topic is about a specific file or feature (like "Dockerfile"), focus ONLY on that file or feature

If it is the penultimate iteration (e.g., iteration 3 of 4), prepare a synthesis for closure in the next iteration.

**Restrictions:**
- Do NOT deviate from the main focus — focus EXCLUSIVELY on the specific topic
- NEVER respond with just "Continue the research" as an answer — always provide substantive research findings
- The research MUST directly address the original question

**Style:**
- Be concise but thorough
- Focus on providing new information, not repeating what's already been covered
- Use markdown formatting to improve readability
- Cite specific files and code sections when relevant

#### Final Iteration

**Guidelines:**
- This is the final iteration of the research process
- CAREFULLY review the entire conversation history to understand all previous findings
- Synthesize ALL findings from previous iterations into a comprehensive conclusion
- Start with `## Final Conclusion`
- The conclusion MUST directly address the original question
- Stay STRICTLY focused on the specific topic — do not drift to related topics
- Include specific code references and implementation details related to the topic
- Highlight the most important discoveries and insights about this specific functionality
- Provide a complete and definitive answer to the original question
- Ensure the conclusion builds on and references key findings from previous iterations
- If the topic is about a specific file or feature (like "Dockerfile"), focus ONLY on that file or feature
- May include actionable recommendations or insights when appropriate

**Forbidden:**
- Deviating to related topics
- Responding with "Continue the research" as an answer — always provide a complete conclusion
- Responding with open or incomplete phrases
- Including general repository information unless directly relevant to the query

**Style:**
- Be concise but thorough
- Use markdown formatting to improve readability
- Cite specific files and code sections when relevant
- Structure the response with clear headings
- End with actionable insights or recommendations when appropriate

---

### Mode 3: Simple Chat (Direct Response)

**Role:** You are an expert code analyst providing direct, concise, and accurate information about code repositories. You NEVER start responses with markdown headers or code fences.

Direct technical response mode.

**Characteristics:**
- Answer the user's question directly without ANY preamble or filler phrases
- Do NOT include any rationale, explanation, or extra comments before the answer
- Do NOT start with preambles like "Okay, here's a breakdown" or "Here's an explanation"
- Do NOT start with markdown headers like `## Analysis of...` or any file path references
- Do NOT start with ` ```markdown ` code fences
- Do NOT end the response with ` ``` ` closing fences
- Do NOT start by repeating or acknowledging the question
- JUST START with the direct answer to the question
- Start with the most relevant information that directly addresses the user's query

**Anti-pattern example (DO NOT do this):**
```## Analysis of `source/classes/xbrowse.prg`

This file contains...```
Instead, just start directly with:
```TXBrowse is a powerful data grid control that supports...```

**Style:**
- Format the response with proper markdown including headings, lists, and code blocks WITHIN the answer (not wrapping it)
- For code analysis, organize the response with clear sections
- Think step by step and structure the answer logically
- Use concise, direct language
- Prioritize accuracy over verbosity
- When showing code, include line numbers and file paths when relevant
- Use markdown formatting to improve readability
- Be precise and technical when discussing code
- The response language should match the user's query language

---

## How to Run the Analysis

### Phase 1: Initial Exploration

1. **Identify the project type**
   - Detect the main programming language
   - Identify the framework(s) used
   - Determine the application type (web, mobile, CLI, API, desktop, library, etc.)

2. **Map the directory structure**
   - List all top-level directories
   - Identify organizational patterns (DDD, MVC, Clean Architecture, layered, etc.)
   - Locate main configuration files
   - Measure directory depth and breadth

3. **Examine configuration files**
   - package.json, pyproject.toml, Cargo.toml, pom.xml, Makefile, .hbp, etc.
   - Build files: webpack.config.js, tsconfig.json, Makefile, .bat/.sh scripts
   - Container configuration: Dockerfile, docker-compose.yml
   - IDE/editor configuration: .editorconfig, .vscode/, .agent/

### Phase 2: Technology Analysis

1. **Main technology stack**
   - Languages and versions used
   - Backend and frontend frameworks
   - Databases and caching systems
   - Message queues and external services
   - AI/ML integrations

2. **Critical dependencies**
   - Main libraries and their purpose
   - Dependencies with known vulnerabilities
   - Outdated or unmaintained packages
   - Internal vs external dependency ratio

3. **Development tools**
   - Linters and formatters used
   - Testing systems
   - CI/CD tools
   - Task runners and bundlers
   - Build system complexity

### Phase 3: Architecture Analysis

1. **Architectural patterns**
   - Identify whether it uses MVC, MVP, MVVM, Clean Architecture, Hexagonal, etc.
   - Detect design patterns used (Factory, Observer, Strategy, Composite, Bridge, etc.)
   - Identify specific architectures (microservices, serverless, monolith)
   - Map class inheritance hierarchies
   - **Generate a class hierarchy diagram** using `[quote][mermaid]...[/mermaid][/quote]` syntax
   - **Generate an architecture layers diagram** showing the layered structure

2. **Component structure**
   - Main modules and their responsibilities
   - Dependencies between components
   - Application entry and exit points
   - Communication patterns between components
   - Coupling and cohesion assessment
   - **Generate a component dependency diagram** showing inter-module relationships

3. **Data flow**
   - How information flows through the system
   - APIs and contracts between modules
   - Integrations with external services
   - Event/callback patterns
   - **Generate a data flow diagram** showing how data moves through the system

### Phase 4: Code Analysis

1. **Overall quality**
   - Readability and maintainability
   - Cyclomatic complexity
   - Code duplication
   - Function and module length
   - Naming conventions consistency

2. **Good patterns identified**
   - SOLID principles applied
   - Dependency injection
   - Consistent error handling
   - Logging and monitoring
   - Data validation
   - Documentation coverage

3. **Areas for improvement**
   - Code smells detected
   - Frequent anti-patterns
   - Lack of documentation in critical functions
   - Insufficient testing coverage
   - Monolithic files needing refactoring
   - Hardcoded values or paths

### Phase 5: Testing and Quality

1. **Testing strategy**
   - Types of tests implemented (unit, integration, e2e)
   - Testing frameworks used
   - Current code coverage
   - Testing patterns employed
   - Sample/example coverage as implicit testing

2. **CI/CD**
   - Continuous integration pipeline
   - Deployment stages
   - Branching strategies
   - Release workflow
   - Build automation level

### Phase 6: Report Generation

1. **Report structure**
   - Executive summary
   - System architecture (with Mermaid diagrams using `[quote][mermaid]...[/mermaid][/quote]` syntax)
   - Complete technology stack (with Mermaid mindmap or pie chart)
   - Component breakdown by category
   - Quantitative metrics table
   - Code quality analysis with scoring
   - Design patterns identified (with Mermaid class diagrams)
   - Notable innovations
   - Findings and recommendations (prioritized)
   - Build pipeline diagram
   - Event/callback flow diagrams

2. **Output format**
   - Structured Markdown
   - Clear and navigable sections
   - Code examples when relevant
   - Actionable recommendations
   - **ALL Mermaid diagrams MUST use `[quote][mermaid]...[/mermaid][/quote]` syntax** (never use ` ```mermaid ` fences)
   - Generate as many Mermaid diagrams as possible to visually illustrate the analysis
   - Tables for metrics and comparisons

---

## Decision Tree

The following decision tree should be used to determine the analysis mode and approach. When generating this in a report, use the Mermaid syntax:

[quote][mermaid]
flowchart TD
    A["User Query"] --> B{"Query Type?"}
    B -->|"Specific file/function"| C["RAG Mode"]
    B -->|"Broad investigation"| D["Deep Research Mode"]
    B -->|"Quick question"| E["Simple Chat Mode"]
    
D --> F{"Multiple services?"} F -->|"Yes"| G["Identify inter-service communication"] F -->|"No"| H["Analyze as monolith"] D --> I{"Existing documentation?"} I -->|"Yes"| J["Compare with implementation"] I -->|"No"| K["Generate from code"] D --> L{"Has tests?"} L -->|"Yes"| M["Analyze coverage and quality"] L -->|"No"| N["Flag as critical improvement area"] D --> O{"Multi-language?"} O -->|"Yes"| P["Analyze each layer, then map interactions"] O -->|"No"| Q["Focus on single-language patterns"] [/mermaid][/quote] --- ## Output Format — DeepWiki Page Style The analysis MUST generate output structured as **wiki-style pages** that resemble the DeepWiki interface. The output is a single markdown document, but it is organized as multiple logical "pages" separated by `---` dividers. Each page follows the conventions below. **CRITICAL: All Mermaid diagrams MUST use `[quote][mermaid]...[/mermaid][/quote]` syntax. NEVER use ` ```mermaid ``` ` fences.** ### Page Structure Conventions Every logical page/section follows this structure: 1. **Page Title** — An `#` or `##` heading acting as the page name 2. **Relevant source files** — A blockquote listing the key source files related to this page, each with file path and optional line range (e.g., `include/fivewin.ch#8-9`). Format: `> 📄 path/to/file.ext` or `> 📄 path/to/file.ext#L10-25` 3. **Introduction paragraph** — One or two sentences summarizing the page, with **cross-references** to other sections written as bold links (e.g., "For detailed class internals see **Core Architecture**. For build scripts see **Build and Platform Support**.") 4. **Subsections** (`###`) — Each with descriptive **prose-style text** (not just bullet lists). Write flowing, well-structured paragraphs that explain concepts, followed by code examples, tables, or diagrams as needed 5. **Source citations inline** — Reference specific source files with line numbers inline using backtick formatting: `` `source/classes/window.prg#L45-60` `` 6. **Code snippets** — Show relevant code fragments using fenced code blocks with language tags 7. **Tables** — Use markdown tables for structured data (compiler targets, component lists, metrics, etc.) 8. **Mermaid diagrams** — Using `[quote][mermaid]...[/mermaid][/quote]` syntax wherever a visual aid helps understanding ### Sidebar Navigation Structure At the very beginning of the document, include a **navigation index** representing the wiki's sidebar. Use a nested list mirroring the structure shown below. Adapt the items to the actual project being analyzed: ```markdown## 📑 Navigation - **Overview** - **Getting Started** - Installation - Building Applications - Hello World Tutorial - Sample Applications - **Core Architecture** - Window System (TWindow) - Dialog System - Control System (TControl) - Event Handling - Data Binding Pattern - MDI Framework - **Data Access Layer** - Data Access Architecture - Database Connector Summary - **UI Controls** - TXBrowse — Advanced Data Grid - TGet — Input Fields - [other major controls] - **AI and Modern Features** - **Build and Platform Support** - **Settings**``` ### Wiki Page Template Below is the template for each page. Replace bracketed items with actual content: --- ```markdown# [Page Title] > 📄 Relevant source files > > `[file_path_1]#L[start]-[end]` — [brief description] > `[file_path_2]` — [brief description] > `[file_path_3]#L[start]-[end]` — [brief description] [Introduction paragraph in flowing prose. Cross-reference other pages: "For installation steps see **Installation**. For detailed class internals see **Core Architecture**. For build scripts and compiler targets see **Build and Platform Support**."] ## [First Subsection Title] [Descriptive, flowing prose explaining this aspect of the project. Not just bullet points — write real paragraphs that read naturally, as a wiki article would.] [Optional: framework version defined in `include/fivewin.ch#L8-9`:] #define FWVERSION "FWH 25.12" #define FW_VersionNo 25120 [Continuation of the explanation, referencing source code inline like `source/classes/window.prg#L45` when citing specific implementations.] | Column 1 | Column 2 | Column 3 | |---|---|---| | Data | Data | Data | ## [Second Subsection Title] [More prose-style content explaining the next concept...] [INSERT MERMAID diagram using [quote][mermaid]...[/mermaid][/quote] syntax] ## [Third Subsection Title] [Continue with additional subsections as needed...]``` --- ### Mandatory Pages to Generate The following pages MUST be generated for any project analysis. Adapt titles and content to match the project: | Page | Content | Key Diagrams | |---|---|---| | **Overview** | Project introduction, what it is, version, purpose, subsystem map | Subsystem map (flowchart), tech stack (pie) | | **Getting Started** | Installation, building, hello world, sample apps | Build pipeline (flowchart) | | **Core Architecture** | Main class hierarchy, design patterns, layers | Class hierarchy (classDiagram), layers (graph TD) | | **Window/UI System** | Window classes, control hierarchy, event handling | Class diagram, event sequence diagram | | **Data Access Layer** | Database connectivity, supported backends, ORMs | ER diagram, component dependency | | **UI Controls** | Major controls (grids, inputs, menus, etc.) breakdown | Component relationship diagram | | **AI and Modern Features** | AI integrations, web tech, modern additions | Dependency diagram | | **Build and Platform Support** | Compilers, targets, makefiles, platform matrix | Build pipeline (flowchart) | ### Style Guidelines for Prose - **Write like a wiki article**, NOT like a technical report with bullet lists - Use flowing paragraphs that explain concepts naturally - Start each page with a summary paragraph that gives context - Use cross-references to other pages: "For more details see **Core Architecture**" - Cite source files inline: "The framework version is defined in `include/fivewin.ch#L8-9`" - Show code snippets indented or in fenced blocks when illustrating specific definitions - Use tables for structured comparisons (compiler matrix, component lists, etc.) - Every page should have a **"Relevant source files"** blockquote at the top - Keep an academic/encyclopedic tone — informative, neutral, precise --- ## Language Handling The skill: - Detects the language of the user's query automatically - Responds in the SAME language as the user's query - **IMPORTANT:** If a specific language is requested in the prompt, that language takes priority over the detected query language - Maintains linguistic consistency across ALL iterations in Deep Research mode - Never switches language mid-iteration - Code comments and technical terms may remain in the original language of the codebase --- ## Formatting Rules All responses must: - Use structured Markdown with proper syntax for all formatting - For code blocks, use triple backticks with language specification (` ```harbour `, ` ```c `, ` ```javascript `, etc.) - Use `##` headings for major sections - Use bullet points or numbered lists where appropriate - Format tables using markdown table syntax when presenting structured data - Use **bold** and *italic* for emphasis - Reference file paths as `inline code` - Maintain visual clarity - Include emoji indicators for priority levels (🔴🟡🟢) ### Mermaid Diagram Syntax (MANDATORY) **ALL Mermaid diagrams MUST use this custom syntax:** ```[quote][mermaid] ...mermaid code here (raw, WITHOUT ```mermaid fences)... [/mermaid][/quote]``` **Rules:** - **NEVER** use ` ```mermaid ``` ` fences for diagrams - **ALWAYS** wrap Mermaid code inside `[quote][mermaid]...[/mermaid][/quote]` - The Mermaid code goes directly between the tags, with NO additional code fences - Generate **as many Mermaid diagrams as possible** to visually illustrate the analysis - Every architecture section, class hierarchy, data flow, build pipeline, event system, and component relationship SHOULD have an accompanying Mermaid diagram **Correct example:** ```[quote][mermaid] classDiagram class TWindow { +hWnd +Paint() +End() } TWindow <|-- TDialog TWindow <|-- TControl [/mermaid][/quote]``` **INCORRECT example (DO NOT do this):** ~~~```mermaid classDiagram class TWindow { ... } ```~~~ **Critical formatting constraints:** 1. Do NOT include ` ```markdown ` fences at the beginning or end of the answer 2. Start the response directly with the content 3. The content will already be rendered as markdown, so just provide the raw markdown content 4. Think step by step and ensure the answer is well-structured and visually organized --- ## Focus Enforcement The skill guarantees: - Exclusive focus on the queried topic - Continuity in multi-turn investigations - Technical coherence between iterations - Avoidance of topic drift - Responses directly aligned with the original question - If the topic is about a specific file or feature, ONLY that file or feature is analyzed - General repository information is excluded unless directly relevant to the query - NEVER responds with just filler phrases like "Continue the research" — always provides substantive findings - Cross-references previous iteration findings to build a coherent narrative --- ## Mermaid Diagram Guidelines The analysis MUST generate as many Mermaid diagrams as possible. Below are the **mandatory diagram types** to include when applicable. All diagrams use `[quote][mermaid]...[/mermaid][/quote]` syntax. ### 1. Class Hierarchy Diagram Use `classDiagram` to show inheritance and composition between classes: [quote][mermaid] classDiagram class BaseClass { +dataMembers +Method1() +Method2() } class ChildA { +SpecificData +OverriddenMethod() } class ChildB { +OtherData +AnotherMethod() } BaseClass <|-- ChildA BaseClass <|-- ChildB BaseClass *-- HelperClass [/mermaid][/quote] ### 2. Architecture Layers Diagram Use `graph TD` (top-down) to show layered architectures: [quote][mermaid] graph TD A["Application Layer"] --> B["Framework / DSL Layer"] B --> C["OOP Classes Layer"] C --> D["Utility Functions"] D --> E["API Wrappers / Bindings"] E --> F["Operating System / Runtime"] [/mermaid][/quote] ### 3. Data Flow Diagram Use `flowchart LR` (left-right) to show how data moves through the system: [quote][mermaid] flowchart LR A["User Input"] --> B["Validation"] B --> C["Business Logic"] C --> D["Data Access Layer"] D --> E[("Database")] C --> F["Rendering"] F --> G["Screen Output"] [/mermaid][/quote] ### 4. Build Pipeline Diagram Use `flowchart LR` to illustrate the build process and toolchain: [quote][mermaid] flowchart LR A[".prg Source"] --> B["Harbour Compiler"] B --> C[".c Generated"] C --> D["C/C++ Compiler"] D --> E[".obj Files"] F[".c Source"] --> D G[".cpp Source"] --> D E --> H["Librarian / Linker"] H --> I[".lib / .exe"] [/mermaid][/quote] ### 5. Component Dependency Diagram Use `graph LR` to show dependencies between modules: [quote][mermaid] graph LR UI["UI Controls"] --> Core["Core Framework"] DB["Database Layer"] --> Core Net["Networking"] --> Core AI["AI Integration"] --> Net AI --> Core Reports["Reporting"] --> UI Reports --> DB Web["WebView"] --> UI Web --> Net [/mermaid][/quote] ### 6. Event / Callback Flow Diagram Use `sequenceDiagram` to show event handling and callback patterns: [quote][mermaid] sequenceDiagram participant User participant Window participant Control participant EventHandler
User->>Window: Click/KeyPress Window->>Control: WndProc dispatch Control->>EventHandler: Evaluate bAction/bWhen EventHandler-->>Control: Result Control-->>Window: Refresh/Update Window-->>User: Visual feedback [/mermaid][/quote] ### 7. Design Patterns Diagram Use `classDiagram` to illustrate identified design patterns: [quote][mermaid] classDiagram class Subject { +Attach(observer) +Notify() } class Observer { +Update() } class ConcreteObserver { +Update() } Subject --> Observer : notifies Observer <|-- ConcreteObserver [/mermaid][/quote] ### 8. Technology Stack Diagram Use `pie` or `mindmap` to show technology distribution: [quote][mermaid] pie title Code Distribution by Language "Harbour/xBase" : 460 "C" : 200 "C++" : 40 "Headers" : 102 [/mermaid][/quote] ### 9. State Diagram Use `stateDiagram-v2` to model lifecycle states of key objects: [quote][mermaid] stateDiagram-v2 [*] --> Created : New() Created --> Active : Activate() Active --> Updated : Refresh() Updated --> Active Active --> Destroyed : End() Destroyed --> [*] [/mermaid][/quote] ### 10. ER Diagram (Data Model) Use `erDiagram` when the project has database entities: [quote][mermaid] erDiagram CUSTOMER ||--o{ ORDER : places ORDER ||--|{ LINE_ITEM : contains PRODUCT ||--o{ LINE_ITEM : "ordered in" [/mermaid][/quote] ### When to Include Each Diagram | Diagram Type | When to Include | |---|---| | Class Hierarchy | Always (if the project has classes) | | Architecture Layers | Always (for any multi-layered project) | | Data Flow | When data processing pipelines exist | | Build Pipeline | When the build system is non-trivial | | Component Dependencies | When there are 3+ distinct modules | | Event/Callback Flow | When event-driven patterns are used | | Design Patterns | When recognizable patterns are found | | Technology Stack | Always (pie chart of code distribution) | | State Diagram | When objects have clear lifecycle states | | ER Diagram | When database entities are present | --- ## Usage Examples ### Full analysis of an unknown project ```Analyze the repository at /workspace/my-project as DeepWiki would``` ### Focus on a specific aspect ```Perform an architecture analysis of the project focusing on design patterns``` ### Comparison with best practices ```Evaluate the code quality comparing with clean code principles``` ### Deep research on a specific module ```Investigate the database connectivity layer in depth using Deep Research mode``` ### Quick question about a file ```What does the TXBrowse class do and what are its main methods?``` --- ## Metrics to Collect - Number of files per language - Total lines of code - Maximum directory depth - Number of direct dependencies - Test coverage (if applicable) - Average cyclomatic complexity - Average number of functions/classes per file - Largest files by line count - Class inheritance depth - Number of samples/examples --- ## Prompt Template Reference For integration with embedding/RAG pipelines, the context processing follows this template structure: ```<START_OF_SYS_PROMPT> {system_prompt} {output_format_str} <END_OF_SYS_PROMPT> {# If conversation history exists #} <START_OF_CONVERSATION_HISTORY> {for each dialog_turn in conversation_history} {turn_number}. User: {user_query} You: {assistant_response} {end for} <END_OF_CONVERSATION_HISTORY> {# If file contexts are provided #} <START_OF_CONTEXT> {for each context in contexts} {index}. File Path: {context.file_path} Content: {context.text} {end for} <END_OF_CONTEXT> <START_OF_USER_PROMPT> {user_input} <END_OF_USER_PROMPT>``` **Deep Research iterations** use role/guidelines/style blocks: ```<role> Expert analyst identity, repository info, language constraint, iteration context </role> <guidelines> Iteration-specific behavioral rules (first / intermediate / final) </guidelines> <style> Output formatting preferences (concise, markdown, citations) </style>``` This structure ensures consistent behavior whether the skill is invoked as a standalone agent, integrated with a semantic search engine, or orchestrated through a multi-turn pipeline. --- ## Available Helper Scripts The skill includes optional Harbour scripts that can be used during the analysis: - **analyze-structure.prg**: Analyzes the directory structure and generates a tree with file counts and sizes - **detect-tech-stack.prg**: Detects technologies based on file extensions and configuration files - **calculate-metrics.prg**: Calculates code metrics (lines per language, file counts, directory depth) ### analyze-structure.prg ```harbour/* * Directory Structure Analyzer * Usage: analyze-structure <path> [max_depth] * Generates a visual tree of the directory structure */ #include "directry.ch" FUNCTION Main( cPath, cMaxDepth ) LOCAL nMaxDepth := 3 DEFAULT cPath := "." DEFAULT cMaxDepth := "3" nMaxDepth := Val( cMaxDepth ) ? "Directory Structure Analysis" ? Replicate( "=", 40 ) ? "" AnalyzeDir( cPath, 0, nMaxDepth ) RETURN NIL STATIC FUNCTION AnalyzeDir( cPath, nLevel, nMaxDepth ) LOCAL aFiles, aFile LOCAL nFiles := 0, nDirs := 0 LOCAL cIndent := Replicate( " ", nLevel ) IF nLevel > nMaxDepth RETURN NIL ENDIF aFiles := Directory( cPath + "\*.*", "D" ) FOR EACH aFile IN aFiles IF aFile[ F_NAME ] == "." .OR. aFile[ F_NAME ] == ".." LOOP ENDIF IF "D" $ aFile[ F_ATTR ] nDirs++ ? cIndent + "[DIR] " + aFile[ F_NAME ] AnalyzeDir( cPath + "\" + aFile[ F_NAME ], nLevel + 1, nMaxDepth ) ELSE nFiles++ ENDIF NEXT ? cIndent + " (" + LTrim( Str( nFiles ) ) + " files, " + ; LTrim( Str( nDirs ) ) + " subdirs)" RETURN NIL``` ### detect-tech-stack.prg ```harbour/* * Technology Stack Detector * Usage: detect-tech-stack <path> * Detects programming languages and frameworks from file extensions * and configuration files */ FUNCTION Main( cPath ) LOCAL aExtensions := {} LOCAL aTechFiles := { ; { "package.json", "Node.js / JavaScript" }, ; { "pyproject.toml", "Python" }, ; { "Cargo.toml", "Rust" }, ; { "pom.xml", "Java (Maven)" }, ; { "build.gradle", "Java (Gradle)" }, ; { "Makefile", "Make build system" }, ; { "Dockerfile", "Docker" }, ; { "docker-compose.yml", "Docker Compose" }, ; { ".hbp", "Harbour" }, ; { "fivewin.ch", "FiveWin for Harbour" }, ; { "tsconfig.json", "TypeScript" }, ; { "webpack.config.js","Webpack" }, ; { "go.mod", "Go" }, ; { "CMakeLists.txt", "CMake" }, ; { ".csproj", "C# / .NET" } ; } DEFAULT cPath := "." ? "Technology Stack Detection" ? Replicate( "=", 40 ) ? "" // Detect by config files ? "## Detected Technologies" DetectByConfigFiles( cPath, aTechFiles ) ? "" ? "## Languages by Extension" CountByExtension( cPath, aExtensions ) RETURN NIL STATIC FUNCTION DetectByConfigFiles( cPath, aTechFiles ) LOCAL aItem FOR EACH aItem IN aTechFiles IF File( cPath + "\" + aItem[ 1 ] ) .OR. ; File( cPath + "\include\" + aItem[ 1 ] ) ? " [✓] " + aItem[ 2 ] + " (" + aItem[ 1 ] + ")" ENDIF NEXT RETURN NIL STATIC FUNCTION CountByExtension( cPath, aExtensions ) LOCAL aLangs := { ; { ".prg", "Harbour/xBase", 0 }, ; { ".c", "C", 0 }, ; { ".cpp", "C++", 0 }, ; { ".h", "C/C++ Header", 0 }, ; { ".ch", "Clipper Header", 0 }, ; { ".js", "JavaScript", 0 }, ; { ".ts", "TypeScript", 0 }, ; { ".py", "Python", 0 }, ; { ".rb", "Ruby", 0 }, ; { ".go", "Go", 0 }, ; { ".rs", "Rust", 0 }, ; { ".java","Java", 0 }, ; { ".cs", "C#", 0 }, ; { ".bat", "Batch script", 0 }, ; { ".sh", "Shell script", 0 }, ; { ".md", "Markdown", 0 }, ; { ".html","HTML", 0 }, ; { ".css", "CSS", 0 } ; } LOCAL aItem CountFilesRecursive( cPath, aLangs ) FOR EACH aItem IN aLangs IF aItem[ 3 ] > 0 ? " " + PadR( aItem[ 2 ], 20 ) + LTrim( Str( aItem[ 3 ] ) ) + " files" ENDIF NEXT RETURN NIL STATIC FUNCTION CountFilesRecursive( cPath, aLangs ) LOCAL aFiles, aFile, aItem, cExt aFiles := Directory( cPath + "\*.*", "D" ) FOR EACH aFile IN aFiles IF aFile[ F_NAME ] == "." .OR. aFile[ F_NAME ] == ".." LOOP ENDIF IF "D" $ aFile[ F_ATTR ] IF aFile[ F_NAME ] != ".git" CountFilesRecursive( cPath + "\" + aFile[ F_NAME ], aLangs ) ENDIF ELSE cExt := Lower( SubStr( aFile[ F_NAME ], RAt( ".", aFile[ F_NAME ] ) ) ) FOR EACH aItem IN aLangs IF cExt == aItem[ 1 ] aItem[ 3 ]++ EXIT ENDIF NEXT ENDIF NEXT RETURN NIL``` ### calculate-metrics.prg ```harbour/* * Code Metrics Calculator * Usage: calculate-metrics <path> * Calculates lines of code, file counts, and complexity estimates */ #include "directry.ch" STATIC nTotalLines := 0 STATIC nTotalFiles := 0 STATIC nMaxDepth := 0 STATIC nLargestFile := 0 STATIC cLargestName := "" FUNCTION Main( cPath ) LOCAL aCodeExts := { ".prg", ".c", ".cpp", ".h", ".ch", ".js", ".ts", ; ".py", ".go", ".rs", ".java", ".cs" } DEFAULT cPath := "." ? "Code Metrics Report" ? Replicate( "=", 40 ) ? "" ProcessDir( cPath, aCodeExts, 0 ) ? "" ? "## Summary" ? " Total source files: " + LTrim( Str( nTotalFiles ) ) ? " Total lines of code: " + LTrim( Str( nTotalLines ) ) ? " Max directory depth: " + LTrim( Str( nMaxDepth ) ) ? " Largest file: " + cLargestName + ; " (" + LTrim( Str( nLargestFile ) ) + " lines)" IF nTotalFiles > 0 ? " Avg lines per file: " + LTrim( Str( Int( nTotalLines / nTotalFiles ) ) ) ENDIF RETURN NIL STATIC FUNCTION ProcessDir( cPath, aCodeExts, nDepth ) LOCAL aFiles, aFile, cExt, nLines IF nDepth > nMaxDepth nMaxDepth := nDepth ENDIF aFiles := Directory( cPath + "\*.*", "D" ) FOR EACH aFile IN aFiles IF aFile[ F_NAME ] == "." .OR. aFile[ F_NAME ] == ".." LOOP ENDIF IF "D" $ aFile[ F_ATTR ] IF aFile[ F_NAME ] != ".git" .AND. aFile[ F_NAME ] != "node_modules" ProcessDir( cPath + "\" + aFile[ F_NAME ], aCodeExts, nDepth + 1 ) ENDIF ELSE cExt := Lower( SubStr( aFile[ F_NAME ], RAt( ".", aFile[ F_NAME ] ) ) ) IF AScan( aCodeExts, cExt ) > 0 nTotalFiles++ nLines := CountLines( cPath + "\" + aFile[ F_NAME ] ) nTotalLines += nLines IF nLines > nLargestFile nLargestFile := nLines cLargestName := cPath + "\" + aFile[ F_NAME ] ENDIF ENDIF ENDIF NEXT RETURN NIL STATIC FUNCTION CountLines( cFile ) LOCAL nHandle, cLine, nCount := 0 nHandle := FOpen( cFile ) IF nHandle >= 0 DO WHILE ! HB_FEof( nHandle ) cLine := HB_FReadLine( nHandle ) nCount++ ENDDO FClose( nHandle ) ENDIF RETURN nCount``` Run any of these scripts with Harbour: `hbrun analyze-structure.prg <path>`

Re: Antigravity as bugs solver and tech support

Posted: Sun Mar 01, 2026 11:00 am
by Antonio Linares

FiveTechSoft/fwh

  • Overview
  • Getting Started
    • Installation
    • Building Applications
    • Hello World Tutorial
    • Sample Applications
  • Core Architecture
    • Window System (TWindow)
    • Dialog System
    • Control System (TControl)
    • Event Handling
    • Data Binding Pattern
    • MDI Framework
  • Data Access Layer
    • Data Access Architecture
    • Database Connector Summary
  • UI Controls
    • TXBrowse — Advanced Data Grid
    • TGet — Input Fields
    • TRichEdit5 — Rich Text Editor
    • TScintilla — Code Editor
    • TRibbon — Office-Style Ribbon
    • TMenu — Menu System
  • AI and Modern Features
  • Build and Platform Support

Overview

📄 Relevant source files

include/fivewin.ch#L1-25 — Main framework header, version and description macros
[fwh.mak](file:///c:/fwteam/fwh.mak) — Primary build makefile
[whatsnew.txt](file:///c:/fwteam/whatsnew.txt) — 25,865 lines of changelog spanning 30+ years

This page introduces the FiveWin for Harbour (FWH) repository: its purpose, platform targets, directory layout, and the eight major subsystems. For installation steps see Getting Started. For detailed class internals see Core Architecture. For build scripts and compiler targets see Build and Platform Support.

What is FWH?

FWH is a Windows desktop GUI application framework built on top of the Harbour and xHarbour compilers. It wraps the Win32 API in a class-based object model, letting application code written entirely in Harbour (a dBASE/Clipper-compatible language) create windows, dialogs, controls, menus, database grids, printed reports, and — in recent versions — embedded web browsers and AI service integrations.

The framework version is defined in include/fivewin.ch#L9-10:

Code: Select all | Expand

#define FWVERSION    "FWH 25.12"
#define FW_VersionNo 25120

The FWDESCRIPTION macro resolves to one of four strings depending on compiler and bitness (include/fivewin.ch#L12-24):

CompilerBitnessDescription
Harbour32-bit"FiveWin for Harbour"
Harbour64-bit"FiveWin for Harbour 64"
xHarbour32-bit"FiveWin for xHarbour"
xHarbour64-bit"FiveWin for xHarbour 64"

Repository Layout

The repository is organized into clearly separated directories for source code, headers, samples, resources, and build artifacts:

Code: Select all | Expand

c:\fwteam\
├── source/                    ~693 source files
│   ├── classes/               256 Harbour classes (.prg)
│   ├── ceclasses/             50 Windows CE classes
│   ├── function/              147 utility functions (C + Harbour)
│   ├── winapi/                162 Win32 API wrappers (C + Harbour)
│   └── internal/              78+ internal components (C/C++)
├── include/                   102 header files (.ch, .h)
├── samples/                   ~3,487 example files in 56 directories
├── lib/                       70 compiled libraries
├── bitmaps/                   1,121 graphic resources
├── icons/                     403 icons
├── cursors/                   62 cursors
├── docs/                      70 documentation files
├── makes/                     16 alternative makefiles
└── *.mak                      9 makefile variants

Subsystem Map

graph LR subgraph "FWH Framework" Core["Core Architecture<br/>TWindow · TControl · TDialog"] UI["UI Controls<br/>TXBrowse · TGet · TMenu · TRibbon"] DB["Data Access<br/>DBF · MySQL · ODBC · ADO"] Net["Networking<br/>TSocket · TWebServer · TWebView2"] AI["AI Integration<br/>TChatGPT · TOllama · TGemini"] Build["Build System<br/>BCC · MSVC · LLVM"] CE["Windows CE<br/>50 mobile classes"] Print["Reporting<br/>TEReport · FWPDF"] end Core --> UI Core --> DB Core --> Net Core --> AI Net --> AI UI --> Print DB --> Print Core --> CE

Core Class Hierarchy

The entire GUI framework revolves around a single root class TWindow, from which TControl and TDialog inherit. All 256+ visual controls descend from TControl.

classDiagram class TWindow { +hWnd +aControls[] +oMenu, oBar, oMsgBar +New() +Activate() +HandleEvent() +Paint() +End() } class TDialog { +cResName +lModal +Activate() +End() } class TControl { +bSetGet +bChange +nId +VarGet() +VarPut() +Refresh() } class TXBrowse { +aCols[] +cAlias +SetRDD() +SetArray() +ToExcel() } class TGet { +Picture +VarGet() +VarPut() } class TButton class TComboBox class TRichEdit5 class TScintilla TWindow <|-- TDialog TWindow <|-- TControl TWindow <|-- TMdiFrame TControl <|-- TXBrowse TControl <|-- TGet TControl <|-- TButton TControl <|-- TComboBox TControl <|-- TCheckBox TControl <|-- TRichEdit5 TControl <|-- TScintilla TControl <|-- TRibbon TControl <|-- TPanel TWindow *-- TMenu TWindow *-- TBar TWindow *-- TMsgBar

Technology Stack

pie title Code Distribution by File Type "Harbour (.prg)" : 460 "C (.c)" : 200 "C++ (.cpp)" : 40 "Headers (.ch/.h)" : 102 "Samples" : 3487
ComponentTechnologyNotes
Primary LanguageHarbour / xBaseCompatible with Harbour and xHarbour
Secondary LanguageC / C++Win32 API bindings, GDI+ rendering
OS APIWin32 APIWindows 7/8/10/11, 32 and 64-bit
GraphicsGDI / GDI+[source/winapi/gdipfwh.cpp](file:///c:/fwteam/source/winapi/gdipfwh.cpp)
CompilersBCC32, MSVC, LLVM-ClangMulti-compiler support
DatabaseDBF, MySQL, PostgreSQL, ODBC, ADOMultiple backends
WebWebView2, WebSockets, HTTPChromium embedded
AIOpenAI, Ollama, Gemini, DeepSeek, Kimicurl-based API clients
PDFharuPDF, FWPDFNative generation

AI and Modern Features

FWH integrates native classes for communicating with AI services direct from Harbour code. All classes use hbcurl for HTTP communication.

ClassFileModel DefaultDescription
TChatGPT[source/classes/chatgpt.prg](file:///c:/fwteam/source/classes/chatgpt.prg)gpt-4o-miniOpenAI Chat API
TOllama[source/classes/tollama.prg](file:///c:/fwteam/source/classes/tollama.prg)deepseek-r1:14bLocal LLMs via Ollama with streaming and image support
TAgentsource/classes/tollama.prg#L191—Agent framework with tool categories
TOpenAI[source/classes/topenai.prg](file:///c:/fwteam/source/classes/topenai.prg)—OpenAI with Vision
TGemini[source/classes/tgemini.prg](file:///c:/fwteam/source/classes/tgemini.prg)—Google Gemini AI
TDeepSeek[source/classes/tdeepseek.prg](file:///c:/fwteam/source/classes/tdeepseek.prg)—DeepSeek AI
TKimi[source/classes/tkimi.prg](file:///c:/fwteam/source/classes/tkimi.prg)—Moonshot Kimi AI
Transformer[source/classes/transformer.prg](file:///c:/fwteam/source/classes/transformer.prg)—Native Transformer architecture in Harbour+C
TNeuralNet[source/classes/tneuralnet.prg](file:///c:/fwteam/source/classes/tneuralnet.prg)—Neural network with C matrix ops

For example, the TChatGPT class at source/classes/chatgpt.prg#L10-29 is minimal — 5 DATA members and 5 methods — and sends prompts via curl_easy_perform. TOllama at source/classes/tollama.prg#L8-26 adds streaming (SendStream) and image (SendImage) capabilities with a default model of deepseek-r1:14b.

Build and Platform Support

The build system uses makefiles processed by NMake. The primary makefile [fwh.mak](file:///c:/fwteam/fwh.mak) defines compilation paths for Harbour, BCC32, and MSVC compilers. Multiple makefile variants exist for different targets:

MakefileTarget
[fwh.mak](file:///c:/fwteam/fwh.mak)Harbour + BCC32 (32-bit)
[fw64.mak](file:///c:/fwteam/fw64.mak)Harbour + MSVC (64-bit)
[fwhx.mak](file:///c:/fwteam/fwhx.mak)xHarbour + BCC32
fw64x.makxHarbour + MSVC (64-bit)
fwhclang.makHarbour + LLVM-Clang
flowchart LR A[".prg Source"] --> B["Harbour Compiler"] B --> C[".c Generated"] C --> D["C/C++ Compiler<br/>(BCC32 / MSVC / Clang)"] D --> E[".obj Files"] F[".c Source<br/>(winapi/, function/)"] --> D G[".cpp Source<br/>(internal/)"] --> D E --> H["TLIB / LIB Librarian"] H --> I["FiveH.lib + FiveHC.lib<br/>xfw.lib"]

Core Architecture

📄 Relevant source files

source/classes/window.prg#L197-800 — TWindow class definition (4,470 lines, 100+ methods)
source/classes/control.prg#L60-273 — TControl class definition (inherits TWindow)
source/classes/dialog.prg#L48-158 — TDialog class definition (inherits TWindow)
include/fivewin.ch#L1-2433 — Command preprocessor DSL (108 KB)

This page describes the foundational architecture of FWH: the TWindow class hierarchy, the preprocessor-based command DSL, the event handling model, and the data binding pattern. For specific controls see UI Controls. For data access see Data Access Layer.

Architecture Layers

FWH follows a layered architecture where user application code passes through a preprocessor DSL layer before reaching the OOP class layer, which in turn invokes C-level Win32 API wrappers.

graph TD A["Application Layer<br/>User .prg files"] --> B["Preprocessor DSL<br/>fivewin.ch — #xcommand / #xtranslate"] B --> C["OOP Classes Layer<br/>source/classes/*.prg (256 classes)"] C --> D["Utility Functions<br/>source/function/*.prg + *.c"] D --> E["Win32 API Wrappers<br/>source/winapi/*.c"] E --> F["Windows OS<br/>Win32 API / GDI / GDI+"] C --> G["Internal Components<br/>source/internal/*.c + *.cpp"] G --> F

Window System (TWindow)

TWindow is the root class of the entire GUI hierarchy, defined at source/classes/window.prg#L197. It encapsulates a Windows hWnd handle and provides over 100 methods for window creation, event handling, painting, coordinate management, and child control management.

Key DATA members include:

  • hWnd — the native window handle
  • aControls — array of child control objects (Composite pattern)
  • oMenu, oBar, oMsgBar — optional menu, toolbar, and status bar
  • nClrPane, nClrText — foreground/background colors
  • bLClicked, bPainted, bKeyDown — event callback code blocks

Event dispatching routes through HandleEvent() at window.prg#L490-491, which calls the external C function WndHandleEvent(). All event callbacks use Harbour code blocks (bAction, bWhen, bValid), implementing the Observer/Strategy pattern.

Dialog System

TDialog inherits from TWindow and adds modal/non-modal dialog behavior. Defined at source/classes/dialog.prg#L48, it supports resource-based and code-based dialog creation, multi-monitor awareness, and MDI child dialogs.

Control System (TControl)

TControl inherits from TWindow at source/classes/control.prg#L60 and serves as the base for all visual controls. It adds:

  • bSetGet — bidirectional data binding code block
  • VarGet() / VarPut() — read/write bound variables
  • lDrag — design-time drag-and-drop support
  • nDlgCode — keyboard navigation behavior

Preprocessor Command DSL

One of FWH's most distinctive innovations is its preprocessor-based DSL defined in [include/fivewin.ch](file:///c:/fwteam/include/fivewin.ch) (108 KB, 2,433 lines). It translates declarative xBase-style commands into OOP method calls:

Code: Select all | Expand

// User writes this declarative command:
@ 10, 10 BUTTON oBtn PROMPT "Click Me" ;
   SIZE 100, 30 ;
   ACTION MsgInfo("Hello!") ;
   OF oDlg

// Preprocessor translates it to:
oBtn := TButton():New( 10, 10, "Click Me", oDlg, ;
   {|| MsgInfo("Hello!")}, 100, 30, ... )

Event / Callback Flow

sequenceDiagram participant User participant Windows OS participant TWindow participant TControl participant CodeBlock User->>Windows OS: Mouse Click / Key Press Windows OS->>TWindow: WndProc → HandleEvent() TWindow->>TControl: Command() dispatch by nId TControl->>CodeBlock: Eval( bAction / bLClicked ) CodeBlock-->>TControl: Return value TControl->>TControl: Refresh() / VarPut() TControl-->>TWindow: Update parent TWindow-->>User: Visual feedback

Data Binding Pattern

FWH uses a code-block-based data binding pattern through bSetGet. Each control can bind to any Harbour variable using a two-way code block:

Code: Select all | Expand

// bSetGet binds a control to a variable:
@ 10, 10 GET oGet VAR cName OF oDlg
// Internally creates: bSetGet := {|u| If( u == nil, cName, cName := u )}
// VarGet() calls Eval( bSetGet )       → reads cName
// VarPut(x) calls Eval( bSetGet, x )   → writes cName

Design Patterns

PatternImplementationExample
CompositeaControls[] in TWindow/TControlParent windows contain child controls
Observer/StrategyCode blocks bAction, bWhen, bValidEvent callbacks as interchangeable blocks
Template MethodTWindow defines flow, subclasses overridePaint(), HandleEvent()
FactoryNew() and Redefine() constructorsCreate from code or from resource
BridgeHarbour ↔ C via HB_FUNC()WndHandleEvent() in C, called from Harbour
FacadeSimplified API over complex Win32::Center() wraps WndCenterEx()
CommandDSL preprocessor translates to objects#xcommand @ ... BUTTON

Data Access Layer

📄 Relevant source files

[source/classes/database.prg](file:///c:/fwteam/source/classes/database.prg) — TDatabase abstraction for DBF
[source/classes/todbc.prg](file:///c:/fwteam/source/classes/todbc.prg) — TODBC class for ODBC connectivity
[source/classes/trecset.prg](file:///c:/fwteam/source/classes/trecset.prg) — TRecSet for ADO RecordSets
[source/internal/fwmaria.prg](file:///c:/fwteam/source/internal/fwmaria.prg) — MariaDB/MySQL client (390 KB)
source/classes/xbrowse.prg#L496-533 — Data source adapters in TXBrowse

This page describes FWH's data access capabilities. FWH supports multiple database backends through a consistent adapter API. For the grid control that visualizes data see TXBrowse — Advanced Data Grid.

Data Access Architecture

graph TD App["Application Code"] --> XBrw["TXBrowse Grid"] App --> DB["TDatabase (DBF)"] XBrw --> RDD["SetRDD() — DBF via RDD"] XBrw --> ARR["SetArray() — In-memory arrays"] XBrw --> ADO["SetAdo() — ADO RecordSets"] XBrw --> MYSQL["SetMySql() — MySQL/MariaDB"] XBrw --> PG["SetPostGre() — PostgreSQL"] XBrw --> DLP["SetDolphin() — Dolphin queries"] XBrw --> EGL["SetEagle() — Eagle engine"] RDD --> DBFN["DBF Native"] ADO --> ODBC["ODBC / SQL Server"] MYSQL --> Maria["MariaDB / MySQL Server"] PG --> PGS["PostgreSQL Server"]

Database Connector Summary

ClassFileSizeBackend
TDatabase[source/classes/database.prg](file:///c:/fwteam/source/classes/database.prg)—DBF native via RDD
FWMaria[source/internal/fwmaria.prg](file:///c:/fwteam/source/internal/fwmaria.prg)390 KBMariaDB / MySQL
TODBC[source/classes/todbc.prg](file:///c:/fwteam/source/classes/todbc.prg)—ODBC
TRecSet[source/classes/trecset.prg](file:///c:/fwteam/source/classes/trecset.prg)—ADO RecordSet
TDbODBC[source/classes/tdbodbc.prg](file:///c:/fwteam/source/classes/tdbodbc.prg)—ODBC with DBF-like API
TDataRow[source/classes/datarow.prg](file:///c:/fwteam/source/classes/datarow.prg)90 KBRecord-level abstraction
TArrData[source/classes/tarrdata.prg](file:///c:/fwteam/source/classes/tarrdata.prg)—Array-as-database

UI Controls

📄 Relevant source files

source/classes/xbrowse.prg#L130-800 — TXBrowse class (19,420 lines, 621 KB)
[source/classes/tget.prg](file:///c:/fwteam/source/classes/tget.prg) — TGet input control (165 KB)
[source/classes/fget.prg](file:///c:/fwteam/source/classes/fget.prg) — TFGet extended input (154 KB)
[source/classes/tribbon.prg](file:///c:/fwteam/source/classes/tribbon.prg) — TRibbon (72 KB)
[source/classes/menu.prg](file:///c:/fwteam/source/classes/menu.prg) — TMenu system (99 KB)

This page covers FWH's major UI control classes. All controls inherit from TControl (see Core Architecture).

TXBrowse — Advanced Data Grid

TXBrowse is the most substantial class in the framework at 19,420 lines / 621 KB, defined at source/classes/xbrowse.prg#L130. It is an advanced data grid supporting:

  • Multiple data sources: DBF (RDD), arrays, ADO, MySQL, PostgreSQL, Dolphin, Eagle
  • Column management: freeze, swap, hide, auto-fit, group headers, formulas
  • Export: Excel, Calc, CSV, DBF, HTML, Word, PDF
  • UI features: kinetic scrolling, multi-select, incremental search/filter, editable cells
  • State persistence: SaveState() / RestoreState() for column layout

Major Controls

ControlFileSizeDescription
TXBrowse[xbrowse.prg](file:///c:/fwteam/source/classes/xbrowse.prg)621 KBAdvanced data grid with 200+ methods
TGet[tget.prg](file:///c:/fwteam/source/classes/tget.prg)165 KBEnhanced GET input field
TFGet[fget.prg](file:///c:/fwteam/source/classes/fget.prg)154 KBExtended GET with formatting
TWindow[window.prg](file:///c:/fwteam/source/classes/window.prg)131 KBBase window class (100+ methods)
TGraph[tgraph.prg](file:///c:/fwteam/source/classes/tgraph.prg)113 KBCharts and graphs
TScintilla[scintila.prg](file:///c:/fwteam/source/classes/scintila.prg)176 KBCode editor (Scintilla)
TRichEdit5[triched5.prg](file:///c:/fwteam/source/classes/triched5.prg)101 KBModern RichEdit control
TMenu[menu.prg](file:///c:/fwteam/source/classes/menu.prg)99 KBMenu system
TDataRow[datarow.prg](file:///c:/fwteam/source/classes/datarow.prg)90 KBRecord-level data handling
TRibbon[tribbon.prg](file:///c:/fwteam/source/classes/tribbon.prg)72 KBOffice-style Ribbon UI
TWBrowse[wbrowse.prg](file:///c:/fwteam/source/classes/wbrowse.prg)84 KBClassic browse control

Object Lifecycle

stateDiagram-v2 [*] --> Created : New() / Redefine() Created --> Initiated : Initiate(hDlg) Initiated --> Active : SetFocus() / Show() Active --> Editing : SetColumns() / FastEdit Editing --> Active : CancelEdit() / Valid Active --> Refreshed : Refresh() Refreshed --> Active Active --> Destroyed : End() Destroyed --> [*]

Quantitative Metrics

MetricValue
Source files (.prg)460+
Source files (.c/.cpp)240+
Header files (.ch/.h)102
Harbour classes (desktop)256
Harbour classes (Windows CE)50
Sample/example files3,487
Changelog lines (whatsnew.txt)25,865
Main header size (fivewin.ch)108 KB / 2,433 lines
Largest source file[xbrowse.prg](file:///c:/fwteam/source/classes/xbrowse.prg) (621 KB / 19,420 lines)
Makefile variants9
Years of active development33 (1993–2026)
Current versionFWH 25.12

Recommendations

High Priority 🔴

  • Refactor [xbrowse.prg](file:///c:/fwteam/source/classes/xbrowse.prg) (621 KB / 19,420 lines): split into rendering, editing, data sources, export, and state modules
  • Refactor [fwmaria.prg](file:///c:/fwteam/source/internal/fwmaria.prg) (390 KB): separate connection management, query execution, and schema operations

Medium Priority 🟡

  • Add unit tests: implement a formal testing framework (hbtest or similar) beyond the 3,487 samples
  • API documentation: auto-generate docs from #xcommand directives in [fivewin.ch](file:///c:/fwteam/include/fivewin.ch)

Low Priority 🟢

  • Unify AI classes: create a common TLLM base class for TChatGPT, TOllama, TGemini, TDeepSeek, TKimi
  • CI pipeline: automate multi-compiler builds to catch regressions early

Conclusion

Quality Score: 8.2 / 10

CategoryScore
Functional completeness9.5
Code quality7.5
Architecture8.0
Documentation7.0
Testing6.5
Innovation9.0
Backward compatibility9.5
Active evolution9.0

FWH is an exceptionally mature and comprehensive framework. Its 33-year codebase maintains remarkable architectural consistency while continuously adopting modern technologies — from WebView2 to native AI model integration. The preprocessor-based DSL anticipates decades of DSL-oriented design trends. The main challenge is the scale of a few monolithic files, but the overall coherence is commendable.