Logo de Skill Debug

Skill Debug

Comunidade
javiarmesto
skill-debug

AL debugging and diagnostics for Business Central. Use when performing snapshot debugging, CPU profiling, analyzing telemetry, or troubleshooting runtime issues.

Visão geral

Publicado porjaviarmesto
RepositórioALDC-AL-Development-Collection
Nome da habilidadeskill-debug
Estrelas
115
Forks
37
Arquivos incluídos
Somente instruções
LicençaMIT
Links
  • Instruções em Markdown

    Um arquivo SKILL.md que o modelo carrega sob demanda, consumindo tokens apenas quando uma solicitação é realmente relevante para a habilidade.

  • Funciona com qualquer LLM

    Habilidades de IA são Markdown simples, não código específico de um provedor, por isso funcionam com GPT, Claude, Gemini, Grok ou um modelo local.

  • Completa em si mesma

    Tudo de que o modelo precisa está nas instruções — sem arquivos extras para sincronizar.

  • Código aberto

    Publicada por javiarmesto no GitHub. Leia o conteúdo-fonte antes de instalar.

Instalação

Instale a habilidade de IA Skill Debug no TypingMind para usá-la com qualquer LLM ou adicione-a a outro agente que leia SKILL.md.

1

Instalar no TypingMind

O TypingMind instala uma habilidade diretamente da pasta dela no GitHub — lê o arquivo SKILL.md, reúne os arquivos de recursos em um pacote e armazena o resultado localmente.

  1. Abra o app e vá para Plugins → Habilidades.
  2. Escolha "Instalar do GitHub".
  3. Cole a URL da pasta da habilidade exibida abaixo e confirme.
    https://github.com/javiarmesto/ALDC-AL-Development-Collection/tree/main/.claude/skills/skill-debug
  4. Ative a habilidade em cada chat em que quiser disponibilizá-la.
Plugins → Habilidades → Nova habilidade → Via URL GitHub, depois cole a URL da pasta e pressione Continuar.
2

Instalar em outro agente

Qualquer agente que leia o formato Agent Skills pode usar esta habilidade — copie a pasta para o diretório de habilidades desse agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/javiarmesto/ALDC-AL-Development-Collection.git /tmp/ALDC-AL-Development-Collection
mkdir -p .claude/skills
cp -r /tmp/ALDC-AL-Development-Collection/.claude/skills/skill-debug .claude/skills/skill-debug
Reinicie Claude Code após copiar para que a nova habilidade seja reconhecida.

Use no TypingMind

Ative Skill Debug em qualquer chat do TypingMind e o modelo cuida do resto. O nome e a descrição da habilidade ficam no prompt do sistema e, assim que uma solicitação relevante aparece, o modelo carrega as instruções completas automaticamente — sem precisar de acionamento manual e sem consumir tokens até que ela seja realmente usada.

O modelo carrega Skill Debug automaticamente assim que uma solicitação é relevante para essa habilidade.

Funciona com qualquer modelo de IA

Habilidades de IA são instruções em Markdown simples, não código específico de um provedor. Por isso, Skill Debug não fica vinculada ao modelo para o qual foi criada. Instale-a uma vez no TypingMind e use-a com GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama ou um modelo local executado por conta própria — tudo com suas próprias chaves de API.

  • Carregada apenas quando necessário

    O prompt do sistema contém apenas o nome e a descrição. As instruções são buscadas na primeira solicitação relevante, então uma habilidade sem uso não gera custo.

  • Troque de modelo durante a conversa

    Como a habilidade é composta de instruções, não de código, trocar de modelo não afeta seu funcionamento — o próximo modelo lê o mesmo arquivo SKILL.md.

Instruções da habilidade

Este é o conteúdo de SKILL.md que o modelo carrega. Leia antes de instalar — uma habilidade é um conjunto de instruções que seu modelo seguirá.

Skill: AL Debugging & Diagnostics

Purpose

For BC29 AL0926 section-order errors or new isolation behavior, read the relevant sections of AL18 capability checks. Use actual compiler/runtime evidence and keep compilation distinct from execution.

Systematic diagnosis and root cause analysis for AL Business Central issues: runtime errors, logic bugs, intermittent failures, performance bottlenecks, and configuration problems.

When to Load

This skill should be loaded when:

  • A runtime error, exception, or unexpected behavior is reported
  • A logic bug needs root cause analysis (not just a symptom fix)
  • An intermittent issue needs snapshot capture
  • A performance bottleneck needs CPU profiling
  • Configuration issues (auth, symbols, build, publishing) block development
  • An event subscriber is not firing as expected

Core Patterns

Pattern 1: Choose Debugging Strategy

Select the right tool before starting:

Issue TypeStrategyTool
Consistent runtime errorStandard debuggeral_debug
Already deployed codeDebug without publishal_debug
Rapid dev cycleIncremental publishal_publish (incremental)
Intermittent / hard-to-reproduceSnapshot debuggingal_snapshotdebugging
Slow performanceCPU profilingVS Code command (not an agent tool)
Auth / symbols / buildConfiguration troubleshootSee Workflow Step 2b
Copilot AI featureAgent session debuglaunch.json with clientType: Agent

Pattern 2: Data Flow Tracing

Scenario: "Value is wrong after posting"

1. Set breakpoint at final location (where value is wrong)
2. Work backwards to find where value is set
3. Use `usages` tool to find all assignments
4. Set breakpoints at each assignment point
5. Step through to find which execution path is taken
6. Inspect conditions and variable states at each point

Pattern 3: Event Subscriber Not Firing

Scenario: "My event subscriber doesn't execute"

1. Verify subscriber signature exactly matches publisher (name, parameters, types)
2. Check SkipOnMissingLicense and SkipOnMissingPermission attributes
3. Confirm the extension containing the publisher is active and published
4. Set breakpoint inside subscriber body
5. Verify the publisher event is actually being raised (breakpoint in publisher)
6. Check if IsHandled = true is set before your subscriber runs
7. Inspect subscriber execution order (EventPriority)

Pattern 4: Performance Bottleneck

al
// ❌ N+1 pattern — common cause of slow pages
repeat
    Item.Get(SalesLine."No.");      // DB call inside loop
    SalesLine.Amount := Item.Price * SalesLine.Quantity;
until SalesLine.Next() = 0;

// ✅ Use SetLoadFields + single pass
SalesLine.SetLoadFields("No.", Quantity, Amount);
if SalesLine.FindSet() then
    repeat
        // ...
    until SalesLine.Next() = 0;

CPU profile analysis focus:

  • Top time-consuming procedures (hotspots)
  • Frequently called procedures in loops
  • Expensive database operations
  • FlowField CalcFormula complexity

Pattern 5: Snapshot Debugging for Intermittent Issues

⚠️ HUMAN GATE: Snapshots may capture sensitive runtime data.
Before initializing:
1. Confirm what data will be captured
2. Security review for sensitive information
3. Obtain explicit user approval

Commands (one tool — `al_snapshotdebugging` — covers initialize / finish / view):
  al_snapshotdebugging (initialize)   ← start capture session
  [reproduce scenario 10-20 times]
  al_snapshotdebugging (finish)       ← end capture
  al_snapshotdebugging (view)         ← view and compare

Compare snapshots between success and failure cases:
- Variable values at failure point
- Timing differences
- Execution paths taken
- Data state variations

Workflow

Step 1: Context Gathering (MANDATORY before any debugging)

Read existing plans context first:

.claude/plans/memory.md              ← project state and recent decisions
.claude/plans/*-diagnosis.md         ← previous debug sessions (similar issues)

Gather issue information:

  • What is the expected behavior vs actual behavior?
  • When does it happen: always / sometimes / specific conditions?
  • Exact error message and stack trace
  • Recent code changes (potential regression source)
  • User/permission set and environment where it occurs

Stop criterion: can reproduce the issue consistently (≥80% success rate).

Step 2a: Isolate the Problem (Runtime / Logic)

  1. Narrow down scope with search and usages tools
  2. Identify suspect objects (tables, pages, codeunits, event subscribers)
  3. Attach debugger with selected strategy (Pattern 1)
  4. Set strategic breakpoints:
    • Just before the error occurs
    • At data modification points
    • In event subscribers and validation triggers
  5. Inspect: variable values, record filters, call stack, parameter values
  6. Step execution: F10 (step over), F11 (step into), Shift+F11 (step out)

Step 2b: Configuration Troubleshooting

Authentication failures (401/403, cannot download symbols):

⚠️ HUMAN GATE: Clearing credentials disconnects active sessions.
Confirm impact and obtain approval before clearing the credentials cache
(a VS Code command, not an agent tool).
Then re-authenticate and verify launch.json authentication method.

Missing symbols (unresolved references, red squiggles):

al_downloadsymbols                      ← first attempt
al_downloadsymbols (globalSourcesOnly)  ← if no BC server connection is available
al_build                                ← verify compilation

Check app.json dependencies version alignment.

Build errors — common codes:

  • AL0896 — Recursive FlowField: map dependency graph, break circular chain
  • AL0185 — Object ID conflict: check ID range in app.json, no duplicates
  • AL0118 — Field length mismatch: align extension field length with base table

Publishing failures: check environment connectivity, extension version increment, dependency resolution via al_packages.

Step 3: Diagnose Root Cause

Identify the exact point of failure and — critically — WHY it occurs:

Common AL root causes by scenario:

SymptomRoot Cause Candidates
Record Not FoundWrong key values, filters blocking read, wrong company context, permission on read
FlowField wrong valueCalcFields not called, incorrect CalcFormula filters, circular dependency (AL0896)
OnValidate not firingDirect assignment without Validate(), IsHandled = true in subscriber, disabled trigger
Custom event not firingSignature mismatch, wrong ObjectType/ObjectId, publisher not raising event, compilation error in subscriber
Slow pageMissing SetLoadFields, N+1 loop, FlowField CalcFormula too complex, missing index/key
Intermittent failureRace condition, timing dependency, data-state dependency, environment-specific

Step 4: Document Diagnosis (MANDATORY)

Create .claude/plans/<issue-kebab-case>-diagnosis.md before proposing any fix:

markdown
# Debug Session: <Issue Title>

**Date**: YYYY-MM-DD
**Severity**: Critical / High / Medium / Low
**Status**: Investigating → Diagnosed → Fixed → Verified

## Issue Summary
[Brief description]

## Symptoms
- Expected: [what should happen]
- Actual: [what happens — include exact error text]

## Reproduction Steps
1. [Step]
2. [Step]
**Reproducibility**: Always / Sometimes / Rare

## Root Cause
[Technical explanation with evidence — code snippet, line reference]

## Recommended Fix
[Specific solution. Short-term hotfix + long-term if needed]

## Testing Strategy
- Unit: [what to mock/test]
- Regression: [related functionality to verify]

## Next Steps
1. [Action]
2. [Action]

File naming: sales-posting-error-diagnosis.md, slow-customer-list-diagnosis.md.

Step 5: Propose Fix & Handoff (MANDATORY HITL gate)

  1. Design fix addressing root cause (never symptoms only)
  2. Consider edge cases and side effects
  3. PAUSE — present diagnosis and proposed fix to user for approval
  4. After approval: handoff implementation to al-developer (simple) or via al-conductor TDD cycle (complex refactor)
  5. After fix: run tests, re-profile if performance issue, verify regression scenarios

Clean up: remove debugging artifacts, breakpoints, and temporary logging from code.

References

Constraints

  • This skill covers diagnosis and root cause analysis only — code changes are implemented by al-developer or via al-conductor
  • NEVER guess solutions without evidence from debugging tools
  • NEVER skip Step 4 (diagnosis document) for non-trivial issues (>5 min investigation)
  • NEVER proceed to fix without user approval (Step 5 HITL gate)
  • NEVER leave debugging code, breakpoints, or temporary logging in production code
  • Performance deep-dive (SetLoadFields, FlowField patterns, query optimization) → load skill-performance.md
  • Event publisher/subscriber design patterns → load skill-events.md
  • Permission set generation → load skill-permissions.md

Perguntas frequentes

O que a habilidade de IA Skill Debug faz?

AL debugging and diagnostics for Business Central. Use when performing snapshot debugging, CPU profiling, analyzing telemetry, or troubleshooting runtime issues.

Por que usar Skill Debug no TypingMind?

Porque basta instalar uma vez para usar com qualquer modelo. Skill Debug é escrito em Markdown simples, e não em código específico de um provedor, então a mesma habilidade funciona com GPT-5, Claude, Gemini, Grok ou um modelo local — e é possível trocar de modelo no meio do chat sem que ela deixe de funcionar. O TypingMind usa suas próprias chaves de API, então o pagamento é feito diretamente aos provedores, em vez de uma assinatura por licença de usuário, e suas habilidades e chats permanecem no seu próprio armazenamento.

Como instalar Skill Debug no TypingMind?

Abra Plugins → Habilidades → Instalar do GitHub no TypingMind e cole https://github.com/javiarmesto/ALDC-AL-Development-Collection/tree/main/.claude/skills/skill-debug. O TypingMind lê o arquivo SKILL.md e instala a habilidade para que possa ser ativada em cada chat.

Quais modelos de IA podem usar Skill Debug?

Qualquer modelo conectado no TypingMind. As habilidades de IA são instruções em Markdown simples, e não código específico de um provedor. Assim, GPT, Claude, Gemini, Grok e modelos locais podem carregar esta habilidade quando uma solicitação corresponder a ela.

Quantos modelos de IA posso usar com Skill Debug?

Quantos quiser. Desde que o modelo ofereça suporte a habilidades, é possível usar Skill Debug com ele — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e outros — tudo no TypingMind com suas próprias chaves de API.

A habilidade de IA Skill Debug é gratuita?

Sim. A habilidade é publicada no GitHub por javiarmesto sob a licença MIT. O pagamento é feito apenas ao seu provedor de IA pelos tokens usados.

O que são habilidades de IA?

Uma habilidade de IA é um conjunto reutilizável de instruções que ensina um modelo de IA a realizar uma tarefa específica. Ela segue o formato aberto Agent Skills: um arquivo SKILL.md com nome e descrição, além de scripts, modelos de documento ou arquivos de referência de que o modelo possa precisar. O modelo lê as instruções apenas quando sua solicitação corresponde à habilidade, então uma habilidade instalada não gera custos até ser usada.

Qual é a diferença entre habilidades de IA e plugins ou servidores MCP?

Um plugin ou servidor MCP oferece ao modelo novas ferramentas para chamar — código que é executado em algum lugar e retorna um resultado. Já uma habilidade de IA fornece conhecimento e um processo ao modelo: como abordar uma tarefa, quais etapas seguir e como deve ser um bom resultado. As habilidades são escritas em Markdown simples, por isso não precisam de servidor, chave de API nem ambiente de execução, e funcionam com qualquer modelo.

Ver todos

Crie seu próprio espaço de IA agora

Inscreva-se na nossa newsletter para receber novidades sobre recursos e futuros sorteios 👇