# Arquitectura de Claw-Code en Pseudocódigo Harbour
Basado en la documentación del repositorio `claw-code`, aquí está el pseudocódigo en Harbour que ilustra su arquitectura:
```harbour// Definición de la estructura principal del sistema
CLASS ClawCodeHarness
VAR oRuntime // Runtime crate - cerebro del sistema
VAR oApi // API crate - clientes provider
VAR oTools // Tools crate - herramientas integradas
VAR oPlugins // Plugins crate - extensibilidad
VAR oCommands // Commands crate - comandos slash
METHOD New()
::oRuntime := Runtime():New()
::oApi := Api():New()
::oTools := Tools():New()
::oPlugins := Plugins():New()
::oCommands := Commands():New()
RETURN Self
// Flujo principal de ejecución
METHOD Execute( cUserInput )
LOCAL oSession := ::oRuntime:CreateSession()
LOCAL oWorker := ::oRuntime:SpawnWorker( oSession )
DO CASE
CASE ::IsPromptCommand( cUserInput )
RETURN ::HandlePrompt( oWorker, cUserInput )
CASE ::IsSlashCommand( cUserInput )
RETURN ::oCommands:Execute( cUserInput, oSession )
OTHERWISE
RETURN ::HandleRepl( oWorker, cUserInput )
ENDCASE
ENDCLASS
// Máquina de estados del Worker
CLASS Worker
VAR nStatus // WorkerStatus enum
VAR oSession
VAR cTrustState
METHOD New()
::nStatus := WORKER_SPAWNING
::cTrustState := "pending"
RETURN Self
METHOD TransitionTo( nNewStatus )
::nStatus := nNewStatus
::EmitLaneEvent( nNewStatus )
ENDCLASS
// Definición de estados del worker
#define WORKER_SPAWNING 1
#define WORKER_TRUST_REQUIRED 2
#define WORKER_READY_FOR_PROMPT 3
#define WORKER_PROMPT_ACCEPTED 4
#define WORKER_RUNNING 5
#define WORKER_BLOCKED 6
#define WORKER_FINISHED 7
#define WORKER_FAILED 8
// Sistema de eventos estructurados
CLASS LaneEvent
VAR cEventName // lane.started, lane.ready, lane.blocked, etc.
VAR cStatus // success, failure, pending
VAR oBlocker // tipo de bloqueo si aplica
VAR cDetails // detalles adicionales
METHOD New( cName, cStatus, oBlocker, cDetails )
::cEventName := cName
::cStatus := cStatus
::oBlocker := oBlocker
::cDetails := cDetails
ENDCLASS
// Runtime - cerebro del sistema
CLASS Runtime
VAR oSessionStore
VAR oPermissionEnforcer
VAR oMcpManager
VAR oWorkerRegistry
METHOD CreateSession()
LOCAL oSession := Session():New()
::oSessionStore:Add( oSession )
RETURN oSession
METHOD SpawnWorker( oSession )
LOCAL oWorker := Worker():New()
// Secuencia de boot del worker
oWorker:TransitionTo( WORKER_SPAWNING )
IF ::CheckTrustRequired( oSession )
oWorker:TransitionTo( WORKER_TRUST_REQUIRED )
IF ::AutoResolveTrust( oSession )
oWorker:TransitionTo( WORKER_READY_FOR_PROMPT )
ENDIF
ELSE
oWorker:TransitionTo( WORKER_READY_FOR_PROMPT )
ENDIF
::oWorkerRegistry:Register( oWorker )
RETURN oWorker
ENDCLASS
// Sistema de herramientas
CLASS Tools
VAR aToolSpecs // array de especificaciones de herramientas
METHOD New()
::LoadBuiltinTools()
::LoadPluginTools()
ENDCLASS
METHOD ExecuteTool( cToolName, hParams )
LOCAL oTool := ::FindTool( cToolName )
IF oTool != NIL
RETURN oTool:Execute( hParams )
ENDIF
RETURN NIL
ENDCLASS
// Ejemplo de herramienta integrada
CLASS BashTool
METHOD Execute( hParams )
LOCAL cCommand := hParams["command"]
LOCAL nPermission := ::CheckPermission( cCommand )
IF nPermission == PERMISSION_DENIED
RETURN CreateErrorResult( "Permission denied" )
ENDIF
RETURN ::ExecuteBashCommand( cCommand )
ENDCLASS
ENDCLASS
// Punto de entrada principal
FUNCTION Main()
LOCAL oClaw := ClawCodeHarness():New()
LOCAL cInput
DO WHILE .T.
cInput := GetUserInput()
IF cInput == "quit"
EXIT
ENDIF
oClaw:Execute( cInput )
ENDDO
RETURN NIL```
## Notas
Este pseudocódigo Harbour ilustra los componentes clave de la arquitectura claw-code:
1. **Estructura modular en crates** - `runtime`, `api`, `tools`, `plugins`, `commands` [1](#0-0)
2. **Máquina de estados del worker** - transición desde `Spawning` hasta `Finished/Failed` [2](#0-1)
3. **Sistema de eventos estructurados** - `LaneEvent` para orquestación [3](#0-2)
4. **Runtime como cerebro** - gestiona sesiones, permisos, y ciclo de vida [4](#0-3)
5. **Sistema de herramientas** - 40 herramientas expuestas incluyendo bash, file ops, etc. [5](#0-4)
El pseudocódigo mantiene la filosofía "clawable" de ejecución determinista, legible por máquina y recuperable sin intervención humana.
Wiki pages you might want to explore:
- [Overview (instructkr/claw-code)](/wiki/instructkr/claw-code#1)
- [Lane Orchestration & Roadmap (instructkr/claw-code)](/wiki/instructkr/claw-code#8)
### Citations
**File:** rust/README.md (L179-206)
```markdown```text
rust/
├── Cargo.toml # Workspace root
├── Cargo.lock
└── crates/
├── api/ # Provider clients + streaming + request preflight
├── commands/ # Shared slash-command registry + help rendering
├── compat-harness/ # TS manifest extraction harness
├── mock-anthropic-service/ # Deterministic local Anthropic-compatible mock
├── plugins/ # Plugin metadata, manager, install/enable/disable surfaces
├── runtime/ # Session, config, permissions, MCP, prompts, auth/runtime loop
├── rusty-claude-cli/ # Main CLI binary (`claw`)
├── telemetry/ # Session tracing and usage telemetry types
└── tools/ # Built-in tools, skill resolution, tool search, agent runtime surfaces```
### Crate Responsibilities
- **api** — provider clients, SSE streaming, request/response types, auth (API key + OAuth bearer), request-size/context-window preflight
- **commands** — slash command definitions, parsing, help text generation, JSON/text command rendering
- **compat-harness** — extracts tool/prompt manifests from upstream TS source
- **mock-anthropic-service** — deterministic `/v1/messages` mock for CLI parity tests and local harness runs
- **plugins** — plugin metadata, install/enable/disable/update flows, plugin tool definitions, hook integration surfaces
- **runtime** — `ConversationRuntime`, config loading, session persistence, permission policy, MCP client lifecycle, system prompt assembly, usage tracking
- **rusty-claude-cli** — REPL, one-shot prompt, direct CLI subcommands, streaming display, tool call rendering, CLI argument parsing
- **telemetry** — session trace events and supporting telemetry payloads
- **tools** — tool specs + execution: Bash, ReadFile, WriteFile, EditFile, GlobSearch, GrepSearch, WebSearch, WebFetch, Agent, TodoWrite, NotebookEdit, Skill, ToolSearch, and runtime-facing tool discovery
```
**File:** ROADMAP.md (L75-87)
```markdown
## Phase 1 — Reliable Worker Boot
### 1. Ready-handshake lifecycle for coding workers
Add explicit states:
- `spawning`
- `trust_required`
- `ready_for_prompt`
- `prompt_accepted`
- `running`
- `blocked`
- `finished`
- `failed````
**File:** rust/crates/runtime/src/lib.rs (L1-6)
```rust//! Core runtime primitives for the `claw` CLI and supporting crates.
//!
//! This crate owns session persistence, permission evaluation, prompt assembly,
//! MCP plumbing, tool-facing file operations, and the core conversation loop
//! that drives interactive and one-shot turns.```
**File:** PARITY.md (L145-151)
```markdown## Tool Surface: 40 exposed tool specs on `main`
- `mvp_tool_specs()` in `rust/crates/tools/src/lib.rs` exposes **40** tool specs.
- Core execution is present for `bash`, `read_file`, `write_file`, `edit_file`, `glob_search`, and `grep_search`.
- Existing product tools in `mvp_tool_specs()` include `WebFetch`, `WebSearch`, `TodoWrite`, `Skill`, `Agent`, `ToolSearch`, `NotebookEdit`, `Sleep`, `SendUserMessage`, `Config`, `EnterPlanMode`, `ExitPlanMode`, `StructuredOutput`, `REPL`, and `PowerShell`.
- The 9-lane push replaced pure fixed-payload stubs for `Task*`, `Team*`, `Cron*`, `LSP`, and MCP tools with registry-backed handlers on `main`.
- `Brief` is handled as an execution alias in `execute_tool()`, but it is not a separately exposed tool spec in `mvp_tool_specs()`.```