@startuml
!theme plain
skinparam componentStyle rectangle

title SmartTools Registry - Resolution & Caching Architecture

actor User
box "Local Environment" #LightBlue
  participant "CLI" as CLI
  participant "Local\nTools" as Local
  participant "Global\nTools" as Global
  participant "Cache" as Cache
end box

box "Registry Infrastructure" #LightGreen
  participant "API\nServer" as API
  database "SQLite\nDB" as DB
  participant "Gitea\nRepo" as Repo
end box

User -> CLI: smarttools install summarize

== Resolution Order ==
CLI -> Local: Check ./smarttools/summarize/
Local --> CLI: Not found

CLI -> Global: Check ~/.smarttools/summarize/
Global --> CLI: Not found

CLI -> Cache: Check cached registry index
Cache --> CLI: Found (age: 2 min)

CLI -> API: GET /tools/rob/summarize
API -> DB: Query tool + version
DB --> API: Tool metadata + YAML
API --> CLI: 200 OK + ETag + max-age=300

CLI -> Cache: Update cache entry
CLI -> Global: Write config.yaml
CLI -> Global: Generate wrapper script
CLI --> User: Installed rob/summarize v1.2.0

== Offline Scenario ==
User -> CLI: smarttools install translate
CLI -> Local: Check local
Local --> CLI: Not found
CLI -> Global: Check global
Global --> CLI: Not found
CLI -> Cache: Check cache
Cache --> CLI: Found translate v2.0.0
CLI -> API: GET /tools/rob/translate
API -[#red]-> CLI: Connection timeout
CLI -> Cache: Use stale cache (warn user)
CLI -> Global: Install from cache
CLI --> User: Installed rob/translate v2.0.0\n(warning: from cache, registry unavailable)

== Publishing Flow ==
User -> CLI: smarttools registry publish ./mytool/
CLI -> CLI: Validate YAML schema
CLI -> API: POST /tools (with token)
API -> API: Verify auth token
API -> Repo: Create branch\n(mytool-v1.0.0)
API -> Repo: Commit tool YAML
API -> Repo: Create PR
Repo --> API: PR #42 URL
API --> CLI: 201 Created\n{"pr_url": "..."}
CLI --> User: Tool submitted for review\nPR: https://gitea.brrd.tech/.../pulls/42

== Webhook Sync ==
Repo -> API: POST /webhook/gitea\n(PR merged event + HMAC sig)
API -> API: Verify HMAC signature
API -> Repo: git pull
API -> API: Parse tools/*.yaml
API -> DB: BEGIN TRANSACTION
API -> DB: INSERT/UPDATE tools
API -> DB: REBUILD search_index
API -> DB: COMMIT
API --> Repo: 200 OK

note right of DB
  Cache invalidation:
  - Clear index.json cache
  - Next API call regenerates
  - Clients get fresh data
end note

@enduml